qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
60,696,671
I have a class `Foo`, and I want to extend it dynamically with some literal object that I have. How can I keep the `this` typed **without manually repeating the keys** of the literal object in a separate interface? ```js const someLiteralObject = { key1: 'foo', key2: 'bar', // ...lots of more keys } class Foo { constructor(){ Object.assign(this, someLiteralObject) } test() { console.log(this.key1); //error: Property 'key1' does not exist on type 'Foo' } } const test = new Foo(); console.log(test.key1); //error: Property 'key1' does not exist on type 'Foo' ```
2020/03/15
[ "https://Stackoverflow.com/questions/60696671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4019513/" ]
EDIT: I suggest you to look into [Mixins in Typescript](https://www.typescriptlang.org/docs/handbook/mixins.html) and research the difference between `Object.assign` and `applyMixins` helper presented there. Perhaps that design pattern is what you actually need instead. Here's a dirty but strongly typed solution wit using a literal object and not repeating all it's keys as asked. Explanations inline and [TypeScript Playground link](https://www.typescriptlang.org/play?#code/PTAEAkEsBMFNQC4AtYGd4oDYAdYCdVQBDAdyIE9RIA7UcgewFc9QADRhSTVAOgVVahU9ALawSKPLAA0Q2PABGsTPRKgJRBIhSVo9HgChgAKmMHQx0AHFIANzSgAwvWqoEeRgGME9FgHM7WFoiKlcEImpPGVBMSABreBp7Anh6ADM2AEkwiKiAFXJcVkMLc0sAZVhPF2hQemxOFyJMUGwiPCIxBHwqQna-RjFqLQRGbEx4NN9teFZqsI9vXwAKAEpisrLQAAEfPW1IQhpuvDSiKJjzuMJUSD9qTWZJ6bdNSE9QLqR6aFRgbDw9XwnDQJWMwAMsAAHthfFpjvgzhdMs4Fl4fHgADx5UDQ7rUX51BQAKyqWgAvETSd5ZHkAIK4qH4wmMahxaiqagAbQAuqBKaz2ZzeQA+UAAb3MoGl1HEyx4Cv6qAAXKB6atVXkDABfIymLYAeWSeDwMAcIU8mCIqEIPlAUlGeGCoVekXgyE0oUtjDgtpQoAC9loIkgUJoYIh0NheBGhXgjitNoA6pBkABZUM0bGM5mEFEuNyLDG0jNh2h4oKE+gksli8lS6X5tFLLHZV35OPYsUAMjVpZoslRhfRvgACu1OrATqguyKDPOQKAGSGy58IpQEuQ+gTgNMvj9eKAAKroNgIOPpISiWAAGVT+GaBpr3kEdsYp9TxCOw0R51ghnmNwrzEO8TkfZ8KQlKVNwARlVAByKZ6Hg6RoNgcgACYEIUdoUJ1L9QEArRQEXTEAFoyLYa1CILBBBEOOoGkgJpMFkBQOFAJAImgchDCMMBWGQQ5lVfONEGUbhPinb5agRJ1miEapcG0T1BKQQ56MIERfHdLjaDycoDjZQgFF0WAzkYTAEAAxNCAAMXoehRyeKDpRo5sMTWSU3Lcp9qWs61bnuZYhNQWRhBA+8OkwPyyVWBtdTc7o3BC9SVQOQhe3PXBLwi28ovA-zVlctzAPoCYeBUPxUsOHhYPitzdV1Rc6QJNgE0ClN00zahROU7pMEk5oWnoZAemqOAcNPD0tFYBz6E0z4dJU2g5scqBoDgXqANo0B5v5PbHOcqQCI65NUyQftqExbLYEvebjuiW7cuvUCHxiiC5340Ak18a4CKjMlYGgHawlAJCDtlNR5rWAwyoqqrliQur0Jg+LkeShBYctQLQAAIXaHNK3sxySqIosVmK7y3NQMZ8FhnzQr4NAsYa0Amrhgtyv-RGofx9o1nioA). ``` // Hide these helpers away in your `utils.ts` somewhere, see below what they do. /** * Gives Constructor given a instance, like inverse of `InstanceType`. * * Second optional parameter is argument tuple for the `constructor()`. * * @todo this interface lacks signature for static methods/properties. */ export interface IConstructor<T extends object = object, TA extends unknown[] = unknown[]> { new(...args: TA): T } /** * Overrrides a class to return a instance that includes the given mixin. */ export type ClassWithMixin<T extends IConstructor, TMixin extends object> = IConstructor<InstanceType<T> & TMixin, ConstructorParameters<T>> // A mixin many keys and/or methods. Use `typeof someLiteralObject` to use it as interface. const someLiteralObject = { key1: 'foo', key2: 'bar', } as const // <-- `as const` is optional, but handy. // `this:` type tells method internal scope that `this` is more than TS thinks by default. class FooPure { constructor(){ Object.assign(this, someLiteralObject) } test(this: this & typeof someLiteralObject) { console.log(this.key1) } } // And `ClassWithMixin` type tells all other codebase that `Foo` is more than `FooHidden`. const Foo = FooPure as ClassWithMixin<typeof FooPure, typeof someLiteralObject> // Works as expected. const foo = new Foo() console.log(foo.key1) foo.test() class Bar extends Foo { constructor() { super() this.test() } } console.log(new Bar()) ```
Strongly typed way: ``` class Some { // <= This is representing your Object key1: string; key2: string; } const someLiteralObject: Some = { // <= As you can see it is of type Some key1: 'foo', key2: 'bar', } class Foo extends Some { // <= Tell TS we are using all the keys from Some constructor(){ super(); // <= needed for ts, useless as we did not define a constructor in Some Object.assign(this, someLiteralObject); } test() { console.log(this.key1); // Yeah! } } const test = new Foo(); console.log(test.key1); // No error! test.test(); // works fine! ``` Hacky way (e.g. when you dont know what keys the object will have) ``` const someLiteralObject = { key1: 'foo', key2: 'bar', } class Foo { constructor(){ Object.assign(this, someLiteralObject) } test() { console.log((this as any).key1); // tell ts to be unsure about the type of this } } const test = new Foo(); console.log((test as any).key1); // tell ts to be unsure about the type of this ```
11,321,610
I am trying to use the return value(response) from the callback outside the jQuery.post API..how can that be done? ``` jQuery.post( ajaxurl, 'action', function( response ) { console.log(response); // this comes back with "working" // i tried this responseVal = response; but didn't work }); alert(response); // this will be undefined. ``` So I want the alert to have access to response....Yes I know I could easily alerted it inside the callback but my application needs to access this outside. Thanks in advance.
2012/07/04
[ "https://Stackoverflow.com/questions/11321610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
There is nothing wrong with their bitmap strategy. Just change the 'size' parameter based on the screen density. ``` DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); ``` Now muliply your `size`, `width`, `height`, `widthText`, and `heightText` values by `metrics.density`. That will treat them as dp values to produce the correct px value for the screen you are on. From the docs: > > The DisplayMetrics.density field specifies the scale factor you must > use to convert dp units to pixels, according to the current screen > density. On a medium-density screen, DisplayMetrics.density equals > 1.0; on a high-density screen it equals 1.5; on an extra high-density screen, it equals 2.0; and on a low-density screen, it equals 0.75. > This figure is the factor by which you should multiply the dp units on > order to get the actual pixel count for the current screen. > > > You'll have more control over the font rendering if you stick with the bitmaps.
The short answer to your question is, use density resources. If you are using a high density screen, but your bitmap in: `res/drawable-hdpi/` The long answer is, that screen density does not have a "silver bullet" so to speak and to have a successful app, you need to make sure your app works across all screens. Getting your image to render on one screen is easy, keeping that the same across multiple resolutions is a little trickier. This article does a great job of talking about some of the different methods and techniques you can use to make sure that your bitmap displays properly across all screens, and not just one. This article has some best practices and other information that you should be aware of, and that will make things easier for you: <http://developer.android.com/guide/practices/screens_support.html> Best of luck!
41,892,105
How can I get all the records for `findAll ()` service using pagination and `Spring Data JPA` when we do not apply filters it should return all the records rather than displaying it pagewise.I have `findAll (Pageable pageable)` service and calling it from custom repository. IS it possible to get all the records in one page only using pagination?
2017/01/27
[ "https://Stackoverflow.com/questions/41892105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7478215/" ]
``` public interface UserRepository extends PagingAndSortingRepository<User, Long> { //Page<User> findAll(Pageable pageable); is already in this repository. } ``` So just in case you want to find the first page of size 20 try: ``` Page<User> users = repository.findAll(new PageRequest(0, 20)); ``` If what you want to do is to get all entities on a single page, it doesn't make much sense but can be done in two steps: ``` int count = repository.count(); Page<User> users = repository.findAll(new PageRequest(0, count)); ``` `count()` comes from `CrudRepository` which is extended by `PagingAndSortingRepository`.
If you are using PagingAndSortingRepository and still want a list of "things", You can add a method `List<Thing> findBy()` If you have a RepositoryRestResource, it will be exposed as REST: `/things/search/findBy`
41,892,105
How can I get all the records for `findAll ()` service using pagination and `Spring Data JPA` when we do not apply filters it should return all the records rather than displaying it pagewise.I have `findAll (Pageable pageable)` service and calling it from custom repository. IS it possible to get all the records in one page only using pagination?
2017/01/27
[ "https://Stackoverflow.com/questions/41892105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7478215/" ]
``` public interface UserRepository extends PagingAndSortingRepository<User, Long> { //Page<User> findAll(Pageable pageable); is already in this repository. } ``` So just in case you want to find the first page of size 20 try: ``` Page<User> users = repository.findAll(new PageRequest(0, 20)); ``` If what you want to do is to get all entities on a single page, it doesn't make much sense but can be done in two steps: ``` int count = repository.count(); Page<User> users = repository.findAll(new PageRequest(0, count)); ``` `count()` comes from `CrudRepository` which is extended by `PagingAndSortingRepository`.
Use `CrudRepository` instead of `PagingAndSortingRepository` if you don't need paging
41,892,105
How can I get all the records for `findAll ()` service using pagination and `Spring Data JPA` when we do not apply filters it should return all the records rather than displaying it pagewise.I have `findAll (Pageable pageable)` service and calling it from custom repository. IS it possible to get all the records in one page only using pagination?
2017/01/27
[ "https://Stackoverflow.com/questions/41892105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7478215/" ]
``` public interface UserRepository extends PagingAndSortingRepository<User, Long> { //Page<User> findAll(Pageable pageable); is already in this repository. } ``` So just in case you want to find the first page of size 20 try: ``` Page<User> users = repository.findAll(new PageRequest(0, 20)); ``` If what you want to do is to get all entities on a single page, it doesn't make much sense but can be done in two steps: ``` int count = repository.count(); Page<User> users = repository.findAll(new PageRequest(0, count)); ``` `count()` comes from `CrudRepository` which is extended by `PagingAndSortingRepository`.
Now PageRequest constructor is protected and you cannot create with 'new'. You have to call static method: ``` PageRequest.of(int page, int size) PageRequest.of(int page, int size, @NotNull Sort sort) PageRequest.of(int page, int size, @NotNull Direction direction, @NotNull String... properties) ``` And solution looks like: ``` Page<User> users = repository.findAll(PageRequest.of(0, 20)); ``` And of course your UserRepository interface should be extends from PagingAndSortingRepository: ``` public interface UserRepository extends PagingAndSortingRepository<User, Long> ```
41,892,105
How can I get all the records for `findAll ()` service using pagination and `Spring Data JPA` when we do not apply filters it should return all the records rather than displaying it pagewise.I have `findAll (Pageable pageable)` service and calling it from custom repository. IS it possible to get all the records in one page only using pagination?
2017/01/27
[ "https://Stackoverflow.com/questions/41892105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7478215/" ]
``` public interface UserRepository extends PagingAndSortingRepository<User, Long> { //Page<User> findAll(Pageable pageable); is already in this repository. } ``` So just in case you want to find the first page of size 20 try: ``` Page<User> users = repository.findAll(new PageRequest(0, 20)); ``` If what you want to do is to get all entities on a single page, it doesn't make much sense but can be done in two steps: ``` int count = repository.count(); Page<User> users = repository.findAll(new PageRequest(0, count)); ``` `count()` comes from `CrudRepository` which is extended by `PagingAndSortingRepository`.
Step 1: In your repository,implement the interface JpaSpecificationExecutor, which as overloaded findAll method, which accepts the Specification Object and page object created above. ``` The method signature in interface is: Page<T> findAll(@Nullable Specification<T> spec, Pageable pageable); ``` The repository class looks like this: ``` @Repository public interface MyRepository extends CrudRepository<JobRecord, Long>, JpaSpecificationExecutor<JobRecord> { ``` Implement your custom specification with predicates ``` static Specification<JobRecord> findByParam1AndParam2AndParam3(String param1,String param2,String param3) { return (jobRecord, cq, builder) -> { List<Predicate> predicates = new ArrayList<>(); predicates.add(builder.equal(jobRecord.get("param1"), "param1")); predicates.add(builder.equal(jobRecord.get("param2"), "param2")); predicates.add(builder.equal(jobRecord.get("param3"), "param3")); // we can add sorting here cq.orderBy(cb.desc(jobRecord.get("submittedAt"))); // AND all predicates return builder.and(predicates.toArray(new Predicate[0])); }; } ``` Step 2: In your Service, create a Pageable page object as: ``` Pageable page = PageRequest.of(0, 5);// 0 is the firstResult and 5 is pageSize which we can fetch from queryParams ``` The findAll method can be used with pagination as:-- ``` List<Job> jobs = repository.findAll(findByParam1AndParam2AndParam3("param1","param2","param3"), page) .stream() .map(JobRecord::toModel) .collect(Collectors.toList()); return new JobList().jobList(jobs); ```
41,892,105
How can I get all the records for `findAll ()` service using pagination and `Spring Data JPA` when we do not apply filters it should return all the records rather than displaying it pagewise.I have `findAll (Pageable pageable)` service and calling it from custom repository. IS it possible to get all the records in one page only using pagination?
2017/01/27
[ "https://Stackoverflow.com/questions/41892105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7478215/" ]
Now PageRequest constructor is protected and you cannot create with 'new'. You have to call static method: ``` PageRequest.of(int page, int size) PageRequest.of(int page, int size, @NotNull Sort sort) PageRequest.of(int page, int size, @NotNull Direction direction, @NotNull String... properties) ``` And solution looks like: ``` Page<User> users = repository.findAll(PageRequest.of(0, 20)); ``` And of course your UserRepository interface should be extends from PagingAndSortingRepository: ``` public interface UserRepository extends PagingAndSortingRepository<User, Long> ```
If you are using PagingAndSortingRepository and still want a list of "things", You can add a method `List<Thing> findBy()` If you have a RepositoryRestResource, it will be exposed as REST: `/things/search/findBy`
41,892,105
How can I get all the records for `findAll ()` service using pagination and `Spring Data JPA` when we do not apply filters it should return all the records rather than displaying it pagewise.I have `findAll (Pageable pageable)` service and calling it from custom repository. IS it possible to get all the records in one page only using pagination?
2017/01/27
[ "https://Stackoverflow.com/questions/41892105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7478215/" ]
Now PageRequest constructor is protected and you cannot create with 'new'. You have to call static method: ``` PageRequest.of(int page, int size) PageRequest.of(int page, int size, @NotNull Sort sort) PageRequest.of(int page, int size, @NotNull Direction direction, @NotNull String... properties) ``` And solution looks like: ``` Page<User> users = repository.findAll(PageRequest.of(0, 20)); ``` And of course your UserRepository interface should be extends from PagingAndSortingRepository: ``` public interface UserRepository extends PagingAndSortingRepository<User, Long> ```
Use `CrudRepository` instead of `PagingAndSortingRepository` if you don't need paging
41,892,105
How can I get all the records for `findAll ()` service using pagination and `Spring Data JPA` when we do not apply filters it should return all the records rather than displaying it pagewise.I have `findAll (Pageable pageable)` service and calling it from custom repository. IS it possible to get all the records in one page only using pagination?
2017/01/27
[ "https://Stackoverflow.com/questions/41892105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7478215/" ]
Now PageRequest constructor is protected and you cannot create with 'new'. You have to call static method: ``` PageRequest.of(int page, int size) PageRequest.of(int page, int size, @NotNull Sort sort) PageRequest.of(int page, int size, @NotNull Direction direction, @NotNull String... properties) ``` And solution looks like: ``` Page<User> users = repository.findAll(PageRequest.of(0, 20)); ``` And of course your UserRepository interface should be extends from PagingAndSortingRepository: ``` public interface UserRepository extends PagingAndSortingRepository<User, Long> ```
Step 1: In your repository,implement the interface JpaSpecificationExecutor, which as overloaded findAll method, which accepts the Specification Object and page object created above. ``` The method signature in interface is: Page<T> findAll(@Nullable Specification<T> spec, Pageable pageable); ``` The repository class looks like this: ``` @Repository public interface MyRepository extends CrudRepository<JobRecord, Long>, JpaSpecificationExecutor<JobRecord> { ``` Implement your custom specification with predicates ``` static Specification<JobRecord> findByParam1AndParam2AndParam3(String param1,String param2,String param3) { return (jobRecord, cq, builder) -> { List<Predicate> predicates = new ArrayList<>(); predicates.add(builder.equal(jobRecord.get("param1"), "param1")); predicates.add(builder.equal(jobRecord.get("param2"), "param2")); predicates.add(builder.equal(jobRecord.get("param3"), "param3")); // we can add sorting here cq.orderBy(cb.desc(jobRecord.get("submittedAt"))); // AND all predicates return builder.and(predicates.toArray(new Predicate[0])); }; } ``` Step 2: In your Service, create a Pageable page object as: ``` Pageable page = PageRequest.of(0, 5);// 0 is the firstResult and 5 is pageSize which we can fetch from queryParams ``` The findAll method can be used with pagination as:-- ``` List<Job> jobs = repository.findAll(findByParam1AndParam2AndParam3("param1","param2","param3"), page) .stream() .map(JobRecord::toModel) .collect(Collectors.toList()); return new JobList().jobList(jobs); ```
7,799,763
So I have an app that runs on iOS 3.2 - 4.x. It uses ASIHTTPRequest to make all the REST API calls. Ever since my team and I upgraded three of our iPhone 4's to iOS 5, The app will hang and show the ActivityIndicator indefinitely. I looked at the server logs and the requests aren't hitting the server. However, if I press the iPhone home button then open the app again, the request will go through and I will receive the data, business as normal. For some reason the requests are never triggered until I reopen the app. Another weird tidbit, the app works in Xcode 4.2 and the iPhone simulator. The app also works on an iPad2 with iOS 5 (the app is iPhone only). Would this be an ASIHTTPRequest issue? Not too sure how to pinpoint the issue since there is no crash and only happens on the phone. Any insight would be much appreciated! Thanks.
2011/10/17
[ "https://Stackoverflow.com/questions/7799763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/999988/" ]
If you are using a UISwitch, then as seen in the developer API, the task `setOn: animated:` should do the trick. ``` - (void)setOn:(BOOL)on animated:(BOOL)animated ``` So to set the switch ON in your program, you would use: **Objective-C** ``` [switchName setOn:YES animated:YES]; ``` **Swift** ``` switchName.setOn(true, animated: true) ```
UISwitches have a property called "on" that should be set. Are you talking about an iOS app or a mobile web site?
7,799,763
So I have an app that runs on iOS 3.2 - 4.x. It uses ASIHTTPRequest to make all the REST API calls. Ever since my team and I upgraded three of our iPhone 4's to iOS 5, The app will hang and show the ActivityIndicator indefinitely. I looked at the server logs and the requests aren't hitting the server. However, if I press the iPhone home button then open the app again, the request will go through and I will receive the data, business as normal. For some reason the requests are never triggered until I reopen the app. Another weird tidbit, the app works in Xcode 4.2 and the iPhone simulator. The app also works on an iPad2 with iOS 5 (the app is iPhone only). Would this be an ASIHTTPRequest issue? Not too sure how to pinpoint the issue since there is no crash and only happens on the phone. Any insight would be much appreciated! Thanks.
2011/10/17
[ "https://Stackoverflow.com/questions/7799763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/999988/" ]
UISwitches have a property called "on" that should be set. Are you talking about an iOS app or a mobile web site?
Use this code to solve on/off state problem in switch in iOS ``` - (IBAction)btnSwitched:(id)sender { UISwitch *switchObject = (UISwitch *)sender; if(switchObject.isOn){ self.lblShow.text=@"Switch State is Disabled"; }else{ self.lblShow.text=@"Switch State is Enabled"; } ```
7,799,763
So I have an app that runs on iOS 3.2 - 4.x. It uses ASIHTTPRequest to make all the REST API calls. Ever since my team and I upgraded three of our iPhone 4's to iOS 5, The app will hang and show the ActivityIndicator indefinitely. I looked at the server logs and the requests aren't hitting the server. However, if I press the iPhone home button then open the app again, the request will go through and I will receive the data, business as normal. For some reason the requests are never triggered until I reopen the app. Another weird tidbit, the app works in Xcode 4.2 and the iPhone simulator. The app also works on an iPad2 with iOS 5 (the app is iPhone only). Would this be an ASIHTTPRequest issue? Not too sure how to pinpoint the issue since there is no crash and only happens on the phone. Any insight would be much appreciated! Thanks.
2011/10/17
[ "https://Stackoverflow.com/questions/7799763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/999988/" ]
UISwitches have a property called "on" that should be set. Are you talking about an iOS app or a mobile web site?
I also use the `setOn:animated:` for this and it works fine. This is the code I use in an app's `viewDidLoad` to toggle a `UISwitch` in code so that it loads preset. ``` // Check the status of the autoPlaySetting BOOL autoPlayOn = [[NSUserDefaults standardUserDefaults] boolForKey:@"autoPlay"]; [self.autoplaySwitch setOn:autoPlayOn animated:NO]; ```
7,799,763
So I have an app that runs on iOS 3.2 - 4.x. It uses ASIHTTPRequest to make all the REST API calls. Ever since my team and I upgraded three of our iPhone 4's to iOS 5, The app will hang and show the ActivityIndicator indefinitely. I looked at the server logs and the requests aren't hitting the server. However, if I press the iPhone home button then open the app again, the request will go through and I will receive the data, business as normal. For some reason the requests are never triggered until I reopen the app. Another weird tidbit, the app works in Xcode 4.2 and the iPhone simulator. The app also works on an iPad2 with iOS 5 (the app is iPhone only). Would this be an ASIHTTPRequest issue? Not too sure how to pinpoint the issue since there is no crash and only happens on the phone. Any insight would be much appreciated! Thanks.
2011/10/17
[ "https://Stackoverflow.com/questions/7799763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/999988/" ]
UISwitches have a property called "on" that should be set. Are you talking about an iOS app or a mobile web site?
**ViewController.h** ``` - (IBAction)switchAction:(id)sender; @property (strong, nonatomic) IBOutlet UILabel *lbl; ``` **ViewController.m** ``` - (IBAction)switchAction:(id)sender { UISwitch *mySwitch = (UISwitch *)sender; if ([mySwitch isOn]) { self.lbl.backgroundColor = [UIColor redColor]; } else { self.lbl.backgroundColor = [UIColor blueColor]; } } ```
7,799,763
So I have an app that runs on iOS 3.2 - 4.x. It uses ASIHTTPRequest to make all the REST API calls. Ever since my team and I upgraded three of our iPhone 4's to iOS 5, The app will hang and show the ActivityIndicator indefinitely. I looked at the server logs and the requests aren't hitting the server. However, if I press the iPhone home button then open the app again, the request will go through and I will receive the data, business as normal. For some reason the requests are never triggered until I reopen the app. Another weird tidbit, the app works in Xcode 4.2 and the iPhone simulator. The app also works on an iPad2 with iOS 5 (the app is iPhone only). Would this be an ASIHTTPRequest issue? Not too sure how to pinpoint the issue since there is no crash and only happens on the phone. Any insight would be much appreciated! Thanks.
2011/10/17
[ "https://Stackoverflow.com/questions/7799763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/999988/" ]
If you are using a UISwitch, then as seen in the developer API, the task `setOn: animated:` should do the trick. ``` - (void)setOn:(BOOL)on animated:(BOOL)animated ``` So to set the switch ON in your program, you would use: **Objective-C** ``` [switchName setOn:YES animated:YES]; ``` **Swift** ``` switchName.setOn(true, animated: true) ```
Use this code to solve on/off state problem in switch in iOS ``` - (IBAction)btnSwitched:(id)sender { UISwitch *switchObject = (UISwitch *)sender; if(switchObject.isOn){ self.lblShow.text=@"Switch State is Disabled"; }else{ self.lblShow.text=@"Switch State is Enabled"; } ```
7,799,763
So I have an app that runs on iOS 3.2 - 4.x. It uses ASIHTTPRequest to make all the REST API calls. Ever since my team and I upgraded three of our iPhone 4's to iOS 5, The app will hang and show the ActivityIndicator indefinitely. I looked at the server logs and the requests aren't hitting the server. However, if I press the iPhone home button then open the app again, the request will go through and I will receive the data, business as normal. For some reason the requests are never triggered until I reopen the app. Another weird tidbit, the app works in Xcode 4.2 and the iPhone simulator. The app also works on an iPad2 with iOS 5 (the app is iPhone only). Would this be an ASIHTTPRequest issue? Not too sure how to pinpoint the issue since there is no crash and only happens on the phone. Any insight would be much appreciated! Thanks.
2011/10/17
[ "https://Stackoverflow.com/questions/7799763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/999988/" ]
If you are using a UISwitch, then as seen in the developer API, the task `setOn: animated:` should do the trick. ``` - (void)setOn:(BOOL)on animated:(BOOL)animated ``` So to set the switch ON in your program, you would use: **Objective-C** ``` [switchName setOn:YES animated:YES]; ``` **Swift** ``` switchName.setOn(true, animated: true) ```
I also use the `setOn:animated:` for this and it works fine. This is the code I use in an app's `viewDidLoad` to toggle a `UISwitch` in code so that it loads preset. ``` // Check the status of the autoPlaySetting BOOL autoPlayOn = [[NSUserDefaults standardUserDefaults] boolForKey:@"autoPlay"]; [self.autoplaySwitch setOn:autoPlayOn animated:NO]; ```
7,799,763
So I have an app that runs on iOS 3.2 - 4.x. It uses ASIHTTPRequest to make all the REST API calls. Ever since my team and I upgraded three of our iPhone 4's to iOS 5, The app will hang and show the ActivityIndicator indefinitely. I looked at the server logs and the requests aren't hitting the server. However, if I press the iPhone home button then open the app again, the request will go through and I will receive the data, business as normal. For some reason the requests are never triggered until I reopen the app. Another weird tidbit, the app works in Xcode 4.2 and the iPhone simulator. The app also works on an iPad2 with iOS 5 (the app is iPhone only). Would this be an ASIHTTPRequest issue? Not too sure how to pinpoint the issue since there is no crash and only happens on the phone. Any insight would be much appreciated! Thanks.
2011/10/17
[ "https://Stackoverflow.com/questions/7799763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/999988/" ]
If you are using a UISwitch, then as seen in the developer API, the task `setOn: animated:` should do the trick. ``` - (void)setOn:(BOOL)on animated:(BOOL)animated ``` So to set the switch ON in your program, you would use: **Objective-C** ``` [switchName setOn:YES animated:YES]; ``` **Swift** ``` switchName.setOn(true, animated: true) ```
**ViewController.h** ``` - (IBAction)switchAction:(id)sender; @property (strong, nonatomic) IBOutlet UILabel *lbl; ``` **ViewController.m** ``` - (IBAction)switchAction:(id)sender { UISwitch *mySwitch = (UISwitch *)sender; if ([mySwitch isOn]) { self.lbl.backgroundColor = [UIColor redColor]; } else { self.lbl.backgroundColor = [UIColor blueColor]; } } ```
7,799,763
So I have an app that runs on iOS 3.2 - 4.x. It uses ASIHTTPRequest to make all the REST API calls. Ever since my team and I upgraded three of our iPhone 4's to iOS 5, The app will hang and show the ActivityIndicator indefinitely. I looked at the server logs and the requests aren't hitting the server. However, if I press the iPhone home button then open the app again, the request will go through and I will receive the data, business as normal. For some reason the requests are never triggered until I reopen the app. Another weird tidbit, the app works in Xcode 4.2 and the iPhone simulator. The app also works on an iPad2 with iOS 5 (the app is iPhone only). Would this be an ASIHTTPRequest issue? Not too sure how to pinpoint the issue since there is no crash and only happens on the phone. Any insight would be much appreciated! Thanks.
2011/10/17
[ "https://Stackoverflow.com/questions/7799763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/999988/" ]
Use this code to solve on/off state problem in switch in iOS ``` - (IBAction)btnSwitched:(id)sender { UISwitch *switchObject = (UISwitch *)sender; if(switchObject.isOn){ self.lblShow.text=@"Switch State is Disabled"; }else{ self.lblShow.text=@"Switch State is Enabled"; } ```
I also use the `setOn:animated:` for this and it works fine. This is the code I use in an app's `viewDidLoad` to toggle a `UISwitch` in code so that it loads preset. ``` // Check the status of the autoPlaySetting BOOL autoPlayOn = [[NSUserDefaults standardUserDefaults] boolForKey:@"autoPlay"]; [self.autoplaySwitch setOn:autoPlayOn animated:NO]; ```
7,799,763
So I have an app that runs on iOS 3.2 - 4.x. It uses ASIHTTPRequest to make all the REST API calls. Ever since my team and I upgraded three of our iPhone 4's to iOS 5, The app will hang and show the ActivityIndicator indefinitely. I looked at the server logs and the requests aren't hitting the server. However, if I press the iPhone home button then open the app again, the request will go through and I will receive the data, business as normal. For some reason the requests are never triggered until I reopen the app. Another weird tidbit, the app works in Xcode 4.2 and the iPhone simulator. The app also works on an iPad2 with iOS 5 (the app is iPhone only). Would this be an ASIHTTPRequest issue? Not too sure how to pinpoint the issue since there is no crash and only happens on the phone. Any insight would be much appreciated! Thanks.
2011/10/17
[ "https://Stackoverflow.com/questions/7799763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/999988/" ]
Use this code to solve on/off state problem in switch in iOS ``` - (IBAction)btnSwitched:(id)sender { UISwitch *switchObject = (UISwitch *)sender; if(switchObject.isOn){ self.lblShow.text=@"Switch State is Disabled"; }else{ self.lblShow.text=@"Switch State is Enabled"; } ```
**ViewController.h** ``` - (IBAction)switchAction:(id)sender; @property (strong, nonatomic) IBOutlet UILabel *lbl; ``` **ViewController.m** ``` - (IBAction)switchAction:(id)sender { UISwitch *mySwitch = (UISwitch *)sender; if ([mySwitch isOn]) { self.lbl.backgroundColor = [UIColor redColor]; } else { self.lbl.backgroundColor = [UIColor blueColor]; } } ```
7,799,763
So I have an app that runs on iOS 3.2 - 4.x. It uses ASIHTTPRequest to make all the REST API calls. Ever since my team and I upgraded three of our iPhone 4's to iOS 5, The app will hang and show the ActivityIndicator indefinitely. I looked at the server logs and the requests aren't hitting the server. However, if I press the iPhone home button then open the app again, the request will go through and I will receive the data, business as normal. For some reason the requests are never triggered until I reopen the app. Another weird tidbit, the app works in Xcode 4.2 and the iPhone simulator. The app also works on an iPad2 with iOS 5 (the app is iPhone only). Would this be an ASIHTTPRequest issue? Not too sure how to pinpoint the issue since there is no crash and only happens on the phone. Any insight would be much appreciated! Thanks.
2011/10/17
[ "https://Stackoverflow.com/questions/7799763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/999988/" ]
I also use the `setOn:animated:` for this and it works fine. This is the code I use in an app's `viewDidLoad` to toggle a `UISwitch` in code so that it loads preset. ``` // Check the status of the autoPlaySetting BOOL autoPlayOn = [[NSUserDefaults standardUserDefaults] boolForKey:@"autoPlay"]; [self.autoplaySwitch setOn:autoPlayOn animated:NO]; ```
**ViewController.h** ``` - (IBAction)switchAction:(id)sender; @property (strong, nonatomic) IBOutlet UILabel *lbl; ``` **ViewController.m** ``` - (IBAction)switchAction:(id)sender { UISwitch *mySwitch = (UISwitch *)sender; if ([mySwitch isOn]) { self.lbl.backgroundColor = [UIColor redColor]; } else { self.lbl.backgroundColor = [UIColor blueColor]; } } ```
27,251,797
I have an application that has a single activity that hosts several fragments in a sort of custom navigation drawer design. Two of these fragments depend on a service to return them json information to display. I want to be able to start the service on my splash screen to load the data I need then asynchronously communicate the json to these fragments. I am new to android and programming in general so excuse me if my actions were ill informed but I first tried to register the fragments as receivers and then simply broadcast intents containing the json information in a bundle. This seemed to not work because sometimes the fragments would not be running when the service would broadcast the intent and miss the intent. Then I decided to go with sticky intents but this resulted in stale information not to mention the inherit security concern. What is the best way to have a service perform a background network request upon launching the app and then display the returned information later by any activity or fragment?
2014/12/02
[ "https://Stackoverflow.com/questions/27251797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3740701/" ]
You could call startService() not only from your splash screen, but from your fragments: `getActivity().startService()`. Derive your service from [Service](http://developer.android.com/reference/android/app/Service.html) (not from IntentService). In the `onStartCommand()` it will read data from network, then broadcast the result. If result already loaded, service could simply broadcast the result. When you call `startService()` from your splashscreen, service loads data from network and broadcast it to fragments that are shown at the moment. When new fragment created, it calls `startService()` again and service broadcasts cached data. Another approach is [bindService](http://developer.android.com/reference/android/content/Context.html#bindService(android.content.Intent,%20android.content.ServiceConnection,%20int)). Your fragment could bind to service on `onCreate()` and unbind from it on `onDestroy()`. In this case fragment could call service's methods directly.
Use event bus instead of broadcasting intents, like [Green Robot EventBus](https://github.com/greenrobot/EventBus) (also supports sticky broadcasts)
27,251,797
I have an application that has a single activity that hosts several fragments in a sort of custom navigation drawer design. Two of these fragments depend on a service to return them json information to display. I want to be able to start the service on my splash screen to load the data I need then asynchronously communicate the json to these fragments. I am new to android and programming in general so excuse me if my actions were ill informed but I first tried to register the fragments as receivers and then simply broadcast intents containing the json information in a bundle. This seemed to not work because sometimes the fragments would not be running when the service would broadcast the intent and miss the intent. Then I decided to go with sticky intents but this resulted in stale information not to mention the inherit security concern. What is the best way to have a service perform a background network request upon launching the app and then display the returned information later by any activity or fragment?
2014/12/02
[ "https://Stackoverflow.com/questions/27251797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3740701/" ]
Believe me, I tried a lot of third party approaches (service buses, observes, ...) in large enterprise projects and it turned out the native Android mechanisms are the fastest and robust ones, since they take advantage of the framework's benefits. Thats why I would recommend the usage of LocalBroadcastManager along with BroadcastReceiver. In your activity (or your can event **do this per fragment!**) register in `onStart` and unregister in `onPause` a dedicated Receiver. Use the LocalBroadcastManager in your service to communicate to all potential subscribers. Example: ``` public class YourActivity extends Activity{ private BroadcastReceiver receiver = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { //...do the stuff you need to do depending on the received broadcas } }; private IntentFilter filter = new IntentFilter(UploadService.INTENT_ACTION_UPLOAD); protected onStart(){ LocalBroadcastManager.getInstance(this).registerReceiver(receiver, filter); } protected onPause(){ LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver); } } public class UploadService extends IntentService{ public static final String INTENT_ACTION_UPLOAD = "com.your.package.INTENT_ACTION_UPLOAD"; public onHandleIntent(){ //upload LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(INTENT_ACTION_UPLOAD)); } } ``` In the BroadcastReceiver's `onReceive`you can then do the stuff you need to do depending on the received broadcast. If you need to differentiate more, you can use different actions or extras, for instance in your service: ``` ...send(new Intent(INTENT_ACTION_SOMETHING_ELSE)); ``` or ``` send(new Intent(...).putExtra(WAS_SUCCESSFUL, false)); send(new Intent(...).putExtra(DOWNLOADED_CONTENT, downloadedStuff); ```
Use event bus instead of broadcasting intents, like [Green Robot EventBus](https://github.com/greenrobot/EventBus) (also supports sticky broadcasts)
36,466,008
I'm learning about multithreading in C++11 and I tried this simple test but the output is not what I expected. ``` #include <thread> #include <iostream> #include <mutex> int main() { auto function = [](int x) { std::mutex m; m.try_lock(); std::cout << "Hello" << x << std::endl; m.unlock(); return; }; std::thread t1(function , 1); std::thread t2(function, 2); std::thread t3(function, 3); std::thread t4(function, 4); t1.join(); t2.join(); t3.join(); t4.join(); std::cin.get(); return 0; } ``` I expected the output to be: ``` Hello1 Hello2 Hello3 Hello4 ``` (maybe not in that order but each hello and number in a separate line) Instead I got something like this: ``` HelloHello21 Hello3 Hello4 ``` Or ``` HelloHello2 1 Hello3 Hello4 ``` What puzzles besides the mutex aparently not locking properly is that it's always the Hello1 the one that gets cut in half. EDIT: done in VS2015 if it makes any difference (should not because it's all standard?)
2016/04/07
[ "https://Stackoverflow.com/questions/36466008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4501262/" ]
You need to use `static`, as all threads must access the same mutex object. Also, `try_lock()` (or `lock()`) causes problems if an exception is thrown before you get to `unlock()`. `std::lock_guard<>()` is a much safer way of doing this and is recommended, as it will be released when you go out of its scope, whether it's through a function return or through an exception. Try the following revision of the function: ``` auto function = [](int x) { static std::mutex m; std::lock_guard<std::mutex> mylock(m); std::cout << "Hello" << x << std::endl; return; }; ``` See <http://en.cppreference.com/w/cpp/thread/lock_guard> for more. Also, if you think you may change the mutex type in the future (or are just trying to be fancy) you can set up the mutex with an inferred template type: ``` std::lock_guard<decltype(m)> mylock(m); ```
`try_lock()` does not necessarily lock the mutex. It might lock the mutex, it might not. It only tries to lock the mutex if it can. If it's already locked, it does not wait until the mutex gets unlocked, but returns an indication that this has happened. So, in effect, your code does not end up effectively synchronizing its output, in any way, shape, matter, or form. If you really want to lock the mutex, use `lock()` instead of `try_lock()`. EDIT: and as someone else pointed out, your code effectively creates a separate mutex for each thread, so you need to make that mutex `static`, as well.
6,305,049
I am creating **table rows** within a TableLayout in a loop which goes till the size of an array. The size of my array is 120. In the loop, an object of another class is created. ``` for(int i=0; i<arrName.length; i++) { MyClass *obj =new MyClass(this); /* Some code */ } ``` **Question**: 1) How do I release the object I have created? 2)Which default method is used to release objects created in an activity? (An example could be very useful)
2011/06/10
[ "https://Stackoverflow.com/questions/6305049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
**Use this** html() gets the html code. and .text() function returns only text visible. ``` $(this).find("td:nth-child(1)").text(); ```
The raw JavaScript [`unescape()`](https://developer.mozilla.org/ja/DOM/window.unescape) function can be used for this as follows: ``` var content = $(this).find("td:nth-child(1)").html(); var unescapedContent = unescape(content); ```
902,565
I have a sequence of numbers below... $1, 2, 4, 7, 11, 16 ...$ You get this list by starting at $1$ then add $1, 2, 3, 4, 5 ...$ Given a number $n$, how can I determine if it will show up in this pattern of numbers?
2014/08/19
[ "https://math.stackexchange.com/questions/902565", "https://math.stackexchange.com", "https://math.stackexchange.com/users/70527/" ]
The $k$th term in your sequence is $1+\frac{k(k-1)}{2}$. [See [triangular numbers](http://en.wikipedia.org/wiki/Triangular_number).] Given your number $n$, you just need to check if it is of this form or not.
Put another way, take your number, multiply by $8,$ then subtract $7.$ If the result is a perfect square, the number is in the sequence, otherwise no.
7,966,428
Basically I have created an app that reads and writes values in text boxes to an XML file. Instead of using all text boxes I want to add in some combo boxes but I am not sure what property is needed for it. ``` String ^strMake = this->txtMake->Text; String ^strModel = this->txtModel->Text; String ^strName = this->txtName->Text; String ^strParentPart = this->txtParentPart->Text; String ^strPartID = this->txtPartId->Text; String ^strPartType = this->comboBox1->??????????????? ``` (The question marks is what I need to fill in)
2011/11/01
[ "https://Stackoverflow.com/questions/7966428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/993180/" ]
After a lot of debugging I found that this was actually due to a memory corruption being caused by the QSStrings library which I was using to generate base64 encoded strings. The crashes seemed to happen randomly but only after this library was invoked. When I switched to a different MD5 library, the issue went away. If you are using this library, I would suggest finding a new one to do base64 encoding. I moved to the one found here: <http://www.cocoadev.com/index.pl?BaseSixtyFour>
I think the problem happens because you have something wrong in your view that owns your label (view of your ActiveChallengeViewController). When you set the font of your label, that invokes the setNeedsDisplay of your parent view and because something is wrong, setNeedsDisplay crashs. Your line : ``` self.challengeImageView.image = [self.activeChallenge.challenge retrieveImage:self.bruConnection withCallback:imageCallback]; ``` Is it a synchronous connection to retrieve the image ? Maybe the problem happen here when sometimes the image isn't retrieved from your connection and so the image property of your image view is bad. But i am not sure because setNeedsDisplay doesn't directly invoke the redraw of the view so i don't know if the debugger catches the error just the after setNeedsDisplay call. Edit : I think this answer is bad, if image is not ok, the crash must happen when the imageView image property retains the image but i let the answer in the case of it could help you to point to the real problem.
7,379,070
So far I learned how animations work and how to set the background of a button according to its state as described [here](http://www.gersic.com/blog.php?id=56). Well, I defined an animation: ``` <set xmlns:android="http://schemas.android.com/apk/res/android"> <alpha android:interpolator="@android:anim/accelerate_interpolator" android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="50" android:repeatMode="reverse" android:repeatCount="6"/> ``` I start the animation in the onClick(View v) method. The problem now is, that the actual click action gets processed before the animation finishes. I know I could use an AnimationListener, but this would not look very nice to me since I'd have to call the actual click processes within the AnimationListener then. Does anyone know a more skilful way to let a button blink after it gets clicked?
2011/09/11
[ "https://Stackoverflow.com/questions/7379070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/939248/" ]
You can use the Selector tag like Follows: Create a New xml file and place it in your drawable folder and name it as shadow\_color.xml ``` <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/ask_footer"/> <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/askfooter_hover" /> <item android:drawable="@drawable/ask_footer" /> </selector> ``` And then go to that xml in which your Button is declared: And write one attribute in Button `android:background="@drawable/shadow_color"` and you are done. Mark the answer if you find it usefull..
Define the `onclick` for the button =================================== ``` button1.setOnClickListener( new Button.OnClickListener() { public void onClick (View v){ calcular(1,v); } } ); ``` Make your button blink ====================== This makes the images defined in the XML alternate between each other. ``` public void calcular(final int p,final View v){ MediaPlayer mp = MediaPlayer.create(this, R.raw.click); mp.start(); //v.setBackgroundResource(R.drawable.dia1btn_stl2); final TransitionDrawable transition1 = (TransitionDrawable) v.getBackground(); Handler blinkHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: transition1.startTransition(70); break; case 1: transition1.resetTransition(); break; } super.handleMessage(msg); } }; for (int i=0; i<6; i++) { Message msg = new Message(); if(i % 2 == 0){ msg.what = 0; } else{ msg.what=1; } blinkHandler.sendMessageDelayed(msg, i*100); } /*mCurrentSeries.clear(); if(calcularctrl == 0){ calcularctrl = 1; dtdodo = new DownloadImageTask(this , p , codacaovalue); dtdodo.execute("wwwkjhdijdh"); }*/ Handler handler2 = new Handler(); handler2.postDelayed(new Runnable() { public void run() { //v.setBackgroundResource(R.drawable.dia1btn_stl2); mCurrentSeries.clear(); if(calcularctrl == 0){ calcularctrl = 1; dtdodo = new DownloadImageTask(outer() , p , codacaovalue); dtdodo.execute("wwwkjhdijdh"); } try { this.finalize(); } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); } } public acoesdetalhes outer(){ return acoesdetalhes.this; } }, 1000); } ``` The XML of the button background ================================ ``` <?xml version="1.0" encoding="UTF-8"?> <transition xmlns:android="http://schemas.android.com/apk/res/android"> <!-- The drawables used here can be solid colors, gradients, shapes, images, etc. --> <item android:drawable="@drawable/mes1btn_stl2" /> <item android:drawable="@drawable/mes1btn_prssd2" /> </transition> ``` This code provided in part by user Alin.
40,462,632
I havent used PyGithub yet but I am just curious if there is any possibility to get a list of releases from a repository (e.g. `https://github.com/{username}/{repo-name}/releases`). I can not see any information about that in documentation [here](http://pygithub.readthedocs.io/en/latest/apis.html).
2016/11/07
[ "https://Stackoverflow.com/questions/40462632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3333597/" ]
The question is a bit old but nobody seems to have answered it in the way the OP asked. PyGithub does have a way to return releases of a repo, here is a working example: ```py from github import Github G = Github('') # Put your GitHub token here repo = G.get_repo('justintime50/github-archive') releases = repo.get_releases() for release in releases: print(release.title) ``` The above will return the following: ```sh v4.3.0 v4.2.2 v4.2.1 v4.2.0 v4.1.1 ... ``` I hope this is helpful!
You can get a list of releases from a GitHub repo by making a GET request to ``` https://api.github.com/repos/{user}/{repo}/releases ``` Eg ``` import requests url = 'https://api.github.com/repos/facebook/react/releases' response = requests.get(url) # Raise an exception if the API call fails. response.raise_for_status() data = response.json() ``` Also its worth noting you should be making authenticated requests otherwise you'll hit GitHubs API rate limiting pretty quickly and just get back 403s.
40,462,632
I havent used PyGithub yet but I am just curious if there is any possibility to get a list of releases from a repository (e.g. `https://github.com/{username}/{repo-name}/releases`). I can not see any information about that in documentation [here](http://pygithub.readthedocs.io/en/latest/apis.html).
2016/11/07
[ "https://Stackoverflow.com/questions/40462632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3333597/" ]
The question is a bit old but nobody seems to have answered it in the way the OP asked. PyGithub does have a way to return releases of a repo, here is a working example: ```py from github import Github G = Github('') # Put your GitHub token here repo = G.get_repo('justintime50/github-archive') releases = repo.get_releases() for release in releases: print(release.title) ``` The above will return the following: ```sh v4.3.0 v4.2.2 v4.2.1 v4.2.0 v4.1.1 ... ``` I hope this is helpful!
The documentation for PyGithub doesn't mention it, but I believe that `pygithub-1.29` (the latest published on PyPi as of today) does in fact contain this API: [`Repository.py`](https://github.com/PyGithub/PyGithub/blob/v1.29/github/Repository.py#L2056) for the `v1.29` tag contains a `get_releases()` function. There is also an [open, unmerged pull request](https://github.com/PyGithub/PyGithub/pull/361) that appears to fill out this API to include assets, too.
21,294,352
I'm trying to select the values from two adjacent xml nodes at the same time using ``` var values = xDoc.Element("root") .Elements("model") .Where(x => x.Element("modelName").Value == modelType.ToString()) .Elements("directory") .Select(x => new { x.Element("directoryName").Value, x.Element("taskName").Value }); ``` I'm getting red squiggles under the `.Value`s saying "Duplicate anonymous type property name 'Value'. Here is the xml ``` <root> <model> <modelName>Model1</modelName> <directory> <directoryName>Dir1</directoryName> <taskName>Task1</taskName> </directory> </model> <model> <modelName>Model2</modelName> <directory> <directoryName>FirstValue</directoryName> <taskName>SecondValue</taskName> </directory> </model> </root> ``` I want to extract Dir1 and Task1 or FirstValue and SecondValue.
2014/01/22
[ "https://Stackoverflow.com/questions/21294352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2125444/" ]
I suggest you to use casting elements to string instead of accessing their `Value` property. Because if element is missing (e.g. for `Model1` you don't have `taskName` element) then you will get `NullReferenceException`. ``` var values = from m in xDoc.Root.Elements("model") where (string)m.Element("modelName") == modelType.ToString() let d = m.Element("directory") select new { Directory = (string)d.Element("directoryName"), Task = (string)d.Element("taskName") }; ``` Also I find declarative (query) syntax more readable than lambda syntax (matter of taste). You can also use XPath to make query even more compact: ``` string xpath = String.Format("root/model[modelName='{0}']/directory", modelType); var values = from d in xdoc.XPathSelectElements(xpath) select new { Directory = (string)d.Element("directoryName"), Task = (string)d.Element("taskName") }; ```
Figured it out, you just need to name the properties in the anonymous type ``` var values = xDoc.Element("root") .Elements("model") .Where(x => x.Element("modelName").Value == modelType.ToString()) .Elements("directory") .Select(x => new { Directory = x.Element("directoryName").Value, Task = x.Element("taskName").Value }); ```
44,444,815
hello guys after mixing laravel template i have some problem with the jquery with Error: Bootstrap's JavaScript requires jQuery and after searcing im still confused whats happen can you help me here is my code : ``` <script src="{{{ URL::asset('js/ace-extra.min.js')}}}"></script> <script src="{{{ URL::asset('js/bootstrap.min.js')}}}"></script> <script src="{{{ URL::asset('js/ace-elements.min.js')}}}"></script> <script src="{{{ URL::asset('js/ace.min.js')}}}"></script> ``` ` and error on firefox : [here](https://i.stack.imgur.com/AR0rD.png)
2017/06/08
[ "https://Stackoverflow.com/questions/44444815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8100587/" ]
Here's a simple solution: ``` // array to store required strings $stringsCollection = []; // 4 is the number of strings that you need while (sizeof($stringsCollection) != 4) { // generate new string $randString = random_string($length); // if string is not in `stringsCollection` - add it as a key if (!isset($stringsCollection[$randString])) { $stringsCollection[$randString] = 1; } } print_r(array_keys($stringsCollection)); ```
> > or is there a more efficient way > > > You are heading to "overengeneering land", trying to fix things you cannot even name :) Is it slow? Sluggish? Then profile and fix relevant parts. "Efficient" is buzzword w/o defining what efficiency means for you. > > what is the best way to prevent duplicate outputs / collisions if called multiple times > > > First, I'd use hashing functions with detailed (i.e. seconds or millis) timestamp + some mt\_rand as input like instead. It's limited in length but you can call it multiple times and concatenate results (+ trim if needed). And if you want to be 1000% the value was never returned before, you must keep track of them, however you most likely can **assume** this is not going to happen if you will have input string long enough
38,590,811
Is there a shorthand method for constructing a 2D array? I really don't want to do the following: ``` let board = array2D [| [| 0;0 |] [| 0;1 |] [| 0;2 |] [| 0;3 |] [| 0;4 |] [| 0;5 |] [| 0;6 |] [| 0;7 |] [| 1;0 |] [| 1;1 |] [| 1;2 |] ... [| 7;7 |] |] ``` I thought I could do something like this: ``` let board = array2D [| [| 0;0 |]..[|7;7|] |] ``` Or this: ``` let board = array2D [| [| 0.., 0..7 |] |] ``` Any guidance?
2016/07/26
[ "https://Stackoverflow.com/questions/38590811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/492701/" ]
You could do something like this: ``` import sys try: _, size, file = sys.argv size = int(size) except ValueError: sys.exit('Usage: splitter.py <size in bytes> <filename to split>') with open(file) as infile: count = 0 current_size = 0 # you could do something more # fancy with the name like use # os.path.splitext outfile = open(file+'_0', 'w+') for line in infile: if current_size > size and line.startswith('Recno'): outfile.close() count += 1 current_size = 0 outfile = open(file+'_{}'.format(count), 'w+') current_size += len(line) outfile.write(line) outfile.close() ```
As comment above mentions you can use `split` in the bash shell: ``` split -b 20000m <path-to-your-file> ```
73,945,039
I am trying to add an background image with css but I am geting 404 error GEThttp://127.0.0.1:5500/css/img/example.jpg Here is the code that I use. ``` body { background-image: linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0,0.7)), url(img/example.jpg); background-size: cover; background-position: center; height: 100vh; } ``` The image is in the folder img and the name is correct.
2022/10/04
[ "https://Stackoverflow.com/questions/73945039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15842342/" ]
The path may be correct, but not if the css is the starting point So firstly you have to go up a level with "../" in front of your current path. So "../img/example.jpg" (Maybe you have to go up several levels, depending on where exactly your folder lies, you would need to show your folder structure for more insight if this doesn't fix it)
If this is a CSS file, the image file is relative to the css file, not the html.
73,945,039
I am trying to add an background image with css but I am geting 404 error GEThttp://127.0.0.1:5500/css/img/example.jpg Here is the code that I use. ``` body { background-image: linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0,0.7)), url(img/example.jpg); background-size: cover; background-position: center; height: 100vh; } ``` The image is in the folder img and the name is correct.
2022/10/04
[ "https://Stackoverflow.com/questions/73945039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15842342/" ]
The path may be correct, but not if the css is the starting point So firstly you have to go up a level with "../" in front of your current path. So "../img/example.jpg" (Maybe you have to go up several levels, depending on where exactly your folder lies, you would need to show your folder structure for more insight if this doesn't fix it)
`url` accepts the path relative to `/` (document root of the web server where website is deployed) or to the CSS file. So if you change the line by adding `/css`: `background-image: linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0,0.7)), url(img/example.jpg);` to `background-image: linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0,0.7)), url(/css/img/example.jpg);` it should work. Absolute paths are usually better. For more information please see: <https://developer.mozilla.org/en-US/docs/Web/CSS/url>
12,990
I am a student of computer science with interest in image processing. I have learned how to apply a few effects to images like making them grayscale, sketching them out of lines, etc. I would like to learn more about the algorithmic techniques behind creative manipulation of images like making them sepia-tone, smudging them, etc. **Can someone please point me in the right direction?** How do I learn the fundamentals of these algorithms?
2013/06/30
[ "https://cs.stackexchange.com/questions/12990", "https://cs.stackexchange.com", "https://cs.stackexchange.com/users/8418/" ]
There are books on digital image processing which you can look into. Many common image manipulation techniques, such as smudging (usually known as blurring) are accomplished by [image filtering](http://lodev.org/cgtutor/filtering.html), which is a process of applying a two-dimensional filter to an image: the value of each pixel in the new image is a linear combination of its original value and the original values of its neighbors. Sepia tone is an example of color manipulation: assuming the image is stored as RGB, this amounts to applying some carefully constructed mapping on the R,G,B values of each pixel. The mapping can be represented as a table $\{0,\ldots,255\}^3 \to \{0,\ldots,255\}^3$, or alternatively some formula can be applied instead.
I have been working on that very same thing recently, albeit for a very different purpose. Asides from SO, I have been referring to Google code examples, and forums related to the platform and language that I am working in. Sometimes, I found some information and techniques from [Image Processing Online](http://www.ipol.im/). One technique that I found was particularly helpful, was to outline the processes that I wanted to do first and research each major programming decision, testing it as I go. I hope this helps.
12,990
I am a student of computer science with interest in image processing. I have learned how to apply a few effects to images like making them grayscale, sketching them out of lines, etc. I would like to learn more about the algorithmic techniques behind creative manipulation of images like making them sepia-tone, smudging them, etc. **Can someone please point me in the right direction?** How do I learn the fundamentals of these algorithms?
2013/06/30
[ "https://cs.stackexchange.com/questions/12990", "https://cs.stackexchange.com", "https://cs.stackexchange.com/users/8418/" ]
I have been working on that very same thing recently, albeit for a very different purpose. Asides from SO, I have been referring to Google code examples, and forums related to the platform and language that I am working in. Sometimes, I found some information and techniques from [Image Processing Online](http://www.ipol.im/). One technique that I found was particularly helpful, was to outline the processes that I wanted to do first and research each major programming decision, testing it as I go. I hope this helps.
If you already know the name of some specific image processing technique, Wikipedia has pretty good explanations -- such as ["closing"](http://en.wikipedia.org/wiki/closing_%28morphology%29) in [morphological image processing](http://en.wikipedia.org/wiki/morphological_image_processing). The [computer vision wiki](http://computervision.wikia.com/) is a good place to read and write about computer vision stuff that doesn't fit into an encyclopedia format -- HOWTOs, example code, etc. There exist many "type this, click there" tutorials on how to get a specific effect with a specific piece of software -- [GIMP Tutorials](http://en.wikibooks.org/wiki/GIMP/External_Tutorials), [Kdenlive/Video effects](http://en.wikibooks.org/wiki/Kdenlive/Video_effects), [MATLAB Image Processing Toolbox](http://en.wikibooks.org/wiki/MATLAB_Programming/Image_Processing_Toolbox), etc. Many universities have classes in image processing or computer graphics or both; a few have an entire department dedicated to image processing. Some of them even have a web site that has lots of information about image processing. A few even record class lectures and post them online. * [Virginia Image and Video Analysis laboratory](http://viva.ee.virginia.edu/) * [Berkeley Computer Vision Group](http://www.eecs.berkeley.edu/Research/Projects/CS/vision/) * [USC Computer Vision Laboratory](http://iris.usc.edu/USC-Computer-Vision.html) * [Coursera Computer Vision in English](https://www.coursera.org/course/computervision) * [Coursera Computer Vision in German](https://www.coursera.org/course/compvision) * [MIT Computer Vision Group](http://groups.csail.mit.edu/vision/) * [Cornell Graphics and Vision Group](http://rgb.cs.cornell.edu/)
12,990
I am a student of computer science with interest in image processing. I have learned how to apply a few effects to images like making them grayscale, sketching them out of lines, etc. I would like to learn more about the algorithmic techniques behind creative manipulation of images like making them sepia-tone, smudging them, etc. **Can someone please point me in the right direction?** How do I learn the fundamentals of these algorithms?
2013/06/30
[ "https://cs.stackexchange.com/questions/12990", "https://cs.stackexchange.com", "https://cs.stackexchange.com/users/8418/" ]
There are books on digital image processing which you can look into. Many common image manipulation techniques, such as smudging (usually known as blurring) are accomplished by [image filtering](http://lodev.org/cgtutor/filtering.html), which is a process of applying a two-dimensional filter to an image: the value of each pixel in the new image is a linear combination of its original value and the original values of its neighbors. Sepia tone is an example of color manipulation: assuming the image is stored as RGB, this amounts to applying some carefully constructed mapping on the R,G,B values of each pixel. The mapping can be represented as a table $\{0,\ldots,255\}^3 \to \{0,\ldots,255\}^3$, or alternatively some formula can be applied instead.
you seem to be interested in image enhancement techniques such as used on Instagram to add "cool effects". these algorithms tend to be somewhat more advanced and proprietary. however for basic image manipulation which is the underlying basis for these algorithms, there are many places to start. here are a few: * [Image processing basics](http://www.imageprocessingbasics.com/) tutorials with java applets. * [Image processing basics tutorial](http://www.imageprocessingplace.com/root_files_V3/tutorials.htm) Zip files of many tutorials. the overall site has a comprehensive list of resources eg books. * [CMSC 426 Image processing U Maryland/Jacobs 2003](http://www.cs.umd.edu/~djacobs/CMSC426/CMSC426.htm) there are many university classes some with very good online notes/resources * [Image processing in MATLAB](http://robotix.in/tutorials/category/imageprocessing/ip_matlab) Matlab is a leading mathematical package for image processing and math packages can simplify many algorithms. another leading package for image manipulation is Mathematica. * [Coursera](https://www.coursera.org/course/images), now a leading online course site, has a course on Image and video processing by Sapiro/Duke university. * another option for the hacker types is taking an open source image processing program and reverse-engineering the code, ie learning the algorithms by looking at code and/or tweaking it. [Gimp](http://en.wikipedia.org/wiki/GIMP) is a very full featured open source image processing program with many advanced effects, some as "plugins". note most image techniques have many fundamental connections to [linear/matrix/vector algebra](http://en.wikipedia.org/wiki/Matrix_%28mathematics%29) and thats an important mathematical area to study for basic background.
12,990
I am a student of computer science with interest in image processing. I have learned how to apply a few effects to images like making them grayscale, sketching them out of lines, etc. I would like to learn more about the algorithmic techniques behind creative manipulation of images like making them sepia-tone, smudging them, etc. **Can someone please point me in the right direction?** How do I learn the fundamentals of these algorithms?
2013/06/30
[ "https://cs.stackexchange.com/questions/12990", "https://cs.stackexchange.com", "https://cs.stackexchange.com/users/8418/" ]
There are books on digital image processing which you can look into. Many common image manipulation techniques, such as smudging (usually known as blurring) are accomplished by [image filtering](http://lodev.org/cgtutor/filtering.html), which is a process of applying a two-dimensional filter to an image: the value of each pixel in the new image is a linear combination of its original value and the original values of its neighbors. Sepia tone is an example of color manipulation: assuming the image is stored as RGB, this amounts to applying some carefully constructed mapping on the R,G,B values of each pixel. The mapping can be represented as a table $\{0,\ldots,255\}^3 \to \{0,\ldots,255\}^3$, or alternatively some formula can be applied instead.
What you are referring to is not a branch of just image processing, but specifically [digital image processing.](http://en.wikipedia.org/wiki/Digital_image_processing) Also, [linear filtering](http://en.wikipedia.org/wiki/Linear_filter) should help a bit.
12,990
I am a student of computer science with interest in image processing. I have learned how to apply a few effects to images like making them grayscale, sketching them out of lines, etc. I would like to learn more about the algorithmic techniques behind creative manipulation of images like making them sepia-tone, smudging them, etc. **Can someone please point me in the right direction?** How do I learn the fundamentals of these algorithms?
2013/06/30
[ "https://cs.stackexchange.com/questions/12990", "https://cs.stackexchange.com", "https://cs.stackexchange.com/users/8418/" ]
There are books on digital image processing which you can look into. Many common image manipulation techniques, such as smudging (usually known as blurring) are accomplished by [image filtering](http://lodev.org/cgtutor/filtering.html), which is a process of applying a two-dimensional filter to an image: the value of each pixel in the new image is a linear combination of its original value and the original values of its neighbors. Sepia tone is an example of color manipulation: assuming the image is stored as RGB, this amounts to applying some carefully constructed mapping on the R,G,B values of each pixel. The mapping can be represented as a table $\{0,\ldots,255\}^3 \to \{0,\ldots,255\}^3$, or alternatively some formula can be applied instead.
If you already know the name of some specific image processing technique, Wikipedia has pretty good explanations -- such as ["closing"](http://en.wikipedia.org/wiki/closing_%28morphology%29) in [morphological image processing](http://en.wikipedia.org/wiki/morphological_image_processing). The [computer vision wiki](http://computervision.wikia.com/) is a good place to read and write about computer vision stuff that doesn't fit into an encyclopedia format -- HOWTOs, example code, etc. There exist many "type this, click there" tutorials on how to get a specific effect with a specific piece of software -- [GIMP Tutorials](http://en.wikibooks.org/wiki/GIMP/External_Tutorials), [Kdenlive/Video effects](http://en.wikibooks.org/wiki/Kdenlive/Video_effects), [MATLAB Image Processing Toolbox](http://en.wikibooks.org/wiki/MATLAB_Programming/Image_Processing_Toolbox), etc. Many universities have classes in image processing or computer graphics or both; a few have an entire department dedicated to image processing. Some of them even have a web site that has lots of information about image processing. A few even record class lectures and post them online. * [Virginia Image and Video Analysis laboratory](http://viva.ee.virginia.edu/) * [Berkeley Computer Vision Group](http://www.eecs.berkeley.edu/Research/Projects/CS/vision/) * [USC Computer Vision Laboratory](http://iris.usc.edu/USC-Computer-Vision.html) * [Coursera Computer Vision in English](https://www.coursera.org/course/computervision) * [Coursera Computer Vision in German](https://www.coursera.org/course/compvision) * [MIT Computer Vision Group](http://groups.csail.mit.edu/vision/) * [Cornell Graphics and Vision Group](http://rgb.cs.cornell.edu/)
12,990
I am a student of computer science with interest in image processing. I have learned how to apply a few effects to images like making them grayscale, sketching them out of lines, etc. I would like to learn more about the algorithmic techniques behind creative manipulation of images like making them sepia-tone, smudging them, etc. **Can someone please point me in the right direction?** How do I learn the fundamentals of these algorithms?
2013/06/30
[ "https://cs.stackexchange.com/questions/12990", "https://cs.stackexchange.com", "https://cs.stackexchange.com/users/8418/" ]
you seem to be interested in image enhancement techniques such as used on Instagram to add "cool effects". these algorithms tend to be somewhat more advanced and proprietary. however for basic image manipulation which is the underlying basis for these algorithms, there are many places to start. here are a few: * [Image processing basics](http://www.imageprocessingbasics.com/) tutorials with java applets. * [Image processing basics tutorial](http://www.imageprocessingplace.com/root_files_V3/tutorials.htm) Zip files of many tutorials. the overall site has a comprehensive list of resources eg books. * [CMSC 426 Image processing U Maryland/Jacobs 2003](http://www.cs.umd.edu/~djacobs/CMSC426/CMSC426.htm) there are many university classes some with very good online notes/resources * [Image processing in MATLAB](http://robotix.in/tutorials/category/imageprocessing/ip_matlab) Matlab is a leading mathematical package for image processing and math packages can simplify many algorithms. another leading package for image manipulation is Mathematica. * [Coursera](https://www.coursera.org/course/images), now a leading online course site, has a course on Image and video processing by Sapiro/Duke university. * another option for the hacker types is taking an open source image processing program and reverse-engineering the code, ie learning the algorithms by looking at code and/or tweaking it. [Gimp](http://en.wikipedia.org/wiki/GIMP) is a very full featured open source image processing program with many advanced effects, some as "plugins". note most image techniques have many fundamental connections to [linear/matrix/vector algebra](http://en.wikipedia.org/wiki/Matrix_%28mathematics%29) and thats an important mathematical area to study for basic background.
If you already know the name of some specific image processing technique, Wikipedia has pretty good explanations -- such as ["closing"](http://en.wikipedia.org/wiki/closing_%28morphology%29) in [morphological image processing](http://en.wikipedia.org/wiki/morphological_image_processing). The [computer vision wiki](http://computervision.wikia.com/) is a good place to read and write about computer vision stuff that doesn't fit into an encyclopedia format -- HOWTOs, example code, etc. There exist many "type this, click there" tutorials on how to get a specific effect with a specific piece of software -- [GIMP Tutorials](http://en.wikibooks.org/wiki/GIMP/External_Tutorials), [Kdenlive/Video effects](http://en.wikibooks.org/wiki/Kdenlive/Video_effects), [MATLAB Image Processing Toolbox](http://en.wikibooks.org/wiki/MATLAB_Programming/Image_Processing_Toolbox), etc. Many universities have classes in image processing or computer graphics or both; a few have an entire department dedicated to image processing. Some of them even have a web site that has lots of information about image processing. A few even record class lectures and post them online. * [Virginia Image and Video Analysis laboratory](http://viva.ee.virginia.edu/) * [Berkeley Computer Vision Group](http://www.eecs.berkeley.edu/Research/Projects/CS/vision/) * [USC Computer Vision Laboratory](http://iris.usc.edu/USC-Computer-Vision.html) * [Coursera Computer Vision in English](https://www.coursera.org/course/computervision) * [Coursera Computer Vision in German](https://www.coursera.org/course/compvision) * [MIT Computer Vision Group](http://groups.csail.mit.edu/vision/) * [Cornell Graphics and Vision Group](http://rgb.cs.cornell.edu/)
12,990
I am a student of computer science with interest in image processing. I have learned how to apply a few effects to images like making them grayscale, sketching them out of lines, etc. I would like to learn more about the algorithmic techniques behind creative manipulation of images like making them sepia-tone, smudging them, etc. **Can someone please point me in the right direction?** How do I learn the fundamentals of these algorithms?
2013/06/30
[ "https://cs.stackexchange.com/questions/12990", "https://cs.stackexchange.com", "https://cs.stackexchange.com/users/8418/" ]
What you are referring to is not a branch of just image processing, but specifically [digital image processing.](http://en.wikipedia.org/wiki/Digital_image_processing) Also, [linear filtering](http://en.wikipedia.org/wiki/Linear_filter) should help a bit.
If you already know the name of some specific image processing technique, Wikipedia has pretty good explanations -- such as ["closing"](http://en.wikipedia.org/wiki/closing_%28morphology%29) in [morphological image processing](http://en.wikipedia.org/wiki/morphological_image_processing). The [computer vision wiki](http://computervision.wikia.com/) is a good place to read and write about computer vision stuff that doesn't fit into an encyclopedia format -- HOWTOs, example code, etc. There exist many "type this, click there" tutorials on how to get a specific effect with a specific piece of software -- [GIMP Tutorials](http://en.wikibooks.org/wiki/GIMP/External_Tutorials), [Kdenlive/Video effects](http://en.wikibooks.org/wiki/Kdenlive/Video_effects), [MATLAB Image Processing Toolbox](http://en.wikibooks.org/wiki/MATLAB_Programming/Image_Processing_Toolbox), etc. Many universities have classes in image processing or computer graphics or both; a few have an entire department dedicated to image processing. Some of them even have a web site that has lots of information about image processing. A few even record class lectures and post them online. * [Virginia Image and Video Analysis laboratory](http://viva.ee.virginia.edu/) * [Berkeley Computer Vision Group](http://www.eecs.berkeley.edu/Research/Projects/CS/vision/) * [USC Computer Vision Laboratory](http://iris.usc.edu/USC-Computer-Vision.html) * [Coursera Computer Vision in English](https://www.coursera.org/course/computervision) * [Coursera Computer Vision in German](https://www.coursera.org/course/compvision) * [MIT Computer Vision Group](http://groups.csail.mit.edu/vision/) * [Cornell Graphics and Vision Group](http://rgb.cs.cornell.edu/)
37,373
We have been introduced to 5 characters (all Impel Down Jailers) with "Awakened" Zoan Devil Fruits. Minotaurus is the most famous of them. A normal Zoan fruit allows the user to transform between Natural (normally human), Animal (based on the devil fruit type), and Hybrid forms. I can't, however, remember any of the "Mino" guards in any form besides a exageratedly strong version of the Hybrid one. At the time I thought "Awakened" meant that the fruit was always active so they were stuck as partially animals (as well as give the strengths Crocodile mentioned). With Doflamingo's Paramecia fruit, however, awakening appears to just unlock new abilities. This made me doubt my previous understanding. Wiki doesn't help and I don't have time to rewatch everything. Do we know whether Awakened Zoan Devil Fruit users retain the ability to transform into multiple forms? If the answer to this is "Oda hasn't told us yet", that is sufficient.
2016/11/17
[ "https://anime.stackexchange.com/questions/37373", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/3561/" ]
My theory about its "real name" is, either Towako, the name of hakumen's avatar, maybe Hakumen named its avatar the real name for self-satisfaction? and the second probable name, is kirio/Inasa, as in Kirio Inasa, the boy whom it kidnapped. after the kidnapping, it probably change his name as it likes. I personally think, Towako is the "Real name".
In my opinion i think Hakumen’s real name might have something to do with the baby shown as he vaporizes and yin/yang because in the end he does not fall as negative ki which creates other youkai, but he floats upwards as positive ki. Maybe in the end he died a peaceful death and he could now be reborn as a human, not a mass of hate.We can also assume he would have a woman name since his voice when he whispers “The name i was called was...” is a feminine one.
21,501,174
I'm trying: ``` python3 -m timeit -c 'len("".join([str(x) for x in range(0, 999999)]))' 10 loops, best of 3: 330 msec per loop python3 -m timeit -c 'sum((len(y) for y in [str(x) for x in range(0, 999999)])) 10 loops, best of 3: 439 msec per loop ``` Why does this happen? Is there a faster way? P.S. It is assumed that a list of strings will be in advance.
2014/02/01
[ "https://Stackoverflow.com/questions/21501174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3260919/" ]
A better benchmark with IPython shows the situation is worse than you thought: ``` >>> lst = [str(x) for x in range(0, 999999)] >>> %timeit len("".join(lst)) 100 loops, best of 3: 9.94 ms per loop >>> %timeit sum(len(x) for x in lst) 10 loops, best of 3: 62.2 ms per loop ``` You're seeing two effects here, the overhead of function calls in Python and the overhead of its iteration. `"".join` doesn't have either because it's a single method call that does a loop in C. Intermediate performance with less memory use can be gotten from `map`: ``` >>> %timeit sum(map(len, lst)) 10 loops, best of 3: 29.4 ms per loop ```
The first (faster) version has 1 call to the `len` function, 1 call to `join` and 100k calls to `str`. Looking at the second line you can see that both `len` and `str` are called 100k times each which makes for about twice as many total function calls in the second case.
21,501,174
I'm trying: ``` python3 -m timeit -c 'len("".join([str(x) for x in range(0, 999999)]))' 10 loops, best of 3: 330 msec per loop python3 -m timeit -c 'sum((len(y) for y in [str(x) for x in range(0, 999999)])) 10 loops, best of 3: 439 msec per loop ``` Why does this happen? Is there a faster way? P.S. It is assumed that a list of strings will be in advance.
2014/02/01
[ "https://Stackoverflow.com/questions/21501174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3260919/" ]
Ignoring that rather small time difference for now, there is actually a huge difference for your two ways *in memory*. ``` sum((len(y) for y in [str(x) for x in range(0, 999999)])) ``` This will create a string for each number and store that in a list. Then you use a generator expression to loop over that list and sum the lengths up. So you essentially have a string for each number, a list storing all strings, and a number that is being added to for the lengths. ``` len(''.join([str(x) for x in range(0, 999999)])) ``` This will again create a string for each number and store that in a list. Then you create a huge string with all numbers. Afterwards you call length on in (which is then a O(1) call). So you don’t have the number you add to (while summing the lengths up), but you do have another long string that combines all the other strings again. So even if that is faster, you are throwing away a lot of memory, which will likely have an effect on performance later too. To improve all this, you should consider creating as little stuff permanently as possible. Don’t use list comprehensions as that will actually create the lists; don’t use `str.join` as that requires a list and iterates it twice. ``` sum(len(str(x)) for x in range(0, 999999))) ``` Now, this will still be slower than the `len(''.join(…))` method but won’t have that much of a memory overhead. In fact, it will only create one string object at a time, get its length and add it to the sum. The string can then be immediately collected. The reason this will still be slow though is that it both `len` and `str` need to be looked up with every iteration inside of the generator. To speed that up, use `map` to only look it up twice. wim made a really good suggestion in the comments: ``` sum(map(len, map(str, range(999999)))) ``` This actually performs faster than the `len(''.join(…))` way for me. My timing results in order of being mentioned in my answer: ``` 62.36836282166257 50.54277449168785 58.24419845897603 40.3403849521618 ```
The first (faster) version has 1 call to the `len` function, 1 call to `join` and 100k calls to `str`. Looking at the second line you can see that both `len` and `str` are called 100k times each which makes for about twice as many total function calls in the second case.
148,852
I deployed a webpart by admin user in Visual Studio 2013 through in SharePoint 2013. It's working fine. But when I deploy using another user which already have admin permission then it is showing below error. > > Error occurred in deployment step 'Retract Solution': Object reference not set to an instance of an object. > > >
2015/07/10
[ "https://sharepoint.stackexchange.com/questions/148852", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/37342/" ]
It's most likely your SpSite or SpWeb object is null because of insufficient rights to the user. Can you make sure that the user have rights on the webapp you are deploying the solution too. A simple way to make sure that the user have sufficient rights is to create a new test solution and deploy, it will make things clear.
I had same problem and i tried whatever was suggested in the blog. Like uninstall solution etc. Then I did a restart of system. And opened a new solution and tired to deploy. But this time the error was very clear, I got a message it was due to increase in database size. After reducing deployment worked correctly.
148,852
I deployed a webpart by admin user in Visual Studio 2013 through in SharePoint 2013. It's working fine. But when I deploy using another user which already have admin permission then it is showing below error. > > Error occurred in deployment step 'Retract Solution': Object reference not set to an instance of an object. > > >
2015/07/10
[ "https://sharepoint.stackexchange.com/questions/148852", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/37342/" ]
It's most likely your SpSite or SpWeb object is null because of insufficient rights to the user. Can you make sure that the user have rights on the webapp you are deploying the solution too. A simple way to make sure that the user have sufficient rights is to create a new test solution and deploy, it will make things clear.
I had same problem and my solution was related with no space in disk for deployment. ps.: database disk.
148,852
I deployed a webpart by admin user in Visual Studio 2013 through in SharePoint 2013. It's working fine. But when I deploy using another user which already have admin permission then it is showing below error. > > Error occurred in deployment step 'Retract Solution': Object reference not set to an instance of an object. > > >
2015/07/10
[ "https://sharepoint.stackexchange.com/questions/148852", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/37342/" ]
I had same problem and my solution was related with no space in disk for deployment. ps.: database disk.
I had same problem and i tried whatever was suggested in the blog. Like uninstall solution etc. Then I did a restart of system. And opened a new solution and tired to deploy. But this time the error was very clear, I got a message it was due to increase in database size. After reducing deployment worked correctly.
1,640,364
Revision of mutator method definition Write a mutator method setAge() that takes a single parameter of type int and sets the value of variable age Paste your answer in here: ``` public int setAge(int age) { return age; } ``` Comments: ``` * Test 1 (0.0 out of 1) The compilation was successful The output should have been: setAge() Correct This is what was actually produced: setAge() not Correct ``` confused on why i get this error, is it because i have (int age) after setAge that is why the error is comming up?
2009/10/28
[ "https://Stackoverflow.com/questions/1640364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196341/" ]
Try with ``` public void setAge(int age) { this.age = age; } ```
Your code does not "set the value of a variable age". Your method only returns the value that was passed to it.
1,640,364
Revision of mutator method definition Write a mutator method setAge() that takes a single parameter of type int and sets the value of variable age Paste your answer in here: ``` public int setAge(int age) { return age; } ``` Comments: ``` * Test 1 (0.0 out of 1) The compilation was successful The output should have been: setAge() Correct This is what was actually produced: setAge() not Correct ``` confused on why i get this error, is it because i have (int age) after setAge that is why the error is comming up?
2009/10/28
[ "https://Stackoverflow.com/questions/1640364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196341/" ]
Try with ``` public void setAge(int age) { this.age = age; } ```
Assuming you have a class variable called 'age', you can create the mutator class method as: ``` public class myTest{ public int age; //other code here..if any public void setAge(int age) { this.age = age; } //other code here.. if any } ``` Normally your setAge method should not return anything. Mutator only modifies the value. To return value you should use getAge() method which is called 'Accessor'.
1,640,364
Revision of mutator method definition Write a mutator method setAge() that takes a single parameter of type int and sets the value of variable age Paste your answer in here: ``` public int setAge(int age) { return age; } ``` Comments: ``` * Test 1 (0.0 out of 1) The compilation was successful The output should have been: setAge() Correct This is what was actually produced: setAge() not Correct ``` confused on why i get this error, is it because i have (int age) after setAge that is why the error is comming up?
2009/10/28
[ "https://Stackoverflow.com/questions/1640364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196341/" ]
Your mutator is not actually setting anything. I assume you already have a piece of code that you have to modify, search in that piece for a variable/field 'age'.
Your code does not "set the value of a variable age". Your method only returns the value that was passed to it.
1,640,364
Revision of mutator method definition Write a mutator method setAge() that takes a single parameter of type int and sets the value of variable age Paste your answer in here: ``` public int setAge(int age) { return age; } ``` Comments: ``` * Test 1 (0.0 out of 1) The compilation was successful The output should have been: setAge() Correct This is what was actually produced: setAge() not Correct ``` confused on why i get this error, is it because i have (int age) after setAge that is why the error is comming up?
2009/10/28
[ "https://Stackoverflow.com/questions/1640364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196341/" ]
Your mutator is not actually setting anything. I assume you already have a piece of code that you have to modify, search in that piece for a variable/field 'age'.
Assuming you have a class variable called 'age', you can create the mutator class method as: ``` public class myTest{ public int age; //other code here..if any public void setAge(int age) { this.age = age; } //other code here.. if any } ``` Normally your setAge method should not return anything. Mutator only modifies the value. To return value you should use getAge() method which is called 'Accessor'.
1,640,364
Revision of mutator method definition Write a mutator method setAge() that takes a single parameter of type int and sets the value of variable age Paste your answer in here: ``` public int setAge(int age) { return age; } ``` Comments: ``` * Test 1 (0.0 out of 1) The compilation was successful The output should have been: setAge() Correct This is what was actually produced: setAge() not Correct ``` confused on why i get this error, is it because i have (int age) after setAge that is why the error is comming up?
2009/10/28
[ "https://Stackoverflow.com/questions/1640364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196341/" ]
Your code does not "set the value of a variable age". Your method only returns the value that was passed to it.
Assuming you have a class variable called 'age', you can create the mutator class method as: ``` public class myTest{ public int age; //other code here..if any public void setAge(int age) { this.age = age; } //other code here.. if any } ``` Normally your setAge method should not return anything. Mutator only modifies the value. To return value you should use getAge() method which is called 'Accessor'.
214,395
I'm running through the popular python practice exercises located at github: <https://github.com/zhiwehu/Python-programming-exercises/blob/master/100%2B%20Python%20challenging%20programming%20exercises.txt> I recently discovered recursive functions. So when asked the following in the above link: ``` Question 9 Level 2 Question£º Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized. Suppose the following input is supplied to the program: Hello world Practice makes perfect Then, the output should be: HELLO WORLD PRACTICE MAKES PERFECT ``` My answer is: ``` def capitalize_line(string=""): """Capitalize and add a newline to the input str(if present)""" inp = input("enter: ").upper() string = "\n".join([string, inp]) if string and inp else "".join([string, inp]) if not inp: print(string) return string return capitalize_line(string=string) ``` E.g. Two inputs of 'hello' and 'world' would return 'HELLO\nWORLD'. Is this a suitable solution? Pythonic? The link answer was: ``` Solution: lines = [] while True: s = raw_input() if s: lines.append(s.upper()) else: break; for sentence in lines: print sentence ```
2019/02/27
[ "https://codereview.stackexchange.com/questions/214395", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/161732/" ]
Is this pythonic ? ------------------ The answer to this question is often found by doing `import this`: > > Beautiful is better than ugly. > > Explicit is better than implicit. > > Simple is better than complex. > > Complex is better than complicated. > > Flat is better than nested. > > Sparse is better than dense. > > Readability counts. > > Special cases aren't special enough to break the rules. > > Although practicality beats purity. > > Errors should never pass silently. > > Unless explicitly silenced. > > In the face of ambiguity, refuse the temptation to guess. > > There should be one-- and preferably only one --obvious way to do it. > > Although that way may not be obvious at first unless you're Dutch. > > Now is better than never. > > Although never is often better than *right* now. > > If the implementation is hard to explain, it's a bad idea. > > If the implementation is easy to explain, it may be a good idea. > > Namespaces are one honking great idea -- let's do more of those! > > > --- Why is this line not pythonic ? Because it is not readable enough. > > Readability counts. > > > ``` string = "\n".join([string, inp]) if string and inp else "".join([string, inp]) ``` --- Why is this line not pythonic ? Because it contains more than one instruction by line > > Sparse is better than dense. > > > ``` string = ('\n' if string and inp else '').join([string, inp]) ``` --- Why is this line not pythonic ? Still not the prettiest way of writing that. > > Beautiful is better than ugly. > > > ``` delimiter = '\n' if string and inp else '' string = delimiter.join([string, inp]) ``` I will say later in this post why this is still ugly and how to improve this code. --- Is a recursive function pythonic ? ---------------------------------- No, yes, it's complicated. First, the **call stack hell**. Every time you call a function, python has to "store" the addresses of the caller into a call stack, the depth of the call stack is 1000, which is not much. So... 1. `while` and `for` are often better than recursive in terms of readability (not always true) 2. `while` and `for` are often better than recursive in terms of performance (not always true) 3. Everything that can be done in a loop can be done recursively (with python not always true) 4. Everything that can be done recursively can be done with a while or for loop. (always true) 5. The stack is the limit. 1000 calls comes quick, for example there are more than 1000 words in this post, it wouldn't be a good idea to use recursion to parse it, it would raise a `RecursionError: maximum recursion depth exceeded`. --- Is my implementation of a recursive function good ? --------------------------------------------------- No, because you pass the accumulator as an argument (classic beginner mistake). You think in terms of loops, even when using recursion. Let's take a look at a simple function. ``` def sum(l): # No hidden mystery accumulator if len(l)==1: # The first line is usually the stop condition return l[0] # Return the last element return l[0] + sum(l[1:]) # Return the first + the sum of the rest sum(range(42)) # 861 ``` Let's take a closer look at how it calculates this: ``` def sum(l): if len(l)==1: return l[0] return f"({l[0]}+{sum(l[1:])})" sum(range(10)) # '(0+(1+(2+(3+(4+(5+(6+(7+(8+9)))))))))' ``` Impressive ! --- Now look at your function: ``` def capitalize_line(string=""): # Hidden mystery accumulator inp = input("enter: ").upper() # Move this outside of your function # This line is already debunked string = "\n".join([string, inp]) if string and inp else "".join([string, inp]) if not inp: print(string) # Move this outside of your function return string # You don't use this but you should return capitalize_line(string=string) # not using return as intended # (carrying processed data down the call stack) ``` > > Explicit is better than implicit. > > > Using `stdin` and `stdout` inside a function whose purpose is to `capitalize` letters is not a good thing. It makes the code impossible to divide because everything is linked. The `capitalize` function should capitalize and return a string and nothing else. How should I write it ? ----------------------- You think I will give you the solution like that... I'm sorry Dave, I'm afraid I can't do that ! Just kidding, but promise me you will try before looking at it: > > > ``` > def capitalize(l): > if not l: > return '' > return l[0].upper() + '\n' + capitalize(l[1:]) > > ``` > > > ``` > def capitalize(l): # alternative way > if len(l)==1: > return l[0] > return l[0].upper() + '\n' + capitalize(l[1:]) > > ``` > > > ``` > def main(): # Python 3.8 only > inputs = [] > while s:=input('enter: '): inputs.append(s) > print(capitalize(inputs)) > > ``` > > > ``` > def main(): > inputs = [] > while True: > s = input('enter: ') > if not s: > break > inputs.append(s) > print(capitalize(inputs)) > > ``` > > > ``` > if __name__ == '__main__': > main() # In case someone imports your module to use your functions > ``` > > But You want to do like the pros don't you ? Use generators > > ``` > def capitalize(iterable): > try: > s = next(iterable) > except StopIteration: > return '' > return s.upper() + '\n' + capitalize(iterable) > > ``` > > > ``` > def inputs(): > while True: > s = input('enter: ') > if not s: > break > yield s > > ``` > > Even better (or worse), a recursive generator: > > ``` > def inputs(): > s = input('enter: ') > if not s: return > yield s > yield from inputs() > > ``` > > > ``` > def main(): > print(capitalize(inputs())) > > ``` > > > > Wow, you're still there, it means you had the time to read my entire post, and since you've time on your hands, I recommend you [Socratica](https://www.youtube.com/socratica), more specifically [the video about recursion](https://www.youtube.com/watch?v=Qk0zUZW-U_M&list=PLi01XoE8jYohWFPpC17Z-wWhPOSuh8Er-&index=18). And remember, recursion isn't often the best solution.
While [the answer](https://codereview.stackexchange.com/a/214407/98493) by [@BenoîtPilatte](https://codereview.stackexchange.com/users/193138/beno%C3%AEt-pilatte) is fine as long as you want to keep this a recursive solution, here is a solution using only generators. First, [Python 2 is going to be no longer supported in less than a year](https://pythonclock.org/). If you have not yet switched to Python 3, now is the time. As a small incentive I am going to assume Python 3 in the rest of this answer. Now, let's start by building a generator that takes the user input until an empty line is entered: ``` def user_input(): while True: s = input() if not s: return yield s ``` That was easy, and now we are already done, because we can just use `str.upper` directly, since the output of `input` is a string, no need for a recursive function to do it for you: ``` def solution(): for line in user_input(): print(line.upper()) ``` Alternatively we can chain generators and use [`map`](https://docs.python.org/3/library/functions.html#map): ``` def solution(): for line in map(str.upper, user_input()): print(line) ``` As you can see this is vastly shorter and more readable, regardless of the stack size limit in Python.
2,422,071
There are $14$ more cookies than biscuits in a jar of $38$ cookies and biscuits. How many cookies are in the jar?
2017/09/08
[ "https://math.stackexchange.com/questions/2422071", "https://math.stackexchange.com", "https://math.stackexchange.com/users/478813/" ]
Solve the following system. $$x-y=14$$ and $$x+y=38$$
Think of starting with a jar of $38$ cookies and no biscuits, and turning cookies into biscuits one by one. Each time you do this you reduce the excess of cookies over biscuits by $2$. How many times would you have to do it to make that excess be $14$?
2,422,071
There are $14$ more cookies than biscuits in a jar of $38$ cookies and biscuits. How many cookies are in the jar?
2017/09/08
[ "https://math.stackexchange.com/questions/2422071", "https://math.stackexchange.com", "https://math.stackexchange.com/users/478813/" ]
Solve the following system. $$x-y=14$$ and $$x+y=38$$
A non algebraic technique useful for simpler word problems: *hypothesise*, i.e. start with *Suppose...* Suppose you removed those "extra" $14$ cookies. What's the total number of snacks now? Can you see that the remaining biscuits and cookies are now equal in number? Can you figure out how many cookies you have now? Can you work out how many you started with before you removed $14$?
42,977,235
I am making a script that lists the existing files in a directory,and then save them to a dictionary list. In the directory there are two types of images, "foo" and "bar", which at the end of the name have an identifier to know the position in which they should be viewed, for example: ``` foo_1.jpg foo_2.jpg foo_5.jpg bar_1.jpg bar_2.jpg bar_3.jpg ``` And I want to get the next result: ``` files = [ {'position': 1, 'foo': '/img/foo_1.jpg','bar': '/img/bar_1.jpg'}, {'position': 2, 'foo': '/img/foo_2.jpg','bar': '/img/bar_2.jpg'}, {'position': 3, 'foo': '','bar': '/img/bar_3.jpg', {'position': 5, 'foo': '/img/foo_5.jpg','bar': ''} ] ``` There's my code: ``` def files_in_folder(folder_name): folder_path = os.path.join(current_app.config['UPLOAD_FOLDER'], 'files', str(folder_name)) data = [] if not os.path.isdir(folder_path): return [{}, {}, {}, {}, {}, {}, {}, {}, {}] else: for filename in os.listdir(folder_path): position = int(re.search('[0-9]+', filename).group()) if "foo" in filename: foo_register = {'position': position, 'foo': folder_path + '/' + filename, 'bar': ''} else: bar_register = {'position': position, 'foo': '', 'bar': folder_path + '/' + filename } register = {**foo_register, **bar_register} data.insert(position-1, register) print(data) ``` My result is: ``` [{'foo': '', 'bar': 'uploads/campaigns/1/bar_1.png', 'position': 1}, {'foo': '', 'bar': 'uploads/campaigns/1/bar_2.png', 'position': 2}, {'foo': '', 'bar': 'uploads/campaigns/1/bar_3.png', 'position': 3}, {'foo': 'uploads/campaigns/1/foo_1.png', 'bar': '', 'position': 1, {'foo': '', 'bar': 'uploads/campaigns/1/bar_3.png', 'position': 3}] ``` What I'm missing in my code?. There's a best pythonic way to do this? Thanks in advance.
2017/03/23
[ "https://Stackoverflow.com/questions/42977235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/59468/" ]
Obviously, I don't have those files on my HD, so here's some code that processes a list of file names, but it shouldn't be hard to adapt it for your purposes. The heart of this code is a helper function `parse_name` that extracts the position (`pos`) and image type info (`kind`) from a file name. To organize that info the way you want I put it into a dict of dicts. We then sort the keys of the outer dict to create the desired list of dicts. We use a numeric sort so that `11` doesn't sort before `2`, etc. ``` import os.path from pprint import pprint data = '''\ /img/foo_1.jpg /img/foo_2.jpg /img/foo_5.jpg /img/bar_1.jpg /img/bar_2.jpg /img/bar_3.jpg '''.splitlines() def parse_name(s): fname = os.path.basename(s) fbase, _ = os.path.splitext(fname) kind, pos = fbase.split('_') return kind, int(pos) files_dict = {} for s in data: kind, pos = parse_name(s) d = files_dict.setdefault(pos, {'position': pos}) d[kind] = s pprint(files_dict) print() files_list = [files_dict[k] for k in sorted(files_dict.keys(), key=int)] pprint(files_list) ``` **output** ``` {1: {'bar': '/img/bar_1.jpg', 'foo': '/img/foo_1.jpg', 'position': 1}, 2: {'bar': '/img/bar_2.jpg', 'foo': '/img/foo_2.jpg', 'position': 2}, 3: {'bar': '/img/bar_3.jpg', 'position': 3}, 5: {'foo': '/img/foo_5.jpg', 'position': 5}} [{'bar': '/img/bar_1.jpg', 'foo': '/img/foo_1.jpg', 'position': 1}, {'bar': '/img/bar_2.jpg', 'foo': '/img/foo_2.jpg', 'position': 2}, {'bar': '/img/bar_3.jpg', 'position': 3}, {'foo': '/img/foo_5.jpg', 'position': 5}] ``` --- Actually, we don't need that sort key function, since `pos` has already been converted to `int` in `parse_name`. Oops! :) So we can just do: ``` files_list = [files_dict[k] for k in sorted(files_dict.keys())] ``` --- That `for` loop *could* be condensed to: ``` for s in data: kind, pos = parse_name(s) files_dict.setdefault(pos, {'position': pos})[kind] = s ``` although that's even more cryptic than the previous version. ;) ``` files_dict.setdefault(pos, {'position': pos}) ``` fetches the sub-dict in `files_dict` with the key `pos`. If it doesn't exist, it's created with an initial key-value pair of `('position', pos)`. We then update that sub-dict with the `(kind, s)`, where `s` is the full filename of the the current file.
1. Try to use `filename.startswith('bar')` or `filename.startswith('foo')` to distinguish `foo_1.jpg` and `bar_1.jpg` 2. Try to use `position=int(os.path.splitext(filename)[0].split('_')[-1])` instead of `re`. --- 3. Don't use `register = {**foo_register, **bar_register}` : e.g. ``` a={'foo': '', 'bar': 'uploads/campaigns/1/bar_1.png', 'position': 1} b={'foo': 'uploads/campaigns/1/foo_.png', 'bar': '', 'position': 1} print({**a,**b}) ``` Output: ``` {'foo': 'uploads/campaigns/1/foo_.png', 'bar': '', 'position': 1} ``` I think this is why you got the unexpected result. You can try this: ``` a.update({k:v for k,v in b.items() if v}) print(a) ``` Output: ``` {'foo': 'uploads/campaigns/1/foo_.png', 'bar': 'uploads/campaigns/1/bar_1.png', 'position': 1} ```
42,977,235
I am making a script that lists the existing files in a directory,and then save them to a dictionary list. In the directory there are two types of images, "foo" and "bar", which at the end of the name have an identifier to know the position in which they should be viewed, for example: ``` foo_1.jpg foo_2.jpg foo_5.jpg bar_1.jpg bar_2.jpg bar_3.jpg ``` And I want to get the next result: ``` files = [ {'position': 1, 'foo': '/img/foo_1.jpg','bar': '/img/bar_1.jpg'}, {'position': 2, 'foo': '/img/foo_2.jpg','bar': '/img/bar_2.jpg'}, {'position': 3, 'foo': '','bar': '/img/bar_3.jpg', {'position': 5, 'foo': '/img/foo_5.jpg','bar': ''} ] ``` There's my code: ``` def files_in_folder(folder_name): folder_path = os.path.join(current_app.config['UPLOAD_FOLDER'], 'files', str(folder_name)) data = [] if not os.path.isdir(folder_path): return [{}, {}, {}, {}, {}, {}, {}, {}, {}] else: for filename in os.listdir(folder_path): position = int(re.search('[0-9]+', filename).group()) if "foo" in filename: foo_register = {'position': position, 'foo': folder_path + '/' + filename, 'bar': ''} else: bar_register = {'position': position, 'foo': '', 'bar': folder_path + '/' + filename } register = {**foo_register, **bar_register} data.insert(position-1, register) print(data) ``` My result is: ``` [{'foo': '', 'bar': 'uploads/campaigns/1/bar_1.png', 'position': 1}, {'foo': '', 'bar': 'uploads/campaigns/1/bar_2.png', 'position': 2}, {'foo': '', 'bar': 'uploads/campaigns/1/bar_3.png', 'position': 3}, {'foo': 'uploads/campaigns/1/foo_1.png', 'bar': '', 'position': 1, {'foo': '', 'bar': 'uploads/campaigns/1/bar_3.png', 'position': 3}] ``` What I'm missing in my code?. There's a best pythonic way to do this? Thanks in advance.
2017/03/23
[ "https://Stackoverflow.com/questions/42977235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/59468/" ]
1. Try to use `filename.startswith('bar')` or `filename.startswith('foo')` to distinguish `foo_1.jpg` and `bar_1.jpg` 2. Try to use `position=int(os.path.splitext(filename)[0].split('_')[-1])` instead of `re`. --- 3. Don't use `register = {**foo_register, **bar_register}` : e.g. ``` a={'foo': '', 'bar': 'uploads/campaigns/1/bar_1.png', 'position': 1} b={'foo': 'uploads/campaigns/1/foo_.png', 'bar': '', 'position': 1} print({**a,**b}) ``` Output: ``` {'foo': 'uploads/campaigns/1/foo_.png', 'bar': '', 'position': 1} ``` I think this is why you got the unexpected result. You can try this: ``` a.update({k:v for k,v in b.items() if v}) print(a) ``` Output: ``` {'foo': 'uploads/campaigns/1/foo_.png', 'bar': 'uploads/campaigns/1/bar_1.png', 'position': 1} ```
``` import os, re cwd = os.getcwd() print cwd def update(li, pos, path, key): added = False if len(li) == 0: di=dict() di["position"] = int(pos) di[key] = path li.append(di) added = True else: for di in li: if di["position"]==pos: di[key] = path added = True if not added: di=dict() di["position"] = int(pos) di[key] = path li.append(di) li = [] for filename in os.listdir(cwd+r'/try'): # folder name where my files are. position = int(re.search('[0-9]+', filename).group()) print filename, position path = cwd + '/' + filename if "foo" in filename: update(li, position, path, "foo") elif "bar" in filename: update(li, position, path, "bar") print li ```
42,977,235
I am making a script that lists the existing files in a directory,and then save them to a dictionary list. In the directory there are two types of images, "foo" and "bar", which at the end of the name have an identifier to know the position in which they should be viewed, for example: ``` foo_1.jpg foo_2.jpg foo_5.jpg bar_1.jpg bar_2.jpg bar_3.jpg ``` And I want to get the next result: ``` files = [ {'position': 1, 'foo': '/img/foo_1.jpg','bar': '/img/bar_1.jpg'}, {'position': 2, 'foo': '/img/foo_2.jpg','bar': '/img/bar_2.jpg'}, {'position': 3, 'foo': '','bar': '/img/bar_3.jpg', {'position': 5, 'foo': '/img/foo_5.jpg','bar': ''} ] ``` There's my code: ``` def files_in_folder(folder_name): folder_path = os.path.join(current_app.config['UPLOAD_FOLDER'], 'files', str(folder_name)) data = [] if not os.path.isdir(folder_path): return [{}, {}, {}, {}, {}, {}, {}, {}, {}] else: for filename in os.listdir(folder_path): position = int(re.search('[0-9]+', filename).group()) if "foo" in filename: foo_register = {'position': position, 'foo': folder_path + '/' + filename, 'bar': ''} else: bar_register = {'position': position, 'foo': '', 'bar': folder_path + '/' + filename } register = {**foo_register, **bar_register} data.insert(position-1, register) print(data) ``` My result is: ``` [{'foo': '', 'bar': 'uploads/campaigns/1/bar_1.png', 'position': 1}, {'foo': '', 'bar': 'uploads/campaigns/1/bar_2.png', 'position': 2}, {'foo': '', 'bar': 'uploads/campaigns/1/bar_3.png', 'position': 3}, {'foo': 'uploads/campaigns/1/foo_1.png', 'bar': '', 'position': 1, {'foo': '', 'bar': 'uploads/campaigns/1/bar_3.png', 'position': 3}] ``` What I'm missing in my code?. There's a best pythonic way to do this? Thanks in advance.
2017/03/23
[ "https://Stackoverflow.com/questions/42977235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/59468/" ]
Obviously, I don't have those files on my HD, so here's some code that processes a list of file names, but it shouldn't be hard to adapt it for your purposes. The heart of this code is a helper function `parse_name` that extracts the position (`pos`) and image type info (`kind`) from a file name. To organize that info the way you want I put it into a dict of dicts. We then sort the keys of the outer dict to create the desired list of dicts. We use a numeric sort so that `11` doesn't sort before `2`, etc. ``` import os.path from pprint import pprint data = '''\ /img/foo_1.jpg /img/foo_2.jpg /img/foo_5.jpg /img/bar_1.jpg /img/bar_2.jpg /img/bar_3.jpg '''.splitlines() def parse_name(s): fname = os.path.basename(s) fbase, _ = os.path.splitext(fname) kind, pos = fbase.split('_') return kind, int(pos) files_dict = {} for s in data: kind, pos = parse_name(s) d = files_dict.setdefault(pos, {'position': pos}) d[kind] = s pprint(files_dict) print() files_list = [files_dict[k] for k in sorted(files_dict.keys(), key=int)] pprint(files_list) ``` **output** ``` {1: {'bar': '/img/bar_1.jpg', 'foo': '/img/foo_1.jpg', 'position': 1}, 2: {'bar': '/img/bar_2.jpg', 'foo': '/img/foo_2.jpg', 'position': 2}, 3: {'bar': '/img/bar_3.jpg', 'position': 3}, 5: {'foo': '/img/foo_5.jpg', 'position': 5}} [{'bar': '/img/bar_1.jpg', 'foo': '/img/foo_1.jpg', 'position': 1}, {'bar': '/img/bar_2.jpg', 'foo': '/img/foo_2.jpg', 'position': 2}, {'bar': '/img/bar_3.jpg', 'position': 3}, {'foo': '/img/foo_5.jpg', 'position': 5}] ``` --- Actually, we don't need that sort key function, since `pos` has already been converted to `int` in `parse_name`. Oops! :) So we can just do: ``` files_list = [files_dict[k] for k in sorted(files_dict.keys())] ``` --- That `for` loop *could* be condensed to: ``` for s in data: kind, pos = parse_name(s) files_dict.setdefault(pos, {'position': pos})[kind] = s ``` although that's even more cryptic than the previous version. ;) ``` files_dict.setdefault(pos, {'position': pos}) ``` fetches the sub-dict in `files_dict` with the key `pos`. If it doesn't exist, it's created with an initial key-value pair of `('position', pos)`. We then update that sub-dict with the `(kind, s)`, where `s` is the full filename of the the current file.
``` import os, re cwd = os.getcwd() print cwd def update(li, pos, path, key): added = False if len(li) == 0: di=dict() di["position"] = int(pos) di[key] = path li.append(di) added = True else: for di in li: if di["position"]==pos: di[key] = path added = True if not added: di=dict() di["position"] = int(pos) di[key] = path li.append(di) li = [] for filename in os.listdir(cwd+r'/try'): # folder name where my files are. position = int(re.search('[0-9]+', filename).group()) print filename, position path = cwd + '/' + filename if "foo" in filename: update(li, position, path, "foo") elif "bar" in filename: update(li, position, path, "bar") print li ```
38,603,176
This is for InnoDB with MySQL 5.7. If I have a query like: ``` SELECT A, B, C FROM TABLE WHERE STRCMP(D, 'somestring') > 0 ``` Is it possible to have an index on `D` which can be used by the query? i.e. is MySQL smart enough to use the btree index for STRCMP function? If not, how might I be able to redesign the query (and/or table) such that I can do string comparison on D, and there can be some form of pruning so that it does not have to hit every single row?
2016/07/27
[ "https://Stackoverflow.com/questions/38603176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/254959/" ]
Why not just ``` WHERE D > 'somestring' ``` This would leverage a typical B-tree index on column `D`.
Mysql will not use indexes for function calls. Use below query And Create index on **D** column ``` SELECT A, B, C FROM TABLE WHERE D ='somestring' ``` to create index use the below query ``` create index index1 on TABLE(D); ```
38,603,176
This is for InnoDB with MySQL 5.7. If I have a query like: ``` SELECT A, B, C FROM TABLE WHERE STRCMP(D, 'somestring') > 0 ``` Is it possible to have an index on `D` which can be used by the query? i.e. is MySQL smart enough to use the btree index for STRCMP function? If not, how might I be able to redesign the query (and/or table) such that I can do string comparison on D, and there can be some form of pruning so that it does not have to hit every single row?
2016/07/27
[ "https://Stackoverflow.com/questions/38603176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/254959/" ]
If you perform comparisons only by passing column values to a function such as `STRCMP()`, there is no value in indexing it. Reference: <https://dev.mysql.com/doc/refman/5.5/en/index-btree-hash.html> A B-tree index can be used for column comparisons in expressions that use the `=`, `>`, `>=`, `<`, `<=`, or `BETWEEN` operators. So, you may use `SELECT A, B, C FROM TABLE WHERE D > 'somestring'` instead, while `LIKE` is more strict and could be what you expect. Also, you can use the `COLLATE` operator to convert the column to a case-sensitive collation, to make sure it's comparing the case as well. `SELECT A, B, C FROM TABLE WHERE D > 'somestring' COLLATE utf8_bin`
Mysql will not use indexes for function calls. Use below query And Create index on **D** column ``` SELECT A, B, C FROM TABLE WHERE D ='somestring' ``` to create index use the below query ``` create index index1 on TABLE(D); ```
38,603,176
This is for InnoDB with MySQL 5.7. If I have a query like: ``` SELECT A, B, C FROM TABLE WHERE STRCMP(D, 'somestring') > 0 ``` Is it possible to have an index on `D` which can be used by the query? i.e. is MySQL smart enough to use the btree index for STRCMP function? If not, how might I be able to redesign the query (and/or table) such that I can do string comparison on D, and there can be some form of pruning so that it does not have to hit every single row?
2016/07/27
[ "https://Stackoverflow.com/questions/38603176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/254959/" ]
Amazing how many wrong answers so far. Let me see if I can not join them. `STRCMP` returns -1, 0, or 1, depending on how the arguments compare. `STRCMP(D, 'somestring') > 0` is identical to `D > 'somestring'`. (Not `>=`, not `=`, not `LIKE`) Actually, there *may* be collation differences, but that can be handled if necessary. Any function, and certain operators, 'hide' columns from use with `INDEXes`. `D > 'somestring'` can benefit from an index starting with `D`; the `STRCMP` version cannot.
Mysql will not use indexes for function calls. Use below query And Create index on **D** column ``` SELECT A, B, C FROM TABLE WHERE D ='somestring' ``` to create index use the below query ``` create index index1 on TABLE(D); ```
38,603,176
This is for InnoDB with MySQL 5.7. If I have a query like: ``` SELECT A, B, C FROM TABLE WHERE STRCMP(D, 'somestring') > 0 ``` Is it possible to have an index on `D` which can be used by the query? i.e. is MySQL smart enough to use the btree index for STRCMP function? If not, how might I be able to redesign the query (and/or table) such that I can do string comparison on D, and there can be some form of pruning so that it does not have to hit every single row?
2016/07/27
[ "https://Stackoverflow.com/questions/38603176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/254959/" ]
Why not just ``` WHERE D > 'somestring' ``` This would leverage a typical B-tree index on column `D`.
If you perform comparisons only by passing column values to a function such as `STRCMP()`, there is no value in indexing it. Reference: <https://dev.mysql.com/doc/refman/5.5/en/index-btree-hash.html> A B-tree index can be used for column comparisons in expressions that use the `=`, `>`, `>=`, `<`, `<=`, or `BETWEEN` operators. So, you may use `SELECT A, B, C FROM TABLE WHERE D > 'somestring'` instead, while `LIKE` is more strict and could be what you expect. Also, you can use the `COLLATE` operator to convert the column to a case-sensitive collation, to make sure it's comparing the case as well. `SELECT A, B, C FROM TABLE WHERE D > 'somestring' COLLATE utf8_bin`
38,603,176
This is for InnoDB with MySQL 5.7. If I have a query like: ``` SELECT A, B, C FROM TABLE WHERE STRCMP(D, 'somestring') > 0 ``` Is it possible to have an index on `D` which can be used by the query? i.e. is MySQL smart enough to use the btree index for STRCMP function? If not, how might I be able to redesign the query (and/or table) such that I can do string comparison on D, and there can be some form of pruning so that it does not have to hit every single row?
2016/07/27
[ "https://Stackoverflow.com/questions/38603176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/254959/" ]
Amazing how many wrong answers so far. Let me see if I can not join them. `STRCMP` returns -1, 0, or 1, depending on how the arguments compare. `STRCMP(D, 'somestring') > 0` is identical to `D > 'somestring'`. (Not `>=`, not `=`, not `LIKE`) Actually, there *may* be collation differences, but that can be handled if necessary. Any function, and certain operators, 'hide' columns from use with `INDEXes`. `D > 'somestring'` can benefit from an index starting with `D`; the `STRCMP` version cannot.
Why not just ``` WHERE D > 'somestring' ``` This would leverage a typical B-tree index on column `D`.
38,603,176
This is for InnoDB with MySQL 5.7. If I have a query like: ``` SELECT A, B, C FROM TABLE WHERE STRCMP(D, 'somestring') > 0 ``` Is it possible to have an index on `D` which can be used by the query? i.e. is MySQL smart enough to use the btree index for STRCMP function? If not, how might I be able to redesign the query (and/or table) such that I can do string comparison on D, and there can be some form of pruning so that it does not have to hit every single row?
2016/07/27
[ "https://Stackoverflow.com/questions/38603176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/254959/" ]
Amazing how many wrong answers so far. Let me see if I can not join them. `STRCMP` returns -1, 0, or 1, depending on how the arguments compare. `STRCMP(D, 'somestring') > 0` is identical to `D > 'somestring'`. (Not `>=`, not `=`, not `LIKE`) Actually, there *may* be collation differences, but that can be handled if necessary. Any function, and certain operators, 'hide' columns from use with `INDEXes`. `D > 'somestring'` can benefit from an index starting with `D`; the `STRCMP` version cannot.
If you perform comparisons only by passing column values to a function such as `STRCMP()`, there is no value in indexing it. Reference: <https://dev.mysql.com/doc/refman/5.5/en/index-btree-hash.html> A B-tree index can be used for column comparisons in expressions that use the `=`, `>`, `>=`, `<`, `<=`, or `BETWEEN` operators. So, you may use `SELECT A, B, C FROM TABLE WHERE D > 'somestring'` instead, while `LIKE` is more strict and could be what you expect. Also, you can use the `COLLATE` operator to convert the column to a case-sensitive collation, to make sure it's comparing the case as well. `SELECT A, B, C FROM TABLE WHERE D > 'somestring' COLLATE utf8_bin`
24,488,839
I'm using a jquery slider plugin and I have it working (new to jquery/css/html), but when I try to center the slider it breaks. The red dot that moves around the circle does not center along with the pictures? I'd like to understand why this is and how can it be fixed? Thank you very much. <http://jsfiddle.net/asQL9/> HTML ``` <div id="rotatescroll" class="centered"> <div class="viewport"> <ul class="overview"> <li><a href="http://www.baijs.nl"><img src="https://raw.githubusercontent.com/wieringen/tinycircleslider/master/examples/simple/images/hdr1.jpg" /></a> </li> <li><a href="http://www.baijs.nl"><img src="https://raw.githubusercontent.com/wieringen/tinycircleslider/master/examples/simple/images/hdr1.jpg" /></a> </li> <li><a href="http://www.baijs.nl"><img src="https://raw.githubusercontent.com/wieringen/tinycircleslider/master/examples/simple/images/hdr1.jpg" /></a> </li> <li><a href="http://www.baijs.nl"><img src="https://raw.githubusercontent.com/wieringen/tinycircleslider/master/examples/simple/images/hdr2.jpg" /></a> </li> <li><a href="http://www.baijs.nl"><img src="https://raw.githubusercontent.com/wieringen/tinycircleslider/master/examples/simple/images/hdr2.jpg" /></a> </li> </ul> </div> <div class="dot"></div> <div class="overlay"></div> <div class="thumb"></div> </div> ``` CSS ``` img { border: 0; } .centered { margin: 0 auto; } #rotatescroll { height:300px; position:relative; width:300px; } #rotatescroll .viewport{ height:290px; position: relative; margin:0 auto; overflow:hidden; width:290px; border-radius: 50%; } #rotatescroll .overview { position: absolute; width: 798px; list-style: none; margin: 0; padding: 0; left: 0; top: 0; } #rotatescroll .overview li { height:300px; width:300px; float: left; position: relative; } #rotatescroll .thumb { background:url('http://baijs.com/tinycircleslider/images/bg-thumb.png') no-repeat 50% 50%; position: absolute; top: -3px; cursor: pointer; left: 137px; width: 100px; z-index: 200; height: 100px; } #rotatescroll .dot { background:url('http://baijs.com/tinycircleslider/images/bg-dot.png') no-repeat 0 0; display: none; height: 12px; width: 12px; position: absolute; left: 155px; top: 3px; z-index: 100; } #rotatescroll .dot span { display: none; } #rotatescroll .overlay {background:url('http://i.imgur.com/PtgjArP.png') no-repeat 0 0; pointer-events: none; position: absolute; left: 0; top: -2px; height:300px; width:300px; } .highlight, .indicator{background-color:#FC0;} ``` jquery ``` $('#rotatescroll').tinycircleslider({ interval: true, dotsSnap: true, intervalTime: 1000 }); ```
2014/06/30
[ "https://Stackoverflow.com/questions/24488839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1009762/" ]
Looks like you built all of the dependencies outside of the gcc packaging. Included is a script that will gather all of the dependencies into the gcc packaging and include them as part of the gcc build: ``` gcc-4.9.0/contrib/download_prerequisites ``` That should simplify your initial configuration. Not sure what compiler and/or version being used to build the 4.9.0 gcc compiler. Assuming 3.4-ish if you are still on RHEL 4. Probably will need to build/install 4.2.x gcc in order to incrementally get the support required to build 4.9.x due to lack of pre-built gcc support for RHEL 4. It's the price of staying on an older platform.
Two problems: First, you should never build the compiler in the source directory. It might appear to work, sometimes, but it's not supported and the compiler developers don't do that, so you shouldn't. Create an external `obj` directory, and build there: ``` mkdir obj cd obj /path/to/src/configure ...blah...blah...blah ``` Second, you missed a step: ``` make make install ``` I know lots of projects set up the makefile so that `make install` just works, but bootstrapping a compiler is a bit more complicated than most projects.
18,962
In Western Europe, we currently have a long spell of warm and dry weather. The perfect moment to combine sunbathing with working from home. However, outside in the sun, the legibility of my laptop screen is greatly reduced when compared to inside the house/office, even when I maximize the display's brightness. Are there any tricks I can use to increase the legibility (and ultimately my productivity)? I'll share one trick I often use, but I'm definitely interested in more suggestions.
2018/07/28
[ "https://lifehacks.stackexchange.com/questions/18962", "https://lifehacks.stackexchange.com", "https://lifehacks.stackexchange.com/users/5345/" ]
I forgot where I saw/heard this tip, but I'm often using a [cardboard](https://en.wikipedia.org/wiki/Cardboard) box slightly larger than the laptop to provide shade on the display. At least for me, this makes it more legible. An additional benefit is that this also reduces the amount of sunlight on the laptop, which keeps it cooler and avoids the processor being underclocked, which would decrease performance. A slight disadvantage is that it also partially blocks the sun's rays to my upper body and arms. Here is how it looks like: [![enter image description here](https://i.stack.imgur.com/LtVDtm.jpg)](https://i.stack.imgur.com/LtVDt.jpg)
The cardboard box suggested by Glorfindel, and improved upon by Stan's comment, is fantastic. I have another suggestion that can be used with the box or by itself. Wear a dark shirt, and make sure whatever is behind you is dark. (A wall, a shaded forest, etc.) Much of the reason you can't see the screen is because of reflected light. Therefore, if the screen is facing something dark, there will be less light for it to reflect, and you will be able to see the screen's display better.
18,962
In Western Europe, we currently have a long spell of warm and dry weather. The perfect moment to combine sunbathing with working from home. However, outside in the sun, the legibility of my laptop screen is greatly reduced when compared to inside the house/office, even when I maximize the display's brightness. Are there any tricks I can use to increase the legibility (and ultimately my productivity)? I'll share one trick I often use, but I'm definitely interested in more suggestions.
2018/07/28
[ "https://lifehacks.stackexchange.com/questions/18962", "https://lifehacks.stackexchange.com", "https://lifehacks.stackexchange.com/users/5345/" ]
I forgot where I saw/heard this tip, but I'm often using a [cardboard](https://en.wikipedia.org/wiki/Cardboard) box slightly larger than the laptop to provide shade on the display. At least for me, this makes it more legible. An additional benefit is that this also reduces the amount of sunlight on the laptop, which keeps it cooler and avoids the processor being underclocked, which would decrease performance. A slight disadvantage is that it also partially blocks the sun's rays to my upper body and arms. Here is how it looks like: [![enter image description here](https://i.stack.imgur.com/LtVDtm.jpg)](https://i.stack.imgur.com/LtVDt.jpg)
To increase the legibility of a computer screen, arrangement should be made to control the fall of run rays directly on the computer screen. This can be done by covering the top of the computer by some wooden surface or cloth , in such a way that the area of the wooden surface or the cloth is more than the area of the top surface of the computer.
18,962
In Western Europe, we currently have a long spell of warm and dry weather. The perfect moment to combine sunbathing with working from home. However, outside in the sun, the legibility of my laptop screen is greatly reduced when compared to inside the house/office, even when I maximize the display's brightness. Are there any tricks I can use to increase the legibility (and ultimately my productivity)? I'll share one trick I often use, but I'm definitely interested in more suggestions.
2018/07/28
[ "https://lifehacks.stackexchange.com/questions/18962", "https://lifehacks.stackexchange.com", "https://lifehacks.stackexchange.com/users/5345/" ]
I forgot where I saw/heard this tip, but I'm often using a [cardboard](https://en.wikipedia.org/wiki/Cardboard) box slightly larger than the laptop to provide shade on the display. At least for me, this makes it more legible. An additional benefit is that this also reduces the amount of sunlight on the laptop, which keeps it cooler and avoids the processor being underclocked, which would decrease performance. A slight disadvantage is that it also partially blocks the sun's rays to my upper body and arms. Here is how it looks like: [![enter image description here](https://i.stack.imgur.com/LtVDtm.jpg)](https://i.stack.imgur.com/LtVDt.jpg)
In my experience many command line users have bright font on dark background terminal emulators (usually white on black, or matrix-movie green on black), while in bright environments (e.g. outside work), a dark font on a bright background is more legible (black on white). Of cause this mainly addresses command line users, afaik, office applications are already dark on bright.
18,962
In Western Europe, we currently have a long spell of warm and dry weather. The perfect moment to combine sunbathing with working from home. However, outside in the sun, the legibility of my laptop screen is greatly reduced when compared to inside the house/office, even when I maximize the display's brightness. Are there any tricks I can use to increase the legibility (and ultimately my productivity)? I'll share one trick I often use, but I'm definitely interested in more suggestions.
2018/07/28
[ "https://lifehacks.stackexchange.com/questions/18962", "https://lifehacks.stackexchange.com", "https://lifehacks.stackexchange.com/users/5345/" ]
The cardboard box suggested by Glorfindel, and improved upon by Stan's comment, is fantastic. I have another suggestion that can be used with the box or by itself. Wear a dark shirt, and make sure whatever is behind you is dark. (A wall, a shaded forest, etc.) Much of the reason you can't see the screen is because of reflected light. Therefore, if the screen is facing something dark, there will be less light for it to reflect, and you will be able to see the screen's display better.
To increase the legibility of a computer screen, arrangement should be made to control the fall of run rays directly on the computer screen. This can be done by covering the top of the computer by some wooden surface or cloth , in such a way that the area of the wooden surface or the cloth is more than the area of the top surface of the computer.
18,962
In Western Europe, we currently have a long spell of warm and dry weather. The perfect moment to combine sunbathing with working from home. However, outside in the sun, the legibility of my laptop screen is greatly reduced when compared to inside the house/office, even when I maximize the display's brightness. Are there any tricks I can use to increase the legibility (and ultimately my productivity)? I'll share one trick I often use, but I'm definitely interested in more suggestions.
2018/07/28
[ "https://lifehacks.stackexchange.com/questions/18962", "https://lifehacks.stackexchange.com", "https://lifehacks.stackexchange.com/users/5345/" ]
In my experience many command line users have bright font on dark background terminal emulators (usually white on black, or matrix-movie green on black), while in bright environments (e.g. outside work), a dark font on a bright background is more legible (black on white). Of cause this mainly addresses command line users, afaik, office applications are already dark on bright.
To increase the legibility of a computer screen, arrangement should be made to control the fall of run rays directly on the computer screen. This can be done by covering the top of the computer by some wooden surface or cloth , in such a way that the area of the wooden surface or the cloth is more than the area of the top surface of the computer.
56,854,273
I am trying to write a piece of code that plots a list of markers on a map. The markers are formatted by longitude and latitude: ``` trip_markers[0:4]: [[40.64499, -73.78115], [40.766931, -73.982098], [40.77773, -73.951902], [40.795678, -73.971049]] ``` I am trying to write a function that iterates through this list, and plots each point on a map. ``` def map_from(location, zoom_amount): return folium.Map(location=location, zoom_start=zoom_amount) manhattan_map = map_from([40.7589, -73.9851], 13) ``` The code below seems to be the problem ``` def add_markers(markers, map_obj): for marker in markers: return marker and marker.add_to(map_obj) map_with_markers = add_markers(trip_markers, manhattan_map) ``` I expect my output of `map_with_markers` to produce a map with each point plotted However I am getting: ``` <folium.vector_layers.CircleMarker at 0x7f453a365c50> ```
2019/07/02
[ "https://Stackoverflow.com/questions/56854273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11664078/" ]
I suggest using *Linq*, [GroupBy](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.groupby?view=netframework-4.8): ``` using System.Linq; ... // No Sequential Order test var _entries = new List<string>() { "Awesom", "Bar", "Awesom", "Awesom", "Foo", "Awesom", "Bar", }; int count = _entries .GroupBy(item => item) .Sum(group => group.Count() - 1); ``` with a help of `GroupBy` we obtain `3` groups: ``` 4 items of "Awesom" 1 items of "Foo" 2 items of "Bar" ``` then we can just `Count` items in each group and `Sum` them: `(4 - 1) + (1 - 1) + (2 - 1) == 4` duplicates overall.
When you say *This one compares in sequential order but it should compare with every possible scenario.* I believe you are expecting value of **count = 16**. As by comparing with every possible values you'll have 16 combinations and as all the values are equal you'll get count as 16. ``` var _entries = new List<string>(); _entries.Add("Awesom"); _entries.Add("Awesom"); _entries.Add("Awesom"); _entries.Add("Awesom"); var query = from e1 in _entries from e2 in _entries where e1 == e2 select $"{e1} x {e2}"; var count = query.Count(); ``` Try printing values of query variable and you'll see all combinations.
13,643,706
I'm working on a asp.net page and I have several buttons in my page, some of them are asp.net buttons, other are HTML `input[type=button]` elements. HTML buttons are used to make AJAX calls. When the user press ENTER I need to set as default button one of these HTML buttons, but at the moment the first button in the page is trigged. Is there a way to set a plain HTML button as default on my form?
2012/11/30
[ "https://Stackoverflow.com/questions/13643706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1061499/" ]
read this article <http://www.codeproject.com/Articles/35180/How-To-set-Default-Button-for-ENTER-key-pressed-ev> you can use it in somewhat this way ``` <form id="form1" runat="server" defaultbutton="Button1" > ```
Can you not put the form inside a panel and use the defaultbutton property ``` <asp:Panel runat="server" DefaultButton="btnSomething"> ... </asp:Panel> ```
13,643,706
I'm working on a asp.net page and I have several buttons in my page, some of them are asp.net buttons, other are HTML `input[type=button]` elements. HTML buttons are used to make AJAX calls. When the user press ENTER I need to set as default button one of these HTML buttons, but at the moment the first button in the page is trigged. Is there a way to set a plain HTML button as default on my form?
2012/11/30
[ "https://Stackoverflow.com/questions/13643706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1061499/" ]
Try this : ``` // JavaScript Code var body = document.getElementsByTagName('body')[0]; body.onkeydown = function (e) { if (e.keyCode === 13) { //enter key code // call your html button onclick code here } } ```
Can you not put the form inside a panel and use the defaultbutton property ``` <asp:Panel runat="server" DefaultButton="btnSomething"> ... </asp:Panel> ```
13,643,706
I'm working on a asp.net page and I have several buttons in my page, some of them are asp.net buttons, other are HTML `input[type=button]` elements. HTML buttons are used to make AJAX calls. When the user press ENTER I need to set as default button one of these HTML buttons, but at the moment the first button in the page is trigged. Is there a way to set a plain HTML button as default on my form?
2012/11/30
[ "https://Stackoverflow.com/questions/13643706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1061499/" ]
I'm using JQuery, so I modified the code in the **Mohit Pandey** answer: ``` $("body").keypress(function (event) { if (event.which == 13) { event.preventDefault(); // my function } }); ```
Can you not put the form inside a panel and use the defaultbutton property ``` <asp:Panel runat="server" DefaultButton="btnSomething"> ... </asp:Panel> ```
13,643,706
I'm working on a asp.net page and I have several buttons in my page, some of them are asp.net buttons, other are HTML `input[type=button]` elements. HTML buttons are used to make AJAX calls. When the user press ENTER I need to set as default button one of these HTML buttons, but at the moment the first button in the page is trigged. Is there a way to set a plain HTML button as default on my form?
2012/11/30
[ "https://Stackoverflow.com/questions/13643706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1061499/" ]
Try this : ``` // JavaScript Code var body = document.getElementsByTagName('body')[0]; body.onkeydown = function (e) { if (e.keyCode === 13) { //enter key code // call your html button onclick code here } } ```
read this article <http://www.codeproject.com/Articles/35180/How-To-set-Default-Button-for-ENTER-key-pressed-ev> you can use it in somewhat this way ``` <form id="form1" runat="server" defaultbutton="Button1" > ```
13,643,706
I'm working on a asp.net page and I have several buttons in my page, some of them are asp.net buttons, other are HTML `input[type=button]` elements. HTML buttons are used to make AJAX calls. When the user press ENTER I need to set as default button one of these HTML buttons, but at the moment the first button in the page is trigged. Is there a way to set a plain HTML button as default on my form?
2012/11/30
[ "https://Stackoverflow.com/questions/13643706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1061499/" ]
I'm using JQuery, so I modified the code in the **Mohit Pandey** answer: ``` $("body").keypress(function (event) { if (event.which == 13) { event.preventDefault(); // my function } }); ```
read this article <http://www.codeproject.com/Articles/35180/How-To-set-Default-Button-for-ENTER-key-pressed-ev> you can use it in somewhat this way ``` <form id="form1" runat="server" defaultbutton="Button1" > ```
13,643,706
I'm working on a asp.net page and I have several buttons in my page, some of them are asp.net buttons, other are HTML `input[type=button]` elements. HTML buttons are used to make AJAX calls. When the user press ENTER I need to set as default button one of these HTML buttons, but at the moment the first button in the page is trigged. Is there a way to set a plain HTML button as default on my form?
2012/11/30
[ "https://Stackoverflow.com/questions/13643706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1061499/" ]
Try this : ``` // JavaScript Code var body = document.getElementsByTagName('body')[0]; body.onkeydown = function (e) { if (e.keyCode === 13) { //enter key code // call your html button onclick code here } } ```
I'm using JQuery, so I modified the code in the **Mohit Pandey** answer: ``` $("body").keypress(function (event) { if (event.which == 13) { event.preventDefault(); // my function } }); ```
72,884,629
``` <button type="button" class="action-oser" id="click-vlink2"> <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24"><path d="M12 2c5.514 0 10 4.486 10 10s-4.486 10-10 10-10-4.486-10-10 4.486-10 10-10zm0-2c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm-3 18v-12l10 6-10 6z" style="fill:#fff" /></svg> </button> <div id="video-modal2" style="display:none;"> <div class="content-oser"> <iframe width="560" height="315" id="youtube2" src="https://www.youtube.com/embed/JexOJOssGwk?rel=0&enablejsapi=1&origin=https%3A%2F%2Fwww.apetito.co.uk&widgetid=1" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </div> </div> <script> require( [ 'jquery', 'Magento_Ui/js/modal/modal' ], function( $, modal ) { var options = { type: 'popup', responsive: true, modalClass: 'nursery-modal', 'buttons': [{ class: 'action-oser' }] }; var popup = modal(options, $('#video-modal2')); $("#click-vlink2").on('click',function(){ $("#video-modal2").modal("openModal"); }); $('.action-close').on('click', function() { var video = $("#youtube2").attr("src"); $("#youtube2").attr("src",""); $("#youtube2").attr("src",video); }); } ); </script> ``` I added above script for modal popup video. i added this width="560" height="315" in iframe and it is required size for desktop. But when i'm checking in the mobile devices its not fit according to the mobile device. How can i make this responsive to the all mobile devices also. Any help can be appreciated. Thanks!
2022/07/06
[ "https://Stackoverflow.com/questions/72884629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15602105/" ]
add a [`style=""`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/style) attribute in the `<iframe>` with this css code `max-width: 100%;` [![enter image description here](https://i.stack.imgur.com/e5UBp.gif)](https://i.stack.imgur.com/e5UBp.gif) > > this means that the video iframe in mobile always takes less than the width of the device. > > > and also the height remain the same, so the content below can be visible. > > > ```html <iframe style="max-width: 100%;" width="560" height="315" id="youtube2" src="https://www.youtube.com/embed/JexOJOssGwk?rel=0&enablejsapi=1&origin=https%3A%2F%2Fwww.apetito.co.uk&widgetid=1" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> ``` > > **useful documentations:** > > - `max-width`: <https://developer.mozilla.org/en-US/docs/Web/CSS/max-width> > > - `style attribute`: <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/style> > > >
i guess this can help you. ``` @media screen and (max-width: 750px) { iframe { max-width: 100% !important; width: auto !important; height: auto !important; } } ``` and for more solution example visit : <https://www.h3xed.com/web-development/how-to-make-a-responsive-100-width-youtube-iframe-embed>
47,187,115
I need to only use every other number in a string of numbers. This is how the xml file content comes to us, but I only want to use The first group and then every other group. The second number in each group can be ignored. The most important number are the first like 1,3,5 and 29 Can you help? Each group equals “x”:”x”, ``` <CatcList>{“1":"15","2":"15","3":"25","4":"25","5":"35","6":"35","29":"10","30":"10"}</CatcList> ``` Right now my script looks like this, but I am not the one who wrote it. I only included the portion that would be needed. The StartPage would be the variable used. If you have knowledge of how to add 1 to the EndPage Integer, that would be very helpful as well. Thank you! ``` Util.StringList xs; line.parseLine(",", "", xs); for (Int i=0; i<xs.Size; i++) { Int qty = xs[i].right(xs[i].Length - xs[i].find(":")-1).toInt()-1; for (Int j=0; j<qty; j++) { Output_0.File.DocId = product; Output_0.File.ImagePath = Image; Output_0.File.ImagePath1 = Image; Output_0.File.StartPage = xs[i].left(xs[i].find(("-"))).toInt()-1; Output_0.File.EndPage = xs[i].mid(xs[i].find("-")+1, (xs[i].find(":") - xs[i].find("-")-1)).toInt()-0; Output_0.File.Quantity = qty.toString(); Output_0.File.commit(); ```
2017/11/08
[ "https://Stackoverflow.com/questions/47187115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8908858/" ]
You're probably looking for something like **[jdkapidiff](https://github.com/gunnarmorling/jdkapidiff)** which uses *[japicmp](https://github.com/siom79/japicmp)* to generate reports similar to one hosted here by the author - [jdk8-jdk9-api-diff.](https://gunnarmorling.github.io/jdkapidiff/jdk8-jdk9-api-diff.html) You can clone the project and execute `mvn clean install` to get the similar report on your local. > > Provide a file `~.m2/toolchains.xml` like this: > > > > ``` > <?xml version="1.0" encoding="UTF8"?> > <toolchains> > <toolchain> > <type>jdk</type> > <provides> > <version>1.8</version> > <vendor>oracle</vendor> > </provides> > <configuration> > <jdkHome>/path/to/jdk-1.8</jdkHome> > </configuration> > </toolchain> > <toolchain> > <type>jdk</type> > <provides> > <version>9</version> > <vendor>oracle</vendor> > </provides> > <configuration> > <jdkHome>/path/to/jdk-9</jdkHome> > </configuration> > </toolchain> > </toolchains> > > ``` > >
There are many changes to existing classes and members, in addition to new @since 9 classes and members. The final release of JSR 379 include an annex with the complete set of diffs. The draft is online here: <http://cr.openjdk.java.net/~iris/se/9/java-se-9-fr-spec-01/apidiffs/overview-summary.html>
16,653,016
Been scratching my head over this one. I have a URL format I need to redirect and only need one part of the querystring. Example URL: > > tiles?shape=&colour=&finish=&material=&price=&o=60&tile=50-double-roman-antique-red-03-granular > > > All I need from this is the value of the tile parameter (50-double-roman-antique-red-03-granular) so I can then redirect it to: > > tiles/detail/50-double-roman-antique-red-03-granular > > > Any suggestions for a rewrite rule? Thanks
2013/05/20
[ "https://Stackoverflow.com/questions/16653016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1105816/" ]
My problems: There is a scrollView with many buttons (items). Above it there are 2 function buttons (return, start). 1. When I scroll down item buttons overlie function buttons. When I swallow all touches above my scrollview I will lose my function buttons. So I have to find another solution. 2. When I start draging scroll view a item button is pressed. When I ended the button action will be execute. This is very annoying. But there is the solution. I have created new CCControlButton. It checks whether was clicked outside scrollview or was dragged. The button is used for items buttons. ``` bool ControlButtonForScrolling::checkIfTouchIsInsideScrollView(CCTouch *pTouch) { CCPoint touchLocation = pTouch->getLocation(); // Get the touch position touchLocation = _scrollView->getParent()->convertToNodeSpace(touchLocation); CCRect bBox=_scrollView->boundingBox(); bool result = bBox.containsPoint(touchLocation); return result; } bool ControlButtonForScrolling::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) { bool isInside = this->checkIfTouchIsInsideScrollView(pTouch); if (isInside) { return CCControlButton::ccTouchBegan(pTouch, pEvent); } else { return false; } } void ControlButtonForScrolling::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent) { CCControlButton::ccTouchMoved(pTouch, pEvent); _scrollWasDragged = true; // information about dragging is stored to prevent sending action } void ControlButtonForScrolling::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) { // this method is a copy of CCControlButton::ccTouchEnded except lines with _scrollWasDragged m_eState = CCControlStateNormal; m_isPushed = false; setHighlighted(false); if (!_scrollWasDragged) { if (isTouchInside(pTouch)) { sendActionsForControlEvents(CCControlEventTouchUpInside); } else { sendActionsForControlEvents(CCControlEventTouchUpOutside); } } _scrollWasDragged = false; } ```
Inspired by Tomasz's answer, I created an alternative solution, also inheriting from `CCControlButton`: ``` bool ScrollableButton::isTouchInside(CCTouch *touch) { return !dragging && CCControlButton::isTouchInside(touch); } bool ScrollableButton::ccTouchBegan(CCTouch *touch, CCEvent *event) { dragging = false; return CCControlButton::ccTouchBegan(touch, event); } void ScrollableButton::ccTouchMoved(CCTouch *touch, CCEvent *event) { if (!dragging && ccpDistance(touch->getLocation(), touch->getStartLocation()) > 25) { dragging = true; } CCControlButton::ccTouchMoved(touch, event); } void ScrollableButton::ccTouchEnded(CCTouch *touch, CCEvent *event) { CCControlButton::ccTouchEnded(touch, event); dragging = false; } void ScrollableButton::ccTouchCancelled(CCTouch *touch, CCEvent *event) { CCControlButton::ccTouchCancelled(touch, event); dragging = false; } ``` The secret sauce is the override of the `isTouchInside` function, which will return `false` even if the touch is inside, but was moved. This way, the button will also release its "zoomed" state as soon as you start scrolling. It also adds a small tolerance factor, so if the touch moves just a little, it's still considered a "click". This factor is hardcoded at 25 in the example above.
5,690,512
What's the difference between `|` and `||` in Javascript? Furthermore, what's the difference between `&` and `&&`?
2011/04/17
[ "https://Stackoverflow.com/questions/5690512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/710598/" ]
Another difference is that `||` uses shortcut evaluation. That is, it only evaluates the right side if the left side is `false` (or gets converted to false in a boolean context, e.g. `0`, `""`, `null`, etc.). Similarly, `&&` only evaluates the right side if the left side is `true` (or non-zero, non-empty string, an object, etc.). `|` and `&` always evaluate both sides because the result depends on the exact bits in each value. The reasoning is that for `||`, if either side is true, the whole expression is true, so there's no need to evaluate any further. `&&` is the same but reversed. The exact logic for `||` is that if the left hand side is "truthy", return that value (note that it is **not converted to a boolean**), otherwise, evaluate and return the right hand side. For `&&`, if the left hand side is "falsey", return it, otherwise evaluate and return the right hand side. Here are some examples: ``` false && console.log("Nothing happens here"); true || console.log("Or here"); false || console.log("This DOES get logged"); "foo" && console.log("So does this"); if (obj && obj.property) // make sure obj is not null before accessing a property ```
In Javascript perspective, there is more to it. ``` var a = 42; var b = "abc"; var c = null; a || b; // 42 a && b; // "abc" c || b; // "abc" c && b; // null ``` Both || and && operators perform a boolean test on the first operand (a or c). If the operand is not already boolean (as it's not, here), a normal ToBoolean coercion occurs, so that the test can be performed. For the || operator, if the test is true, the || expression results in the value of the first operand (a or c). If the test is false, the || expression results in the value of the second operand (b). Inversely, for the && operator, if the test is true, the && expression results in the value of the second operand (b). If the test is false, the && expression results in the value of the first operand (a or c). The result of a || or && expression is always the underlying value of one of the operands, not the (possibly coerced) result of the test. In c && b, c is null, and thus falsy. But the && expression itself results in null (the value in c), not in the coerced false used in the test.
5,690,512
What's the difference between `|` and `||` in Javascript? Furthermore, what's the difference between `&` and `&&`?
2011/04/17
[ "https://Stackoverflow.com/questions/5690512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/710598/" ]
In Javascript perspective, there is more to it. ``` var a = 42; var b = "abc"; var c = null; a || b; // 42 a && b; // "abc" c || b; // "abc" c && b; // null ``` Both || and && operators perform a boolean test on the first operand (a or c). If the operand is not already boolean (as it's not, here), a normal ToBoolean coercion occurs, so that the test can be performed. For the || operator, if the test is true, the || expression results in the value of the first operand (a or c). If the test is false, the || expression results in the value of the second operand (b). Inversely, for the && operator, if the test is true, the && expression results in the value of the second operand (b). If the test is false, the && expression results in the value of the first operand (a or c). The result of a || or && expression is always the underlying value of one of the operands, not the (possibly coerced) result of the test. In c && b, c is null, and thus falsy. But the && expression itself results in null (the value in c), not in the coerced false used in the test.
one more point i want to add is || operator is used to assign default value in case the value you are assigning is undefined. So for Exapmle you are assigning a obj to some object test and if you dont want test to be undefined then you can do the following to ensure that value of test wont be undefined. var test = obj || {}; so in case obj is undefined then test's value will be empty object. So it is also being used for assigning default value to your object.
5,690,512
What's the difference between `|` and `||` in Javascript? Furthermore, what's the difference between `&` and `&&`?
2011/04/17
[ "https://Stackoverflow.com/questions/5690512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/710598/" ]
`|` is a bitwise or, `||` is a logical or. A bitwise or takes the two numbers and compares them on a bit-by-bit basis, producing a new integer which combines the 1 bits from both inputs. So `0101 | 1010` would produce `1111`. A logical or `||` checks for the "truthiness" of a value (depends on the type, for integers 0 is false and non-zero is true). It evaluates the statement left to right, and returns the first value which is truthy. So `0101 || 1010` would return `0101` which is truthy, therefore the whole statement is said to be true. The same type of logic applies for `&` vs `&&`. `0101 & 1010` = `0000`. However `0101 && 1010` evaluates to `1010` (`&&` returns the last truthy value so long as both operands are truthy).
To explain a little more in layman's terms: `&&` and `||` are *logical* operators. This means they're used for logical comparison; ``` if (a == 4 && b == 5) ``` This means "If a equals to four AND b equals to five" `|` and `&` are *bitwise* operators. They operate on bits in a specific fashion which the wiki article explains in detail: <http://en.wikipedia.org/wiki/Bitwise_operation>
5,690,512
What's the difference between `|` and `||` in Javascript? Furthermore, what's the difference between `&` and `&&`?
2011/04/17
[ "https://Stackoverflow.com/questions/5690512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/710598/" ]
* `&` is [the bitwise AND operator](http://rx4ajax-jscore.com/resource/glossary/glossb.html#bitwise_and_operator) * `|` is [the bitwise OR operator](http://rx4ajax-jscore.com/resource/glossary/glossb.html#bitwise_or_operator) * `&&` is [the logical AND operator](http://www.devguru.com/technologies/ecmascript/quickref/logical_operators.html) * `||` is [the logical OR operator](http://www.devguru.com/technologies/ecmascript/quickref/logical_operators.html) The difference is that logical operators only consider each input at face value, treating them as whole, while [bitwise operators work at the bit level](http://en.wikipedia.org/wiki/Bitwise_operation): ``` var thetruth = false; var therest = true; var theuniverse = thetruth && therest; //false var theparallel = thetruth && thetruth; //true var theindifferent = thetruth || therest; //true var theideal = thetruth || thetruth; // false var thematrix = 5346908590; var mrsmith = 2354656767; var theoracle = thematrix & mrsmith; //202445230 var theone = thematrix | mrsmith; //7499120127 ```
Single | is bit wise OR operator . If you do 2 | 3 , it converts to binary and performs OR operation. 01 11 Results in 11 equal to 3. Where as || operator checks if first argument is true, if it is true it returns else it goes to other operator. 2 || 3 returns 2 since 2 is true.
5,690,512
What's the difference between `|` and `||` in Javascript? Furthermore, what's the difference between `&` and `&&`?
2011/04/17
[ "https://Stackoverflow.com/questions/5690512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/710598/" ]
* `&` is [the bitwise AND operator](http://rx4ajax-jscore.com/resource/glossary/glossb.html#bitwise_and_operator) * `|` is [the bitwise OR operator](http://rx4ajax-jscore.com/resource/glossary/glossb.html#bitwise_or_operator) * `&&` is [the logical AND operator](http://www.devguru.com/technologies/ecmascript/quickref/logical_operators.html) * `||` is [the logical OR operator](http://www.devguru.com/technologies/ecmascript/quickref/logical_operators.html) The difference is that logical operators only consider each input at face value, treating them as whole, while [bitwise operators work at the bit level](http://en.wikipedia.org/wiki/Bitwise_operation): ``` var thetruth = false; var therest = true; var theuniverse = thetruth && therest; //false var theparallel = thetruth && thetruth; //true var theindifferent = thetruth || therest; //true var theideal = thetruth || thetruth; // false var thematrix = 5346908590; var mrsmith = 2354656767; var theoracle = thematrix & mrsmith; //202445230 var theone = thematrix | mrsmith; //7499120127 ```
Another difference is that `||` uses shortcut evaluation. That is, it only evaluates the right side if the left side is `false` (or gets converted to false in a boolean context, e.g. `0`, `""`, `null`, etc.). Similarly, `&&` only evaluates the right side if the left side is `true` (or non-zero, non-empty string, an object, etc.). `|` and `&` always evaluate both sides because the result depends on the exact bits in each value. The reasoning is that for `||`, if either side is true, the whole expression is true, so there's no need to evaluate any further. `&&` is the same but reversed. The exact logic for `||` is that if the left hand side is "truthy", return that value (note that it is **not converted to a boolean**), otherwise, evaluate and return the right hand side. For `&&`, if the left hand side is "falsey", return it, otherwise evaluate and return the right hand side. Here are some examples: ``` false && console.log("Nothing happens here"); true || console.log("Or here"); false || console.log("This DOES get logged"); "foo" && console.log("So does this"); if (obj && obj.property) // make sure obj is not null before accessing a property ```
5,690,512
What's the difference between `|` and `||` in Javascript? Furthermore, what's the difference between `&` and `&&`?
2011/04/17
[ "https://Stackoverflow.com/questions/5690512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/710598/" ]
* `&` is [the bitwise AND operator](http://rx4ajax-jscore.com/resource/glossary/glossb.html#bitwise_and_operator) * `|` is [the bitwise OR operator](http://rx4ajax-jscore.com/resource/glossary/glossb.html#bitwise_or_operator) * `&&` is [the logical AND operator](http://www.devguru.com/technologies/ecmascript/quickref/logical_operators.html) * `||` is [the logical OR operator](http://www.devguru.com/technologies/ecmascript/quickref/logical_operators.html) The difference is that logical operators only consider each input at face value, treating them as whole, while [bitwise operators work at the bit level](http://en.wikipedia.org/wiki/Bitwise_operation): ``` var thetruth = false; var therest = true; var theuniverse = thetruth && therest; //false var theparallel = thetruth && thetruth; //true var theindifferent = thetruth || therest; //true var theideal = thetruth || thetruth; // false var thematrix = 5346908590; var mrsmith = 2354656767; var theoracle = thematrix & mrsmith; //202445230 var theone = thematrix | mrsmith; //7499120127 ```
one more point i want to add is || operator is used to assign default value in case the value you are assigning is undefined. So for Exapmle you are assigning a obj to some object test and if you dont want test to be undefined then you can do the following to ensure that value of test wont be undefined. var test = obj || {}; so in case obj is undefined then test's value will be empty object. So it is also being used for assigning default value to your object.
5,690,512
What's the difference between `|` and `||` in Javascript? Furthermore, what's the difference between `&` and `&&`?
2011/04/17
[ "https://Stackoverflow.com/questions/5690512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/710598/" ]
Another difference is that `||` uses shortcut evaluation. That is, it only evaluates the right side if the left side is `false` (or gets converted to false in a boolean context, e.g. `0`, `""`, `null`, etc.). Similarly, `&&` only evaluates the right side if the left side is `true` (or non-zero, non-empty string, an object, etc.). `|` and `&` always evaluate both sides because the result depends on the exact bits in each value. The reasoning is that for `||`, if either side is true, the whole expression is true, so there's no need to evaluate any further. `&&` is the same but reversed. The exact logic for `||` is that if the left hand side is "truthy", return that value (note that it is **not converted to a boolean**), otherwise, evaluate and return the right hand side. For `&&`, if the left hand side is "falsey", return it, otherwise evaluate and return the right hand side. Here are some examples: ``` false && console.log("Nothing happens here"); true || console.log("Or here"); false || console.log("This DOES get logged"); "foo" && console.log("So does this"); if (obj && obj.property) // make sure obj is not null before accessing a property ```
Single | is bit wise OR operator . If you do 2 | 3 , it converts to binary and performs OR operation. 01 11 Results in 11 equal to 3. Where as || operator checks if first argument is true, if it is true it returns else it goes to other operator. 2 || 3 returns 2 since 2 is true.
5,690,512
What's the difference between `|` and `||` in Javascript? Furthermore, what's the difference between `&` and `&&`?
2011/04/17
[ "https://Stackoverflow.com/questions/5690512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/710598/" ]
`|` is a bitwise or, `||` is a logical or. A bitwise or takes the two numbers and compares them on a bit-by-bit basis, producing a new integer which combines the 1 bits from both inputs. So `0101 | 1010` would produce `1111`. A logical or `||` checks for the "truthiness" of a value (depends on the type, for integers 0 is false and non-zero is true). It evaluates the statement left to right, and returns the first value which is truthy. So `0101 || 1010` would return `0101` which is truthy, therefore the whole statement is said to be true. The same type of logic applies for `&` vs `&&`. `0101 & 1010` = `0000`. However `0101 && 1010` evaluates to `1010` (`&&` returns the last truthy value so long as both operands are truthy).
* `&` is [the bitwise AND operator](http://rx4ajax-jscore.com/resource/glossary/glossb.html#bitwise_and_operator) * `|` is [the bitwise OR operator](http://rx4ajax-jscore.com/resource/glossary/glossb.html#bitwise_or_operator) * `&&` is [the logical AND operator](http://www.devguru.com/technologies/ecmascript/quickref/logical_operators.html) * `||` is [the logical OR operator](http://www.devguru.com/technologies/ecmascript/quickref/logical_operators.html) The difference is that logical operators only consider each input at face value, treating them as whole, while [bitwise operators work at the bit level](http://en.wikipedia.org/wiki/Bitwise_operation): ``` var thetruth = false; var therest = true; var theuniverse = thetruth && therest; //false var theparallel = thetruth && thetruth; //true var theindifferent = thetruth || therest; //true var theideal = thetruth || thetruth; // false var thematrix = 5346908590; var mrsmith = 2354656767; var theoracle = thematrix & mrsmith; //202445230 var theone = thematrix | mrsmith; //7499120127 ```
5,690,512
What's the difference between `|` and `||` in Javascript? Furthermore, what's the difference between `&` and `&&`?
2011/04/17
[ "https://Stackoverflow.com/questions/5690512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/710598/" ]
To explain a little more in layman's terms: `&&` and `||` are *logical* operators. This means they're used for logical comparison; ``` if (a == 4 && b == 5) ``` This means "If a equals to four AND b equals to five" `|` and `&` are *bitwise* operators. They operate on bits in a specific fashion which the wiki article explains in detail: <http://en.wikipedia.org/wiki/Bitwise_operation>
one more point i want to add is || operator is used to assign default value in case the value you are assigning is undefined. So for Exapmle you are assigning a obj to some object test and if you dont want test to be undefined then you can do the following to ensure that value of test wont be undefined. var test = obj || {}; so in case obj is undefined then test's value will be empty object. So it is also being used for assigning default value to your object.
5,690,512
What's the difference between `|` and `||` in Javascript? Furthermore, what's the difference between `&` and `&&`?
2011/04/17
[ "https://Stackoverflow.com/questions/5690512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/710598/" ]
* `&` is [the bitwise AND operator](http://rx4ajax-jscore.com/resource/glossary/glossb.html#bitwise_and_operator) * `|` is [the bitwise OR operator](http://rx4ajax-jscore.com/resource/glossary/glossb.html#bitwise_or_operator) * `&&` is [the logical AND operator](http://www.devguru.com/technologies/ecmascript/quickref/logical_operators.html) * `||` is [the logical OR operator](http://www.devguru.com/technologies/ecmascript/quickref/logical_operators.html) The difference is that logical operators only consider each input at face value, treating them as whole, while [bitwise operators work at the bit level](http://en.wikipedia.org/wiki/Bitwise_operation): ``` var thetruth = false; var therest = true; var theuniverse = thetruth && therest; //false var theparallel = thetruth && thetruth; //true var theindifferent = thetruth || therest; //true var theideal = thetruth || thetruth; // false var thematrix = 5346908590; var mrsmith = 2354656767; var theoracle = thematrix & mrsmith; //202445230 var theone = thematrix | mrsmith; //7499120127 ```
In Javascript perspective, there is more to it. ``` var a = 42; var b = "abc"; var c = null; a || b; // 42 a && b; // "abc" c || b; // "abc" c && b; // null ``` Both || and && operators perform a boolean test on the first operand (a or c). If the operand is not already boolean (as it's not, here), a normal ToBoolean coercion occurs, so that the test can be performed. For the || operator, if the test is true, the || expression results in the value of the first operand (a or c). If the test is false, the || expression results in the value of the second operand (b). Inversely, for the && operator, if the test is true, the && expression results in the value of the second operand (b). If the test is false, the && expression results in the value of the first operand (a or c). The result of a || or && expression is always the underlying value of one of the operands, not the (possibly coerced) result of the test. In c && b, c is null, and thus falsy. But the && expression itself results in null (the value in c), not in the coerced false used in the test.
6,922,365
I have a web part that for new and edit functionality for custom list. I need a cancel button on it same as ``` <SharePoint:SaveButton /> ``` tag outputs the default save button in sharepoint.
2011/08/03
[ "https://Stackoverflow.com/questions/6922365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/314230/" ]
You can do: ``` <HTML dir="RTL"> ``` To make things attach to the right. For top to bottom you'd have to do that yourself, or in a script. Just for fun I'll see if I can write something using jQuery. I'll post it here. Try this: ``` function rev(el) { $('>*', el).each(function () { rev(this); $(this).prependTo(el); }) } rev($('body')); ``` That was kinda fun :) Do this as well, for more fun: ``` $('body *') .contents() .each(function() { if(this.nodeType == 3) { this.textContent = this.textContent. replace(/a/g, 'ɐ'). replace(/b/g, 'q'). replace(/c/g, 'ɔ'). replace(/d/g, 'p'). replace(/e/g, 'ǝ'). replace(/f/g, 'ɟ'). replace(/g/g, 'ƃ'). replace(/h/g, 'ɥ'). replace(/i/g, 'ı'). replace(/j/g, 'ɾ'). replace(/k/g, 'ʞ'). replace(/l/g, 'ʃ'). replace(/m/g, 'ɯ'). replace(/n/g, 'u'). replace(/o/g, 'o'). replace(/p/g, 'd'). replace(/q/g, 'b'). replace(/r/g, 'ɹ'). replace(/s/g, 's'). replace(/t/g, 'ʇ'). replace(/u/g, 'n'). replace(/v/g, 'ʌ'). replace(/w/g, 'ʍ'). replace(/x/g, 'x'). replace(/y/g, 'ʎ'). replace(/z/g, 'z'). replace(/A/g, '∀'). replace(/B/g, ''). replace(/C/g, 'Ↄ'). replace(/D/g, '◖'). replace(/E/g, 'Ǝ'). replace(/F/g, 'Ⅎ'). replace(/G/g, '⅁'). replace(/H/g, 'H'). replace(/I/g, 'I'). replace(/J/g, 'ſ'). replace(/K/g, '⋊'). replace(/L/g, '⅂'). replace(/M/g, 'W'). replace(/N/g, 'ᴎ'). replace(/O/g, 'O'). replace(/P/g, 'Ԁ'). replace(/Q/g, 'Ό'). replace(/R/g, 'ᴚ'). replace(/S/g, 'S'). replace(/T/g, '⊥'). replace(/U/g, '∩'). replace(/V/g, 'ᴧ'). replace(/W/g, 'M'). replace(/X/g, 'X'). replace(/Y/g, '⅄'). replace(/Z/g, 'Z'). replace(/!/g, '¡'). replace(/"/g, '„'). replace(/&/g, '⅋'). replace(/'/g, ','). replace(/,/g, '\''). replace(/\(/g, ')'). replace(/\)/g, '('). replace(/\./g, '˙'). replace(/1/g, 'Ɩ'). replace(/2/g, 'ᄅ'). replace(/3/g, 'Ɛ'). replace(/4/g, 'ᔭ'). replace(/5/g, 'ϛ'). replace(/6/g, '9'). replace(/7/g, 'Ɫ'). replace(/8/g, '8'). replace(/9/g, '6'). replace(/0/g, '0'). replace(/;/g, '؛'). replace(/</g, '>'). replace(/>/g, '<'). replace(/{/g, '}'). replace(/}/g, '{') } }); ```
Oh, that's rather easy if you are using a laptop or a tablet. If you have a desktop, however, it can be harder to get the display to stay upright. Sometimes duct tape and some creative woodwork can help. If your monitor is attached, however, then no. HTML always renders from the top down.
35,224,575
I have ansible (v2.0.0.2) and python (v2.7.6) and i'm running the 'maven\_artifact' module. As a direct ansible command, it works fine ``` ansible localhost -m maven_artifact -a "group_id=commons-collections artifact_id=commons-collections dest=/tmp/commons-collections-latest.jar" -vvvv ``` but when i do the same via a playbook ``` - name: download via maven maven_artifact: group_id=junit artifact_id=junit dest=/tmp/junit-latest.jar ``` it fails with this error ``` fatal: [test01vm1]: FAILED! => {"changed": false, "failed": true, "invocation": {"module_name": "maven_artifact"}, "module_stderr": "", "module_stdout": "\r\nTraceback (most recent call last):\r\n File \"/home/admin123/.ansible/tmp/ansible-tmp-1454675562.75-201853614879442/maven_artifact\", line 25, in <module>\r\n from lxml import etree\r\nImportError: No module named lxml\r\n", "msg": "MODULE FAILURE", "parsed": false} ``` I believe might be related to the python lxml module, and i found these existing tickets ``` http://stackoverflow.com/questions/13355984/get-errors-when-import-lxml-etree-to-python http://stackoverflow.com/questions/4598229/installing-lxml-module-in-python ``` I'm wondering might someone have a workaround for this? --- EDIT - Add python path details I ran this command to see what path's are on the python home ``` 14:55:11@pcZBook-15:/usr/local/etc$ python -c 'import sys; print(":".join(sys.path))' ``` The list of folders is ``` :/opt/stack/keystone :/opt/stack/glance :/opt/stack/cinder :/opt/stack/nova :/opt/stack/horizon :/usr/lib/python2.7 :/usr/lib/python2.7/plat-x86_64-linux-gnu :/usr/lib/python2.7/lib-tk :/usr/lib/python2.7/lib-old :/usr/lib/python2.7/lib-dynload :/usr/local/lib/python2.7/dist-packages :/usr/lib/python2.7/dist-packages :/usr/lib/python2.7/dist-packages/PILcompat :/usr/lib/python2.7/dist-packages/gtk-2.0 :/usr/lib/pymodules/python2.7 :/usr/lib/python2.7/dist-packages/ubuntu-sso-client :/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode ```
2016/02/05
[ "https://Stackoverflow.com/questions/35224575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55794/" ]
It seems that ansible was trying to execute the 'maven\_artifact' command on the remote target host, which didn't have the required python libraries. In my case I only wanted to run the command on the local 'ansible\_host' so I just added the 'local\_action' prefix and the command runs. ``` - name: download via maven local_action: maven_artifact group_id=junit artifact_id=junit dest=/tmp/junit-latest.jar ```
Just do > > sudo apt-get install python-lxml > > >
35,224,575
I have ansible (v2.0.0.2) and python (v2.7.6) and i'm running the 'maven\_artifact' module. As a direct ansible command, it works fine ``` ansible localhost -m maven_artifact -a "group_id=commons-collections artifact_id=commons-collections dest=/tmp/commons-collections-latest.jar" -vvvv ``` but when i do the same via a playbook ``` - name: download via maven maven_artifact: group_id=junit artifact_id=junit dest=/tmp/junit-latest.jar ``` it fails with this error ``` fatal: [test01vm1]: FAILED! => {"changed": false, "failed": true, "invocation": {"module_name": "maven_artifact"}, "module_stderr": "", "module_stdout": "\r\nTraceback (most recent call last):\r\n File \"/home/admin123/.ansible/tmp/ansible-tmp-1454675562.75-201853614879442/maven_artifact\", line 25, in <module>\r\n from lxml import etree\r\nImportError: No module named lxml\r\n", "msg": "MODULE FAILURE", "parsed": false} ``` I believe might be related to the python lxml module, and i found these existing tickets ``` http://stackoverflow.com/questions/13355984/get-errors-when-import-lxml-etree-to-python http://stackoverflow.com/questions/4598229/installing-lxml-module-in-python ``` I'm wondering might someone have a workaround for this? --- EDIT - Add python path details I ran this command to see what path's are on the python home ``` 14:55:11@pcZBook-15:/usr/local/etc$ python -c 'import sys; print(":".join(sys.path))' ``` The list of folders is ``` :/opt/stack/keystone :/opt/stack/glance :/opt/stack/cinder :/opt/stack/nova :/opt/stack/horizon :/usr/lib/python2.7 :/usr/lib/python2.7/plat-x86_64-linux-gnu :/usr/lib/python2.7/lib-tk :/usr/lib/python2.7/lib-old :/usr/lib/python2.7/lib-dynload :/usr/local/lib/python2.7/dist-packages :/usr/lib/python2.7/dist-packages :/usr/lib/python2.7/dist-packages/PILcompat :/usr/lib/python2.7/dist-packages/gtk-2.0 :/usr/lib/pymodules/python2.7 :/usr/lib/python2.7/dist-packages/ubuntu-sso-client :/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode ```
2016/02/05
[ "https://Stackoverflow.com/questions/35224575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55794/" ]
It seems that ansible was trying to execute the 'maven\_artifact' command on the remote target host, which didn't have the required python libraries. In my case I only wanted to run the command on the local 'ansible\_host' so I just added the 'local\_action' prefix and the command runs. ``` - name: download via maven local_action: maven_artifact group_id=junit artifact_id=junit dest=/tmp/junit-latest.jar ```
You need to install lxml in [test01vm1]. ``` pip install lxml ```
35,224,575
I have ansible (v2.0.0.2) and python (v2.7.6) and i'm running the 'maven\_artifact' module. As a direct ansible command, it works fine ``` ansible localhost -m maven_artifact -a "group_id=commons-collections artifact_id=commons-collections dest=/tmp/commons-collections-latest.jar" -vvvv ``` but when i do the same via a playbook ``` - name: download via maven maven_artifact: group_id=junit artifact_id=junit dest=/tmp/junit-latest.jar ``` it fails with this error ``` fatal: [test01vm1]: FAILED! => {"changed": false, "failed": true, "invocation": {"module_name": "maven_artifact"}, "module_stderr": "", "module_stdout": "\r\nTraceback (most recent call last):\r\n File \"/home/admin123/.ansible/tmp/ansible-tmp-1454675562.75-201853614879442/maven_artifact\", line 25, in <module>\r\n from lxml import etree\r\nImportError: No module named lxml\r\n", "msg": "MODULE FAILURE", "parsed": false} ``` I believe might be related to the python lxml module, and i found these existing tickets ``` http://stackoverflow.com/questions/13355984/get-errors-when-import-lxml-etree-to-python http://stackoverflow.com/questions/4598229/installing-lxml-module-in-python ``` I'm wondering might someone have a workaround for this? --- EDIT - Add python path details I ran this command to see what path's are on the python home ``` 14:55:11@pcZBook-15:/usr/local/etc$ python -c 'import sys; print(":".join(sys.path))' ``` The list of folders is ``` :/opt/stack/keystone :/opt/stack/glance :/opt/stack/cinder :/opt/stack/nova :/opt/stack/horizon :/usr/lib/python2.7 :/usr/lib/python2.7/plat-x86_64-linux-gnu :/usr/lib/python2.7/lib-tk :/usr/lib/python2.7/lib-old :/usr/lib/python2.7/lib-dynload :/usr/local/lib/python2.7/dist-packages :/usr/lib/python2.7/dist-packages :/usr/lib/python2.7/dist-packages/PILcompat :/usr/lib/python2.7/dist-packages/gtk-2.0 :/usr/lib/pymodules/python2.7 :/usr/lib/python2.7/dist-packages/ubuntu-sso-client :/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode ```
2016/02/05
[ "https://Stackoverflow.com/questions/35224575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55794/" ]
It seems that ansible was trying to execute the 'maven\_artifact' command on the remote target host, which didn't have the required python libraries. In my case I only wanted to run the command on the local 'ansible\_host' so I just added the 'local\_action' prefix and the command runs. ``` - name: download via maven local_action: maven_artifact group_id=junit artifact_id=junit dest=/tmp/junit-latest.jar ```
Verify that target machine has python lxml module, and ansible selects the python interpreter where you have installed the lxml module. ``` [ec2-user@i-05f345345aas6b bin]$ pip list | grep xml lxml 3.2.1 ``` And then double check that ansible picks that python version by adding: ``` ansible_python_interpreter=/usr/bin/python2 ``` See <https://docs.ansible.com/ansible/latest/reference_appendices/interpreter_discovery.html> I have observed that ansible 2.12 ansible picks python3 interpreter by default, if no python interpreter is defined in target machine. So double check with ``` pip3 list | grep lxml ``` that lxml module is also available for python3
35,224,575
I have ansible (v2.0.0.2) and python (v2.7.6) and i'm running the 'maven\_artifact' module. As a direct ansible command, it works fine ``` ansible localhost -m maven_artifact -a "group_id=commons-collections artifact_id=commons-collections dest=/tmp/commons-collections-latest.jar" -vvvv ``` but when i do the same via a playbook ``` - name: download via maven maven_artifact: group_id=junit artifact_id=junit dest=/tmp/junit-latest.jar ``` it fails with this error ``` fatal: [test01vm1]: FAILED! => {"changed": false, "failed": true, "invocation": {"module_name": "maven_artifact"}, "module_stderr": "", "module_stdout": "\r\nTraceback (most recent call last):\r\n File \"/home/admin123/.ansible/tmp/ansible-tmp-1454675562.75-201853614879442/maven_artifact\", line 25, in <module>\r\n from lxml import etree\r\nImportError: No module named lxml\r\n", "msg": "MODULE FAILURE", "parsed": false} ``` I believe might be related to the python lxml module, and i found these existing tickets ``` http://stackoverflow.com/questions/13355984/get-errors-when-import-lxml-etree-to-python http://stackoverflow.com/questions/4598229/installing-lxml-module-in-python ``` I'm wondering might someone have a workaround for this? --- EDIT - Add python path details I ran this command to see what path's are on the python home ``` 14:55:11@pcZBook-15:/usr/local/etc$ python -c 'import sys; print(":".join(sys.path))' ``` The list of folders is ``` :/opt/stack/keystone :/opt/stack/glance :/opt/stack/cinder :/opt/stack/nova :/opt/stack/horizon :/usr/lib/python2.7 :/usr/lib/python2.7/plat-x86_64-linux-gnu :/usr/lib/python2.7/lib-tk :/usr/lib/python2.7/lib-old :/usr/lib/python2.7/lib-dynload :/usr/local/lib/python2.7/dist-packages :/usr/lib/python2.7/dist-packages :/usr/lib/python2.7/dist-packages/PILcompat :/usr/lib/python2.7/dist-packages/gtk-2.0 :/usr/lib/pymodules/python2.7 :/usr/lib/python2.7/dist-packages/ubuntu-sso-client :/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode ```
2016/02/05
[ "https://Stackoverflow.com/questions/35224575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55794/" ]
What I usually do is to call: ``` - name: Install PIP apt: name=python-pip state=present - name: Install lxml pip: name=lxml ```
Just do > > sudo apt-get install python-lxml > > >
35,224,575
I have ansible (v2.0.0.2) and python (v2.7.6) and i'm running the 'maven\_artifact' module. As a direct ansible command, it works fine ``` ansible localhost -m maven_artifact -a "group_id=commons-collections artifact_id=commons-collections dest=/tmp/commons-collections-latest.jar" -vvvv ``` but when i do the same via a playbook ``` - name: download via maven maven_artifact: group_id=junit artifact_id=junit dest=/tmp/junit-latest.jar ``` it fails with this error ``` fatal: [test01vm1]: FAILED! => {"changed": false, "failed": true, "invocation": {"module_name": "maven_artifact"}, "module_stderr": "", "module_stdout": "\r\nTraceback (most recent call last):\r\n File \"/home/admin123/.ansible/tmp/ansible-tmp-1454675562.75-201853614879442/maven_artifact\", line 25, in <module>\r\n from lxml import etree\r\nImportError: No module named lxml\r\n", "msg": "MODULE FAILURE", "parsed": false} ``` I believe might be related to the python lxml module, and i found these existing tickets ``` http://stackoverflow.com/questions/13355984/get-errors-when-import-lxml-etree-to-python http://stackoverflow.com/questions/4598229/installing-lxml-module-in-python ``` I'm wondering might someone have a workaround for this? --- EDIT - Add python path details I ran this command to see what path's are on the python home ``` 14:55:11@pcZBook-15:/usr/local/etc$ python -c 'import sys; print(":".join(sys.path))' ``` The list of folders is ``` :/opt/stack/keystone :/opt/stack/glance :/opt/stack/cinder :/opt/stack/nova :/opt/stack/horizon :/usr/lib/python2.7 :/usr/lib/python2.7/plat-x86_64-linux-gnu :/usr/lib/python2.7/lib-tk :/usr/lib/python2.7/lib-old :/usr/lib/python2.7/lib-dynload :/usr/local/lib/python2.7/dist-packages :/usr/lib/python2.7/dist-packages :/usr/lib/python2.7/dist-packages/PILcompat :/usr/lib/python2.7/dist-packages/gtk-2.0 :/usr/lib/pymodules/python2.7 :/usr/lib/python2.7/dist-packages/ubuntu-sso-client :/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode ```
2016/02/05
[ "https://Stackoverflow.com/questions/35224575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55794/" ]
What I usually do is to call: ``` - name: Install PIP apt: name=python-pip state=present - name: Install lxml pip: name=lxml ```
You need to install lxml in [test01vm1]. ``` pip install lxml ```
35,224,575
I have ansible (v2.0.0.2) and python (v2.7.6) and i'm running the 'maven\_artifact' module. As a direct ansible command, it works fine ``` ansible localhost -m maven_artifact -a "group_id=commons-collections artifact_id=commons-collections dest=/tmp/commons-collections-latest.jar" -vvvv ``` but when i do the same via a playbook ``` - name: download via maven maven_artifact: group_id=junit artifact_id=junit dest=/tmp/junit-latest.jar ``` it fails with this error ``` fatal: [test01vm1]: FAILED! => {"changed": false, "failed": true, "invocation": {"module_name": "maven_artifact"}, "module_stderr": "", "module_stdout": "\r\nTraceback (most recent call last):\r\n File \"/home/admin123/.ansible/tmp/ansible-tmp-1454675562.75-201853614879442/maven_artifact\", line 25, in <module>\r\n from lxml import etree\r\nImportError: No module named lxml\r\n", "msg": "MODULE FAILURE", "parsed": false} ``` I believe might be related to the python lxml module, and i found these existing tickets ``` http://stackoverflow.com/questions/13355984/get-errors-when-import-lxml-etree-to-python http://stackoverflow.com/questions/4598229/installing-lxml-module-in-python ``` I'm wondering might someone have a workaround for this? --- EDIT - Add python path details I ran this command to see what path's are on the python home ``` 14:55:11@pcZBook-15:/usr/local/etc$ python -c 'import sys; print(":".join(sys.path))' ``` The list of folders is ``` :/opt/stack/keystone :/opt/stack/glance :/opt/stack/cinder :/opt/stack/nova :/opt/stack/horizon :/usr/lib/python2.7 :/usr/lib/python2.7/plat-x86_64-linux-gnu :/usr/lib/python2.7/lib-tk :/usr/lib/python2.7/lib-old :/usr/lib/python2.7/lib-dynload :/usr/local/lib/python2.7/dist-packages :/usr/lib/python2.7/dist-packages :/usr/lib/python2.7/dist-packages/PILcompat :/usr/lib/python2.7/dist-packages/gtk-2.0 :/usr/lib/pymodules/python2.7 :/usr/lib/python2.7/dist-packages/ubuntu-sso-client :/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode ```
2016/02/05
[ "https://Stackoverflow.com/questions/35224575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55794/" ]
What I usually do is to call: ``` - name: Install PIP apt: name=python-pip state=present - name: Install lxml pip: name=lxml ```
Verify that target machine has python lxml module, and ansible selects the python interpreter where you have installed the lxml module. ``` [ec2-user@i-05f345345aas6b bin]$ pip list | grep xml lxml 3.2.1 ``` And then double check that ansible picks that python version by adding: ``` ansible_python_interpreter=/usr/bin/python2 ``` See <https://docs.ansible.com/ansible/latest/reference_appendices/interpreter_discovery.html> I have observed that ansible 2.12 ansible picks python3 interpreter by default, if no python interpreter is defined in target machine. So double check with ``` pip3 list | grep lxml ``` that lxml module is also available for python3
35,224,575
I have ansible (v2.0.0.2) and python (v2.7.6) and i'm running the 'maven\_artifact' module. As a direct ansible command, it works fine ``` ansible localhost -m maven_artifact -a "group_id=commons-collections artifact_id=commons-collections dest=/tmp/commons-collections-latest.jar" -vvvv ``` but when i do the same via a playbook ``` - name: download via maven maven_artifact: group_id=junit artifact_id=junit dest=/tmp/junit-latest.jar ``` it fails with this error ``` fatal: [test01vm1]: FAILED! => {"changed": false, "failed": true, "invocation": {"module_name": "maven_artifact"}, "module_stderr": "", "module_stdout": "\r\nTraceback (most recent call last):\r\n File \"/home/admin123/.ansible/tmp/ansible-tmp-1454675562.75-201853614879442/maven_artifact\", line 25, in <module>\r\n from lxml import etree\r\nImportError: No module named lxml\r\n", "msg": "MODULE FAILURE", "parsed": false} ``` I believe might be related to the python lxml module, and i found these existing tickets ``` http://stackoverflow.com/questions/13355984/get-errors-when-import-lxml-etree-to-python http://stackoverflow.com/questions/4598229/installing-lxml-module-in-python ``` I'm wondering might someone have a workaround for this? --- EDIT - Add python path details I ran this command to see what path's are on the python home ``` 14:55:11@pcZBook-15:/usr/local/etc$ python -c 'import sys; print(":".join(sys.path))' ``` The list of folders is ``` :/opt/stack/keystone :/opt/stack/glance :/opt/stack/cinder :/opt/stack/nova :/opt/stack/horizon :/usr/lib/python2.7 :/usr/lib/python2.7/plat-x86_64-linux-gnu :/usr/lib/python2.7/lib-tk :/usr/lib/python2.7/lib-old :/usr/lib/python2.7/lib-dynload :/usr/local/lib/python2.7/dist-packages :/usr/lib/python2.7/dist-packages :/usr/lib/python2.7/dist-packages/PILcompat :/usr/lib/python2.7/dist-packages/gtk-2.0 :/usr/lib/pymodules/python2.7 :/usr/lib/python2.7/dist-packages/ubuntu-sso-client :/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode ```
2016/02/05
[ "https://Stackoverflow.com/questions/35224575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55794/" ]
Just do > > sudo apt-get install python-lxml > > >
You need to install lxml in [test01vm1]. ``` pip install lxml ```
35,224,575
I have ansible (v2.0.0.2) and python (v2.7.6) and i'm running the 'maven\_artifact' module. As a direct ansible command, it works fine ``` ansible localhost -m maven_artifact -a "group_id=commons-collections artifact_id=commons-collections dest=/tmp/commons-collections-latest.jar" -vvvv ``` but when i do the same via a playbook ``` - name: download via maven maven_artifact: group_id=junit artifact_id=junit dest=/tmp/junit-latest.jar ``` it fails with this error ``` fatal: [test01vm1]: FAILED! => {"changed": false, "failed": true, "invocation": {"module_name": "maven_artifact"}, "module_stderr": "", "module_stdout": "\r\nTraceback (most recent call last):\r\n File \"/home/admin123/.ansible/tmp/ansible-tmp-1454675562.75-201853614879442/maven_artifact\", line 25, in <module>\r\n from lxml import etree\r\nImportError: No module named lxml\r\n", "msg": "MODULE FAILURE", "parsed": false} ``` I believe might be related to the python lxml module, and i found these existing tickets ``` http://stackoverflow.com/questions/13355984/get-errors-when-import-lxml-etree-to-python http://stackoverflow.com/questions/4598229/installing-lxml-module-in-python ``` I'm wondering might someone have a workaround for this? --- EDIT - Add python path details I ran this command to see what path's are on the python home ``` 14:55:11@pcZBook-15:/usr/local/etc$ python -c 'import sys; print(":".join(sys.path))' ``` The list of folders is ``` :/opt/stack/keystone :/opt/stack/glance :/opt/stack/cinder :/opt/stack/nova :/opt/stack/horizon :/usr/lib/python2.7 :/usr/lib/python2.7/plat-x86_64-linux-gnu :/usr/lib/python2.7/lib-tk :/usr/lib/python2.7/lib-old :/usr/lib/python2.7/lib-dynload :/usr/local/lib/python2.7/dist-packages :/usr/lib/python2.7/dist-packages :/usr/lib/python2.7/dist-packages/PILcompat :/usr/lib/python2.7/dist-packages/gtk-2.0 :/usr/lib/pymodules/python2.7 :/usr/lib/python2.7/dist-packages/ubuntu-sso-client :/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode ```
2016/02/05
[ "https://Stackoverflow.com/questions/35224575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55794/" ]
Just do > > sudo apt-get install python-lxml > > >
Verify that target machine has python lxml module, and ansible selects the python interpreter where you have installed the lxml module. ``` [ec2-user@i-05f345345aas6b bin]$ pip list | grep xml lxml 3.2.1 ``` And then double check that ansible picks that python version by adding: ``` ansible_python_interpreter=/usr/bin/python2 ``` See <https://docs.ansible.com/ansible/latest/reference_appendices/interpreter_discovery.html> I have observed that ansible 2.12 ansible picks python3 interpreter by default, if no python interpreter is defined in target machine. So double check with ``` pip3 list | grep lxml ``` that lxml module is also available for python3
34,381,239
In my form i have about 36 buttons and for each i have the following code ``` button3.BackColor = Color.DarkGreen; button_click("A1"); button3.Enabled = false; nr_l++; textBox4.Text = Convert.ToString(nr_l); ``` which means I will have this code x 36 times, I want to make a method that does this but I dont know how to change last clicked buttons properties, i want something like this : ``` private void change_properties() { last_clicked_button.backcolor = color.darkgreen; button_click("A3"); //this is a method for adding A3 to a string, last_clicked_button.enabled = false; nr_l++; textbox4.text = convert.tostring(nr_l); } private void button3_Click(object sender, EventArgs e) { change_properties(); } ``` How can i tell change\_properties method that it should work with button3 in case it was clicked?
2015/12/20
[ "https://Stackoverflow.com/questions/34381239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5562950/" ]
You're correct, `a.f()` is not a constant expression. And variable length arrays are not allowed by the c++ standard. The GNU compiler, however, supports them as a [language extension](https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html). You can ask the compiler to give you a warning when you use non-standard extensions with the [`-pedantic` option](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html), or an error with `-pedantic-errors`. Edit: Apparently, GCC 4.9 [added](https://gcc.gnu.org/gcc-4.9/changes.html#cxx) the official support for [N3639](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3639.html), the proposal to add variable length arrays to the C++14 standard. In the end, the proposal was not included in the standard, but GCC 4.9 was released before C++14, so that change was not reflected. So, VLA's are supported by GCC 4.9 on purpose in C++14 mode and the above options don't disable them. Note that the C++14 mode is still experimental (even in GCC 5).
The following non-standard code ``` int x = std::rand(); int r[x] = { 1,2,3 }; ``` compiles under g++, not because `g++` mistakenly treats `std::rand()` as a constant expression, but because it implements VLAs by default. Use `-pedantic` or `-Wvla` to warn about them, `-Werror=vla` to turn these warnings into errors.
48,566,174
I've googled and googled and either google is failing me or you can't do this. This warning comes up when you turn on `-Wpedantic`... > > ISO C++ forbids zero-size array ‘variable’ [-Wpedantic] > > > I want to turn off this one warning, not all pedantic warnings. Normally, I'd just add `-Wno-xyz` but I can't find the flag name that relates to that warning. It's just not listed anywhere. Are the pedantic warnings special in that you can't remove them individually?
2018/02/01
[ "https://Stackoverflow.com/questions/48566174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12386/" ]
The good news: You *can* do this. The bad news: You can't use any commandline option. The `[-Wpedantic]` at the end of the diagnostic tells you that `-Wno-pedantic` is the narrowest option that will disable the diagnostic, and that's no use to you if you want to preserve all other pedantic diagnostics. You'll have to do it case-by-case with pragmas. **main.cpp** ``` int main(int argc, char *argv[]) { int a[0]; int b[argc]; return sizeof(a) + sizeof(b); } ``` This program provokes two `-Wpedantic` diaqnostics: ``` $ g++ -Wpedantic -c main.cpp main.cpp: In function ‘int main(int, char**)’: main.cpp:6:12: warning: ISO C++ forbids zero-size array ‘a’ [-Wpedantic] int a[0]; ^ main.cpp:8:15: warning: ISO C++ forbids variable length array ‘b’ [-Wvla] int b[argc]; ^ ``` `-Wno-vla` will suppress the second one. To suppress the first, you have to resort to: **main.cpp (revised)** ``` int main(int argc, char *argv[]) { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpedantic" int a[0]; #pragma GCC diagnostic pop int b[argc]; return sizeof(a) + sizeof(b); } ``` With which: ``` $ g++ -Wpedantic -c main.cpp main.cpp: In function ‘int main(int, char**)’: main.cpp:8:15: warning: ISO C++ forbids variable length array ‘b’ [-Wvla] int b[argc]; ^ ```
Well, you can use a pragma to disable it, but if you want to be portable, you can use a zero-size `std::array` instead: ``` #include <array> //... std::array<int, 0> ar; ``` Using `std::array` over plain arrays is recommended anyway.