qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
9,437,313
I have a function here that finds the sibling(answerfields) of the parent(li) then counts the child inputs. ``` $('#addAnswer').live('click', function(){ var selected = $(this).parents('li').siblings('#answerFields').children('input').length; document.getElementById('legend').innerHTML = selected; }); ``` How can i shorten this up using Jquery 1.5.2? I have a working [JSFiddle](http://jsfiddle.net/rayd360/bPp8a/).
2012/02/24
[ "https://Stackoverflow.com/questions/9437313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1082764/" ]
Other way could be using `perl`: ``` perl -i -pe ' BEGIN { $keysalts = qx(curl -sS https://api.wordpress.org/secret-key/1.1/salt) } s/{AUTH-KEYS-SALTS}/$keysalts/g ' wp-config.php ```
You can escape `$keysalts` using sed itself: ``` sed -i "s/{AUTH-KEYS-SALTS}/`echo $keysalts | sed -e 's/[\/&]/\\&/g'`/g" wp-config.php ``` See [this question](https://stackoverflow.com/questions/407523/escape-a-string-for-sed-search-pattern) for more information.
9,437,313
I have a function here that finds the sibling(answerfields) of the parent(li) then counts the child inputs. ``` $('#addAnswer').live('click', function(){ var selected = $(this).parents('li').siblings('#answerFields').children('input').length; document.getElementById('legend').innerHTML = selected; }); ``` How can i shorten this up using Jquery 1.5.2? I have a working [JSFiddle](http://jsfiddle.net/rayd360/bPp8a/).
2012/02/24
[ "https://Stackoverflow.com/questions/9437313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1082764/" ]
You can escape `$keysalts` using sed itself: ``` sed -i "s/{AUTH-KEYS-SALTS}/`echo $keysalts | sed -e 's/[\/&]/\\&/g'`/g" wp-config.php ``` See [this question](https://stackoverflow.com/questions/407523/escape-a-string-for-sed-search-pattern) for more information.
Actually, I like this [one better](https://stackoverflow.com/questions/584894/sed-scripting-environment-variable-substitution) ``` sed -i 's/{AUTH-KEYS-SALTS}/'"$keysalts"'/g' wp-config.php ``` Personal choice. :-)
9,437,313
I have a function here that finds the sibling(answerfields) of the parent(li) then counts the child inputs. ``` $('#addAnswer').live('click', function(){ var selected = $(this).parents('li').siblings('#answerFields').children('input').length; document.getElementById('legend').innerHTML = selected; }); ``` How can i shorten this up using Jquery 1.5.2? I have a working [JSFiddle](http://jsfiddle.net/rayd360/bPp8a/).
2012/02/24
[ "https://Stackoverflow.com/questions/9437313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1082764/" ]
You can escape `$keysalts` using sed itself: ``` sed -i "s/{AUTH-KEYS-SALTS}/`echo $keysalts | sed -e 's/[\/&]/\\&/g'`/g" wp-config.php ``` See [this question](https://stackoverflow.com/questions/407523/escape-a-string-for-sed-search-pattern) for more information.
It turns out you're asking the wrong question. I also asked the wrong question. The reason it's wrong is the beginning of the first sentence: "In my bash script...". I had the same question & made the same mistake. If you're using bash, you don't need to use sed to do string replacements (and it's much cleaner to use the replace feature built into bash). Instead of: ``` keysalts=`curl -sS https://api.wordpress.org/secret-key/1.1/salt/` sed -i "s/{AUTH-KEYS-SALTS}/$keysalts/g" wp-config.php ``` you can use bash features exclusively, reading the file into a variable, replacing the text in the variable, and writing the replaced text back out to the file: ``` INPUT=$(<wp-config.php) keysalts="$(curl -sS https://api.wordpress.org/secret-key/1.1/salt/)" echo "${INPUT//'{AUTH-KEYS-SALTS}'/"$keysalts"}" >wp-config.php ```
9,437,313
I have a function here that finds the sibling(answerfields) of the parent(li) then counts the child inputs. ``` $('#addAnswer').live('click', function(){ var selected = $(this).parents('li').siblings('#answerFields').children('input').length; document.getElementById('legend').innerHTML = selected; }); ``` How can i shorten this up using Jquery 1.5.2? I have a working [JSFiddle](http://jsfiddle.net/rayd360/bPp8a/).
2012/02/24
[ "https://Stackoverflow.com/questions/9437313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1082764/" ]
Other way could be using `perl`: ``` perl -i -pe ' BEGIN { $keysalts = qx(curl -sS https://api.wordpress.org/secret-key/1.1/salt) } s/{AUTH-KEYS-SALTS}/$keysalts/g ' wp-config.php ```
Actually, I like this [one better](https://stackoverflow.com/questions/584894/sed-scripting-environment-variable-substitution) ``` sed -i 's/{AUTH-KEYS-SALTS}/'"$keysalts"'/g' wp-config.php ``` Personal choice. :-)
9,437,313
I have a function here that finds the sibling(answerfields) of the parent(li) then counts the child inputs. ``` $('#addAnswer').live('click', function(){ var selected = $(this).parents('li').siblings('#answerFields').children('input').length; document.getElementById('legend').innerHTML = selected; }); ``` How can i shorten this up using Jquery 1.5.2? I have a working [JSFiddle](http://jsfiddle.net/rayd360/bPp8a/).
2012/02/24
[ "https://Stackoverflow.com/questions/9437313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1082764/" ]
Other way could be using `perl`: ``` perl -i -pe ' BEGIN { $keysalts = qx(curl -sS https://api.wordpress.org/secret-key/1.1/salt) } s/{AUTH-KEYS-SALTS}/$keysalts/g ' wp-config.php ```
It turns out you're asking the wrong question. I also asked the wrong question. The reason it's wrong is the beginning of the first sentence: "In my bash script...". I had the same question & made the same mistake. If you're using bash, you don't need to use sed to do string replacements (and it's much cleaner to use the replace feature built into bash). Instead of: ``` keysalts=`curl -sS https://api.wordpress.org/secret-key/1.1/salt/` sed -i "s/{AUTH-KEYS-SALTS}/$keysalts/g" wp-config.php ``` you can use bash features exclusively, reading the file into a variable, replacing the text in the variable, and writing the replaced text back out to the file: ``` INPUT=$(<wp-config.php) keysalts="$(curl -sS https://api.wordpress.org/secret-key/1.1/salt/)" echo "${INPUT//'{AUTH-KEYS-SALTS}'/"$keysalts"}" >wp-config.php ```
9,437,313
I have a function here that finds the sibling(answerfields) of the parent(li) then counts the child inputs. ``` $('#addAnswer').live('click', function(){ var selected = $(this).parents('li').siblings('#answerFields').children('input').length; document.getElementById('legend').innerHTML = selected; }); ``` How can i shorten this up using Jquery 1.5.2? I have a working [JSFiddle](http://jsfiddle.net/rayd360/bPp8a/).
2012/02/24
[ "https://Stackoverflow.com/questions/9437313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1082764/" ]
Actually, I like this [one better](https://stackoverflow.com/questions/584894/sed-scripting-environment-variable-substitution) ``` sed -i 's/{AUTH-KEYS-SALTS}/'"$keysalts"'/g' wp-config.php ``` Personal choice. :-)
It turns out you're asking the wrong question. I also asked the wrong question. The reason it's wrong is the beginning of the first sentence: "In my bash script...". I had the same question & made the same mistake. If you're using bash, you don't need to use sed to do string replacements (and it's much cleaner to use the replace feature built into bash). Instead of: ``` keysalts=`curl -sS https://api.wordpress.org/secret-key/1.1/salt/` sed -i "s/{AUTH-KEYS-SALTS}/$keysalts/g" wp-config.php ``` you can use bash features exclusively, reading the file into a variable, replacing the text in the variable, and writing the replaced text back out to the file: ``` INPUT=$(<wp-config.php) keysalts="$(curl -sS https://api.wordpress.org/secret-key/1.1/salt/)" echo "${INPUT//'{AUTH-KEYS-SALTS}'/"$keysalts"}" >wp-config.php ```
65,710
My college network requires Bradford Persistent Agent and Mcafee Virus Software 8.7i. The Bradford Persistent Agent basically checks to make sure Mcafee is running and updated, and reports this status to the network. If it is configured incorrectly, I cannot access the Internet. Right now, I am running off of the device network, (iPod/iPhone WiFi) which is considerably slower and doesn't enable me to use my Ethernet cable. With Windows Vista, everything was configured correctly. After my upgrade to Windows 7, Bradford Persistent Agent isn't registering the fact that Mcafee is installed and updated. Also, Windows Security Center isn't properly registering Mcafee as well, it knows that it is installed but can't read information reports from it. I have tried running the install files and the programs themselves in several configurations of compatibility modes, to no avail. I think this is a problem with Mcafee. Is there a solution? **Solution** (for me): 1. Windows Button -> type "services" -> click "services" icon at top of start menu 2. Navigate to Bradford Persistant Agent -> select Restart Service 3. Bradford Agent now recognized Mcafee (in my situation)
2009/11/04
[ "https://superuser.com/questions/65710", "https://superuser.com", "https://superuser.com/users/16130/" ]
Okay, if you are compiling yourself, then a simple ``` ./configure --prefix=/opt/git-1.6.5.2 ``` (and then `make`, `make install`) should suffice. Your binary files are now in `/opt/git-1.6.5.2/bin`. Obvously, you can change the directory to your needs.
Just install the new version. They will still be compatible. (no guarentees on 2.0 whenever they make it, but there should be **no** incompatibilites between two 1.6.x versions)
43,515,008
I have a func calculate\_tax that should take a *name:salary* pair as an argument, calculates the tax then returns a dictionary of *name:total\_tax* pair.However, it seem not to calculate tax correctly.What could I be doing wrong? Here is the code: ``` def calculate_tax(**data): for key in data: if data[key] > 0 and data[key] <= 1000: data[key] = 0 elif data[key] > 1000 and data[key] <= 10000: data[key] += (data[key]-1000)*0.1 elif data[key] > 10000 and data[key] <= 20200: data[key] += (data[key]-10000)*0.15 elif data[key] > 20200 and data[key] <= 30750: data[key] += (data[key]-20200)*0.2 elif data[key] > 30750 and data[key] <= 50000: data[key] += (data[key]-30750)*0.25 elif data[key] > 50000: data[key] += (data[key]-50000)*0.3 return data ``` The tax rates are: ``` Yearly Income: 0 - 1000 Tax Rate: 0% Yearly Income: 1,001 - 10,000 Tax Rate: 10% Yearly Income: 10,001 - 20,200 Tax Rate: 15% Yearly Income: 20,201 - 30,750 Tax Rate: 20% Yearly Income: 30,751 - 50,000 Tax Rate: 25% Yearly Income: Over 50,000 Tax Rate: 30% ``` For example, when given: ``` {'Ken':500,'Patrick':20500,'Winnie':70000} ``` it should return Patrick's tax as `2490`
2017/04/20
[ "https://Stackoverflow.com/questions/43515008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5127707/" ]
I would use `orElse` ``` static final List<String> CASH_CARD = Arrays.asList("CASH", "CARD"); public List<Order> getForHotelOrders(Long hotelId, Optional<LocalDate> fromDate, Optional<LocalDate> toDate, Optional<List<String>> paymentTypes) { List<String> paymentTypes2 = paymentTypes.orElse(CASH_CARD); return fromDate.isPresent() && toDate.isPresent() ? orderRepository.getForHotel(hotelId, fromDate.get(), toDate.get(), paymentTypes2) : orderRepository.getForHotel(hotelId, paymentTypes); } ``` or ``` public List<Order> getForHotelOrders(long hotelId, Optional<LocalDate> fromDate, Optional<LocalDate> toDate, Optional<List<String>> paymentTypes) { return orderRepository.getForHotel(hotelId, fromDate.orElse(LocalDate.MIN), toDate.orElse(LocalDate.MAX), paymentTypes.orElse(CASH_CARD)); } ``` BTW: If you are avoiding `null` values I would make `hotelId` either a `long` or a `OptionalLong`. Having a nullable `Long` seems inconsistent.
Can use orElse(default), to overcome multiple if else... ``` public List<Order> getForHotelOrders(Long hotelId, Optional<LocalDate> fromDate, Optional<LocalDate> toDate, Optional<List<String>> paymentTypes) { List<Order> orders; LocalDate defaultDate = LocalDate.now(); orders = orderRepository.getForHotel(hotelId, fromDate.orElse(defaultDate), toDate.orElse(defaultDate), paymentTypes.orElse(Arrays.asList("CASH", "CARD"))); return orders; } ```
11,474,301
I have lists of two Shapes - Rectangles and Circles. They both share 3 common properties - ID , Type and Bounds Circles have 2 extra properties - Range and Center How can i join lists of each type into a single list so i can iterate over them so i don't have to type two foreach cycles Could this be donne in a better way than combining the lists ? ``` public interface IRectangle { string Id { get; set; } GeoLocationTypes Type { get; set; } Bounds Bounds { get; set; } } public class Rectangle : IRectangle { public string Id { get; set; } public GeoLocationTypes Type { get; set; } public Bounds Bounds { get; set; } } public interface ICircle { string Id { get; set; } GeoLocationTypes Type { get; set; } Bounds Bounds { get; set; } float Radius { get; set; } Coordinates Center { get; set; } } public class Circle : ICircle { public string Id { get; set; } public GeoLocationTypes Type { get; set; } public Bounds Bounds { get; set; } public float Radius { get; set; } public Coordinates Center { get; set; } } public class Bounds { public Coordinates NE { get; set; } public Coordinates SW { get; set; } } public class Coordinates { public float Lat { get; set; } public float Lng { get; set; } } ```
2012/07/13
[ "https://Stackoverflow.com/questions/11474301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122765/" ]
Make an interface `IShape` that contains the common properties, then implement that as well as ICircle and IRectangle. (You could also use a base class that has the properties). You should them be able to join list of Circles and Rectangles to get a list of IShapes.
You could further add an interface ``` public interface IShape { string Id; GeoLocationTypes Type; Bounds Bounds; } ```
11,474,301
I have lists of two Shapes - Rectangles and Circles. They both share 3 common properties - ID , Type and Bounds Circles have 2 extra properties - Range and Center How can i join lists of each type into a single list so i can iterate over them so i don't have to type two foreach cycles Could this be donne in a better way than combining the lists ? ``` public interface IRectangle { string Id { get; set; } GeoLocationTypes Type { get; set; } Bounds Bounds { get; set; } } public class Rectangle : IRectangle { public string Id { get; set; } public GeoLocationTypes Type { get; set; } public Bounds Bounds { get; set; } } public interface ICircle { string Id { get; set; } GeoLocationTypes Type { get; set; } Bounds Bounds { get; set; } float Radius { get; set; } Coordinates Center { get; set; } } public class Circle : ICircle { public string Id { get; set; } public GeoLocationTypes Type { get; set; } public Bounds Bounds { get; set; } public float Radius { get; set; } public Coordinates Center { get; set; } } public class Bounds { public Coordinates NE { get; set; } public Coordinates SW { get; set; } } public class Coordinates { public float Lat { get; set; } public float Lng { get; set; } } ```
2012/07/13
[ "https://Stackoverflow.com/questions/11474301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122765/" ]
Make both `IRectangle` and `ICircle` inherit from a shared type - say `IShape`. A `List<IShape>` will then be able to take any `IRectangle` and `ICircle` types and their inheriting types. Since both `IRectangle` and `ICircle` share a number of properties, you can do this: ``` public interface IShape { string Id { get; set; } GeoLocationTypes Type { get; set; } Bounds Bounds { get; set; } } public interface ICircle : IShape { float Radius { get; set; } Coordinates Center { get; set; } } public interface IRectangle : IShape { } ```
You could further add an interface ``` public interface IShape { string Id; GeoLocationTypes Type; Bounds Bounds; } ```
11,474,301
I have lists of two Shapes - Rectangles and Circles. They both share 3 common properties - ID , Type and Bounds Circles have 2 extra properties - Range and Center How can i join lists of each type into a single list so i can iterate over them so i don't have to type two foreach cycles Could this be donne in a better way than combining the lists ? ``` public interface IRectangle { string Id { get; set; } GeoLocationTypes Type { get; set; } Bounds Bounds { get; set; } } public class Rectangle : IRectangle { public string Id { get; set; } public GeoLocationTypes Type { get; set; } public Bounds Bounds { get; set; } } public interface ICircle { string Id { get; set; } GeoLocationTypes Type { get; set; } Bounds Bounds { get; set; } float Radius { get; set; } Coordinates Center { get; set; } } public class Circle : ICircle { public string Id { get; set; } public GeoLocationTypes Type { get; set; } public Bounds Bounds { get; set; } public float Radius { get; set; } public Coordinates Center { get; set; } } public class Bounds { public Coordinates NE { get; set; } public Coordinates SW { get; set; } } public class Coordinates { public float Lat { get; set; } public float Lng { get; set; } } ```
2012/07/13
[ "https://Stackoverflow.com/questions/11474301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122765/" ]
You could further add an interface ``` public interface IShape { string Id; GeoLocationTypes Type; Bounds Bounds; } ```
How about this ``` var merged = Rectagles.Select(r => new { r.Id, r.Type, r.Bounds, Radius = float.NaN, Centre = default(Coordinates) }) .Concat(Circles.Select(c => new { c.Id, c.Type, c.Bounds, c.Radius, c.Centre })); ``` it gives a list of enumerable of an anonymous type that exposes the required information. --- **EDIT** To my amazement this actually seems to compile. So there is a solution that works without defining a common interface. However for anything but the quick and dirty I would consider polymorphic over anonymous.
11,474,301
I have lists of two Shapes - Rectangles and Circles. They both share 3 common properties - ID , Type and Bounds Circles have 2 extra properties - Range and Center How can i join lists of each type into a single list so i can iterate over them so i don't have to type two foreach cycles Could this be donne in a better way than combining the lists ? ``` public interface IRectangle { string Id { get; set; } GeoLocationTypes Type { get; set; } Bounds Bounds { get; set; } } public class Rectangle : IRectangle { public string Id { get; set; } public GeoLocationTypes Type { get; set; } public Bounds Bounds { get; set; } } public interface ICircle { string Id { get; set; } GeoLocationTypes Type { get; set; } Bounds Bounds { get; set; } float Radius { get; set; } Coordinates Center { get; set; } } public class Circle : ICircle { public string Id { get; set; } public GeoLocationTypes Type { get; set; } public Bounds Bounds { get; set; } public float Radius { get; set; } public Coordinates Center { get; set; } } public class Bounds { public Coordinates NE { get; set; } public Coordinates SW { get; set; } } public class Coordinates { public float Lat { get; set; } public float Lng { get; set; } } ```
2012/07/13
[ "https://Stackoverflow.com/questions/11474301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122765/" ]
Make both `IRectangle` and `ICircle` inherit from a shared type - say `IShape`. A `List<IShape>` will then be able to take any `IRectangle` and `ICircle` types and their inheriting types. Since both `IRectangle` and `ICircle` share a number of properties, you can do this: ``` public interface IShape { string Id { get; set; } GeoLocationTypes Type { get; set; } Bounds Bounds { get; set; } } public interface ICircle : IShape { float Radius { get; set; } Coordinates Center { get; set; } } public interface IRectangle : IShape { } ```
Make an interface `IShape` that contains the common properties, then implement that as well as ICircle and IRectangle. (You could also use a base class that has the properties). You should them be able to join list of Circles and Rectangles to get a list of IShapes.
11,474,301
I have lists of two Shapes - Rectangles and Circles. They both share 3 common properties - ID , Type and Bounds Circles have 2 extra properties - Range and Center How can i join lists of each type into a single list so i can iterate over them so i don't have to type two foreach cycles Could this be donne in a better way than combining the lists ? ``` public interface IRectangle { string Id { get; set; } GeoLocationTypes Type { get; set; } Bounds Bounds { get; set; } } public class Rectangle : IRectangle { public string Id { get; set; } public GeoLocationTypes Type { get; set; } public Bounds Bounds { get; set; } } public interface ICircle { string Id { get; set; } GeoLocationTypes Type { get; set; } Bounds Bounds { get; set; } float Radius { get; set; } Coordinates Center { get; set; } } public class Circle : ICircle { public string Id { get; set; } public GeoLocationTypes Type { get; set; } public Bounds Bounds { get; set; } public float Radius { get; set; } public Coordinates Center { get; set; } } public class Bounds { public Coordinates NE { get; set; } public Coordinates SW { get; set; } } public class Coordinates { public float Lat { get; set; } public float Lng { get; set; } } ```
2012/07/13
[ "https://Stackoverflow.com/questions/11474301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122765/" ]
Make an interface `IShape` that contains the common properties, then implement that as well as ICircle and IRectangle. (You could also use a base class that has the properties). You should them be able to join list of Circles and Rectangles to get a list of IShapes.
You could make them each use an IShape interface, or you could iterate over Objects and cast. ``` public interface IShape { string Id { get; set; } GeoLocationTypes Type { get; set; } Bounds Bounds { get; set; } } public interface IRectangle : IShape { } public class Rectangle : IRectangle { // No change } public interface ICircle : IShape { float Radius { get; set; } Coordinates Center { get; set; } } public class Circle : ICircle { // No change } public class Bounds { // No change } public class Coordinates { // No change } ``` There is also the [Zip](http://msdn.microsoft.com/en-us/library/dd267698%28VS.100%29.aspx) function that will allow you to enumerate over all of them. An example: ``` var numbers= new [] { 1, 2, 3, 4 }; var words = new [] { "one", "two", "three" }; var numbersAndWords = numbers.Zip(words, (n, w) => new { Number = n, Word = w }); foreach(var nw in numbersAndWords) { Console.WriteLine(nw.Number + nw.Word); } ```
11,474,301
I have lists of two Shapes - Rectangles and Circles. They both share 3 common properties - ID , Type and Bounds Circles have 2 extra properties - Range and Center How can i join lists of each type into a single list so i can iterate over them so i don't have to type two foreach cycles Could this be donne in a better way than combining the lists ? ``` public interface IRectangle { string Id { get; set; } GeoLocationTypes Type { get; set; } Bounds Bounds { get; set; } } public class Rectangle : IRectangle { public string Id { get; set; } public GeoLocationTypes Type { get; set; } public Bounds Bounds { get; set; } } public interface ICircle { string Id { get; set; } GeoLocationTypes Type { get; set; } Bounds Bounds { get; set; } float Radius { get; set; } Coordinates Center { get; set; } } public class Circle : ICircle { public string Id { get; set; } public GeoLocationTypes Type { get; set; } public Bounds Bounds { get; set; } public float Radius { get; set; } public Coordinates Center { get; set; } } public class Bounds { public Coordinates NE { get; set; } public Coordinates SW { get; set; } } public class Coordinates { public float Lat { get; set; } public float Lng { get; set; } } ```
2012/07/13
[ "https://Stackoverflow.com/questions/11474301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122765/" ]
Make an interface `IShape` that contains the common properties, then implement that as well as ICircle and IRectangle. (You could also use a base class that has the properties). You should them be able to join list of Circles and Rectangles to get a list of IShapes.
How about this ``` var merged = Rectagles.Select(r => new { r.Id, r.Type, r.Bounds, Radius = float.NaN, Centre = default(Coordinates) }) .Concat(Circles.Select(c => new { c.Id, c.Type, c.Bounds, c.Radius, c.Centre })); ``` it gives a list of enumerable of an anonymous type that exposes the required information. --- **EDIT** To my amazement this actually seems to compile. So there is a solution that works without defining a common interface. However for anything but the quick and dirty I would consider polymorphic over anonymous.
11,474,301
I have lists of two Shapes - Rectangles and Circles. They both share 3 common properties - ID , Type and Bounds Circles have 2 extra properties - Range and Center How can i join lists of each type into a single list so i can iterate over them so i don't have to type two foreach cycles Could this be donne in a better way than combining the lists ? ``` public interface IRectangle { string Id { get; set; } GeoLocationTypes Type { get; set; } Bounds Bounds { get; set; } } public class Rectangle : IRectangle { public string Id { get; set; } public GeoLocationTypes Type { get; set; } public Bounds Bounds { get; set; } } public interface ICircle { string Id { get; set; } GeoLocationTypes Type { get; set; } Bounds Bounds { get; set; } float Radius { get; set; } Coordinates Center { get; set; } } public class Circle : ICircle { public string Id { get; set; } public GeoLocationTypes Type { get; set; } public Bounds Bounds { get; set; } public float Radius { get; set; } public Coordinates Center { get; set; } } public class Bounds { public Coordinates NE { get; set; } public Coordinates SW { get; set; } } public class Coordinates { public float Lat { get; set; } public float Lng { get; set; } } ```
2012/07/13
[ "https://Stackoverflow.com/questions/11474301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122765/" ]
Make both `IRectangle` and `ICircle` inherit from a shared type - say `IShape`. A `List<IShape>` will then be able to take any `IRectangle` and `ICircle` types and their inheriting types. Since both `IRectangle` and `ICircle` share a number of properties, you can do this: ``` public interface IShape { string Id { get; set; } GeoLocationTypes Type { get; set; } Bounds Bounds { get; set; } } public interface ICircle : IShape { float Radius { get; set; } Coordinates Center { get; set; } } public interface IRectangle : IShape { } ```
You could make them each use an IShape interface, or you could iterate over Objects and cast. ``` public interface IShape { string Id { get; set; } GeoLocationTypes Type { get; set; } Bounds Bounds { get; set; } } public interface IRectangle : IShape { } public class Rectangle : IRectangle { // No change } public interface ICircle : IShape { float Radius { get; set; } Coordinates Center { get; set; } } public class Circle : ICircle { // No change } public class Bounds { // No change } public class Coordinates { // No change } ``` There is also the [Zip](http://msdn.microsoft.com/en-us/library/dd267698%28VS.100%29.aspx) function that will allow you to enumerate over all of them. An example: ``` var numbers= new [] { 1, 2, 3, 4 }; var words = new [] { "one", "two", "three" }; var numbersAndWords = numbers.Zip(words, (n, w) => new { Number = n, Word = w }); foreach(var nw in numbersAndWords) { Console.WriteLine(nw.Number + nw.Word); } ```
11,474,301
I have lists of two Shapes - Rectangles and Circles. They both share 3 common properties - ID , Type and Bounds Circles have 2 extra properties - Range and Center How can i join lists of each type into a single list so i can iterate over them so i don't have to type two foreach cycles Could this be donne in a better way than combining the lists ? ``` public interface IRectangle { string Id { get; set; } GeoLocationTypes Type { get; set; } Bounds Bounds { get; set; } } public class Rectangle : IRectangle { public string Id { get; set; } public GeoLocationTypes Type { get; set; } public Bounds Bounds { get; set; } } public interface ICircle { string Id { get; set; } GeoLocationTypes Type { get; set; } Bounds Bounds { get; set; } float Radius { get; set; } Coordinates Center { get; set; } } public class Circle : ICircle { public string Id { get; set; } public GeoLocationTypes Type { get; set; } public Bounds Bounds { get; set; } public float Radius { get; set; } public Coordinates Center { get; set; } } public class Bounds { public Coordinates NE { get; set; } public Coordinates SW { get; set; } } public class Coordinates { public float Lat { get; set; } public float Lng { get; set; } } ```
2012/07/13
[ "https://Stackoverflow.com/questions/11474301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122765/" ]
Make both `IRectangle` and `ICircle` inherit from a shared type - say `IShape`. A `List<IShape>` will then be able to take any `IRectangle` and `ICircle` types and their inheriting types. Since both `IRectangle` and `ICircle` share a number of properties, you can do this: ``` public interface IShape { string Id { get; set; } GeoLocationTypes Type { get; set; } Bounds Bounds { get; set; } } public interface ICircle : IShape { float Radius { get; set; } Coordinates Center { get; set; } } public interface IRectangle : IShape { } ```
How about this ``` var merged = Rectagles.Select(r => new { r.Id, r.Type, r.Bounds, Radius = float.NaN, Centre = default(Coordinates) }) .Concat(Circles.Select(c => new { c.Id, c.Type, c.Bounds, c.Radius, c.Centre })); ``` it gives a list of enumerable of an anonymous type that exposes the required information. --- **EDIT** To my amazement this actually seems to compile. So there is a solution that works without defining a common interface. However for anything but the quick and dirty I would consider polymorphic over anonymous.
11,474,301
I have lists of two Shapes - Rectangles and Circles. They both share 3 common properties - ID , Type and Bounds Circles have 2 extra properties - Range and Center How can i join lists of each type into a single list so i can iterate over them so i don't have to type two foreach cycles Could this be donne in a better way than combining the lists ? ``` public interface IRectangle { string Id { get; set; } GeoLocationTypes Type { get; set; } Bounds Bounds { get; set; } } public class Rectangle : IRectangle { public string Id { get; set; } public GeoLocationTypes Type { get; set; } public Bounds Bounds { get; set; } } public interface ICircle { string Id { get; set; } GeoLocationTypes Type { get; set; } Bounds Bounds { get; set; } float Radius { get; set; } Coordinates Center { get; set; } } public class Circle : ICircle { public string Id { get; set; } public GeoLocationTypes Type { get; set; } public Bounds Bounds { get; set; } public float Radius { get; set; } public Coordinates Center { get; set; } } public class Bounds { public Coordinates NE { get; set; } public Coordinates SW { get; set; } } public class Coordinates { public float Lat { get; set; } public float Lng { get; set; } } ```
2012/07/13
[ "https://Stackoverflow.com/questions/11474301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122765/" ]
You could make them each use an IShape interface, or you could iterate over Objects and cast. ``` public interface IShape { string Id { get; set; } GeoLocationTypes Type { get; set; } Bounds Bounds { get; set; } } public interface IRectangle : IShape { } public class Rectangle : IRectangle { // No change } public interface ICircle : IShape { float Radius { get; set; } Coordinates Center { get; set; } } public class Circle : ICircle { // No change } public class Bounds { // No change } public class Coordinates { // No change } ``` There is also the [Zip](http://msdn.microsoft.com/en-us/library/dd267698%28VS.100%29.aspx) function that will allow you to enumerate over all of them. An example: ``` var numbers= new [] { 1, 2, 3, 4 }; var words = new [] { "one", "two", "three" }; var numbersAndWords = numbers.Zip(words, (n, w) => new { Number = n, Word = w }); foreach(var nw in numbersAndWords) { Console.WriteLine(nw.Number + nw.Word); } ```
How about this ``` var merged = Rectagles.Select(r => new { r.Id, r.Type, r.Bounds, Radius = float.NaN, Centre = default(Coordinates) }) .Concat(Circles.Select(c => new { c.Id, c.Type, c.Bounds, c.Radius, c.Centre })); ``` it gives a list of enumerable of an anonymous type that exposes the required information. --- **EDIT** To my amazement this actually seems to compile. So there is a solution that works without defining a common interface. However for anything but the quick and dirty I would consider polymorphic over anonymous.
20,438,517
I have a list of ID’s Shown below. ``` AT0920130004 AT0920130005 AT0920130006 AT0920130007 AT0920130008 AT0920130009 AT0920130010 AT1020130001 AT1020130002 AT1020130003 AT1020130004 AT1020130005 AT1120130003 AT1120130004 AT1120130005 AT1120130006 ``` Here an example record has the format `ATmmyyyyxxxx`. where `AT` represents `location`, `mm` represents `month` eg 10 would be `October` `yyyy` represents `year` eg. `2013` `xxxx` represents the `increasing seed of numbers`. Now I need to select an ID which is generated in the `end of the month`. For ex: last id of September i.e. AT0920130010. Any suggestions are appreciated.
2013/12/07
[ "https://Stackoverflow.com/questions/20438517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2881402/" ]
You can use this query to get max ID for each month and year ``` select substring([id], 3, 6) MonthYear, max([id]) MaxID from yourtable group by substring([id], 3, 6) ``` --- To get max ID for one specific month, you can use this query: ``` select max([id]) from yourtable where cast(substring([id], 5, 4) as int) = 2013 -- year and cast(substring([id], 3, 2) as int) = 9 -- month ```
try this : ``` select MAX(t.ID) from TableName t group by SUBSTRING(t.ID, 3, 2) ```
20,438,517
I have a list of ID’s Shown below. ``` AT0920130004 AT0920130005 AT0920130006 AT0920130007 AT0920130008 AT0920130009 AT0920130010 AT1020130001 AT1020130002 AT1020130003 AT1020130004 AT1020130005 AT1120130003 AT1120130004 AT1120130005 AT1120130006 ``` Here an example record has the format `ATmmyyyyxxxx`. where `AT` represents `location`, `mm` represents `month` eg 10 would be `October` `yyyy` represents `year` eg. `2013` `xxxx` represents the `increasing seed of numbers`. Now I need to select an ID which is generated in the `end of the month`. For ex: last id of September i.e. AT0920130010. Any suggestions are appreciated.
2013/12/07
[ "https://Stackoverflow.com/questions/20438517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2881402/" ]
try this : ``` select MAX(t.ID) from TableName t group by SUBSTRING(t.ID, 3, 2) ```
You basically want to get the max id that matches a location, a month and a year. Something like this should do it: ``` SELECT max(id) FROM myTable WHERE substring(id, 0, 2) = [location] AND susbstring(id, 2, 2) = [month] AND substring(id, 4, 4) = [year] ```
20,438,517
I have a list of ID’s Shown below. ``` AT0920130004 AT0920130005 AT0920130006 AT0920130007 AT0920130008 AT0920130009 AT0920130010 AT1020130001 AT1020130002 AT1020130003 AT1020130004 AT1020130005 AT1120130003 AT1120130004 AT1120130005 AT1120130006 ``` Here an example record has the format `ATmmyyyyxxxx`. where `AT` represents `location`, `mm` represents `month` eg 10 would be `October` `yyyy` represents `year` eg. `2013` `xxxx` represents the `increasing seed of numbers`. Now I need to select an ID which is generated in the `end of the month`. For ex: last id of September i.e. AT0920130010. Any suggestions are appreciated.
2013/12/07
[ "https://Stackoverflow.com/questions/20438517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2881402/" ]
try this : ``` select MAX(t.ID) from TableName t group by SUBSTRING(t.ID, 3, 2) ```
try this(this will return whole field, and just id): ``` SELECT YOUR_FIELD, MAX(RIGHT(YOUR_FIELD,4)) AS just_id FROM YOUR_TABLE WHERE RIGHT(YOUR_FIELD,LENGTH(YOUR_FIELD)-2) LIKE '09%' ```
20,438,517
I have a list of ID’s Shown below. ``` AT0920130004 AT0920130005 AT0920130006 AT0920130007 AT0920130008 AT0920130009 AT0920130010 AT1020130001 AT1020130002 AT1020130003 AT1020130004 AT1020130005 AT1120130003 AT1120130004 AT1120130005 AT1120130006 ``` Here an example record has the format `ATmmyyyyxxxx`. where `AT` represents `location`, `mm` represents `month` eg 10 would be `October` `yyyy` represents `year` eg. `2013` `xxxx` represents the `increasing seed of numbers`. Now I need to select an ID which is generated in the `end of the month`. For ex: last id of September i.e. AT0920130010. Any suggestions are appreciated.
2013/12/07
[ "https://Stackoverflow.com/questions/20438517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2881402/" ]
You can use this query to get max ID for each month and year ``` select substring([id], 3, 6) MonthYear, max([id]) MaxID from yourtable group by substring([id], 3, 6) ``` --- To get max ID for one specific month, you can use this query: ``` select max([id]) from yourtable where cast(substring([id], 5, 4) as int) = 2013 -- year and cast(substring([id], 3, 2) as int) = 9 -- month ```
You basically want to get the max id that matches a location, a month and a year. Something like this should do it: ``` SELECT max(id) FROM myTable WHERE substring(id, 0, 2) = [location] AND susbstring(id, 2, 2) = [month] AND substring(id, 4, 4) = [year] ```
20,438,517
I have a list of ID’s Shown below. ``` AT0920130004 AT0920130005 AT0920130006 AT0920130007 AT0920130008 AT0920130009 AT0920130010 AT1020130001 AT1020130002 AT1020130003 AT1020130004 AT1020130005 AT1120130003 AT1120130004 AT1120130005 AT1120130006 ``` Here an example record has the format `ATmmyyyyxxxx`. where `AT` represents `location`, `mm` represents `month` eg 10 would be `October` `yyyy` represents `year` eg. `2013` `xxxx` represents the `increasing seed of numbers`. Now I need to select an ID which is generated in the `end of the month`. For ex: last id of September i.e. AT0920130010. Any suggestions are appreciated.
2013/12/07
[ "https://Stackoverflow.com/questions/20438517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2881402/" ]
You can use this query to get max ID for each month and year ``` select substring([id], 3, 6) MonthYear, max([id]) MaxID from yourtable group by substring([id], 3, 6) ``` --- To get max ID for one specific month, you can use this query: ``` select max([id]) from yourtable where cast(substring([id], 5, 4) as int) = 2013 -- year and cast(substring([id], 3, 2) as int) = 9 -- month ```
try this(this will return whole field, and just id): ``` SELECT YOUR_FIELD, MAX(RIGHT(YOUR_FIELD,4)) AS just_id FROM YOUR_TABLE WHERE RIGHT(YOUR_FIELD,LENGTH(YOUR_FIELD)-2) LIKE '09%' ```
59,085,586
I recently discovered this way of doing in VBA, you populate a function value by passing it as an argument of another function, and then, when the parameter of this other function is filled, its link to the first function value. **EDIT FOR CLARIFICATION** : This idea explained by the teacher was that sometimes, you have a complicated function and then we can extract several informations from the result. And those functions are meant to be used in excel, so instead of letting people calling the complicated one, you create "dummy" functions, like result1 et and result2, and it will be filled with the value we want. **Here is the code (edited, i forget things sorry):** ``` Function f(* a lot of parameters *, Optional result1 As Variant, Optional result2 as Variant) as Boolean raw_result = * a lot of calculus * result1 = raw_result result2 = -raw_result f = True End Function Function result1(* same parameters than f *) as Double ' I will give result1 Call f(* same parameters than f *, result1) End Function Function result2(* same parameters than f *) as Double 'Two coma on purpose to access the second optional parameters Call f(* same parameters than f *,, result2) End Function ``` Here, if i do `result1(* same parameter than f*)`, it will give me `raw_result` value. What is the theory behind this concept, how does it work and is it only a VBA thing ?
2019/11/28
[ "https://Stackoverflow.com/questions/59085586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6621137/" ]
I am not sure what you are meaning to do here, but the function is nothing but an unnecessarily nested function. The `g` in the second function is not used whatsoever in its execution, and neither is `b` as optional parameter. For example what happens for g(3): With `a` replaced by "3" ``` Function g("3" as integer) g = f("3", "blank") End Function ``` ``` Function f("3" As Integer, Optional "Blank" As Variant) b = "3" * 2 f = b (=6) End Function ``` Meaning when returning to the first function, your answer is 6. For clarification: `g` will hold no value unless everything after `=` is evaluated. Then after this is evaluated, `g` will hold a value, but it is not re-evaluated as the function will run only once. Despite this, even if you were to pass `g` as 6 for example, it is discarded by the second function (where it is called `b`) as its first action is to assign a new value to `b`, overwriting whatever value it held. Edit: As the question change, my answer will have to change as well. The issue with what you're doing is that whichever you call (`result1` or `result2`) this doesn't give a different result. Whichever way you call function `f`, and whatever you do inside of it, the only thing it will return is what you set `f` as, in this case `True`. So you can do a plethora of calculations in both `result1` and `result2`, the only return you will get from calling either of these will be "True". This way of nesting functions is not the correct way to get different results from a function. It can be done however, by declaring `result1` and `result2` in your `f` function as public, and accessing them later on for example.
In VBA, within a function you can `access/assign` a value to the function name and no you cannot pass an actual function like you would do in C# `Func<T1, T2, TResult>` i.e. ``` Function g(a as integer) 'Here you are allowed do read or write values to the function name g. 'g = 10 ' assigning a return value 'debug.print g 'Now reading the value g = f(a,g) ' here you are not passing a function as parameter. You are passing the return value of g as a parameter. Which in your case g would be empty like. g = f(3, empty) End Function ```
59,085,586
I recently discovered this way of doing in VBA, you populate a function value by passing it as an argument of another function, and then, when the parameter of this other function is filled, its link to the first function value. **EDIT FOR CLARIFICATION** : This idea explained by the teacher was that sometimes, you have a complicated function and then we can extract several informations from the result. And those functions are meant to be used in excel, so instead of letting people calling the complicated one, you create "dummy" functions, like result1 et and result2, and it will be filled with the value we want. **Here is the code (edited, i forget things sorry):** ``` Function f(* a lot of parameters *, Optional result1 As Variant, Optional result2 as Variant) as Boolean raw_result = * a lot of calculus * result1 = raw_result result2 = -raw_result f = True End Function Function result1(* same parameters than f *) as Double ' I will give result1 Call f(* same parameters than f *, result1) End Function Function result2(* same parameters than f *) as Double 'Two coma on purpose to access the second optional parameters Call f(* same parameters than f *,, result2) End Function ``` Here, if i do `result1(* same parameter than f*)`, it will give me `raw_result` value. What is the theory behind this concept, how does it work and is it only a VBA thing ?
2019/11/28
[ "https://Stackoverflow.com/questions/59085586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6621137/" ]
I changed it into an example that can be run: ``` Option Explicit Sub Test() Debug.Print result1(1, 2, 3) Debug.Print result2(1, 2, 3) End Sub Function f(a, b, c, Optional result1 As Variant, Optional result2 As Variant) As Boolean Dim raw_result raw_result = a + b + c result1 = raw_result result2 = -raw_result f = True End Function Function result1(a, b, c) As Double ' I will give result1 Call f(a, b, c, result1) End Function Function result2(a, b, c) As Double 'Two coma on purpose to access the second optional parameters Call f(a, b, c, , result2) End Function ``` In this case `result1` and `result2` are both submitted `ByRef` (which is the default in VBA) and not `ByVal`. This line ``` Function f(a, b, c, Optional result1 As Variant, Optional result2 As Variant) As Boolean ``` is (by default) exactly the same like ``` Function f(a, b, c, Optional ByRef result1 As Variant, Optional ByRef result2 As Variant) As Boolean ``` if you change it to `ByVal` ``` Function f(a, b, c, Optional ByVal result1 As Variant, Optional ByVal result2 As Variant) As Boolean ``` then the result of `Test()` would be `0` because nothingt can be returned in `result1` and `result2` (no reference). **Here is another example** ``` Sub TestIt() Dim VarA As Long VarA = 1 Dim VarB As Long VarB = 2 MyProcedure VarA, VarB '≙ 1, 2 Debug.Print VarA, VarB 'output is 10, 2 End Sub Sub MyProcedure(ByRef ParamA As Long, ByVal ParamB As Long) ParamA = 10 'will be returned to VarA because it is referenced (ByRef) ParamB = 20 'will NOT be returned to VarB because it is NOT referenced. End Sub ``` The difference is that … * if you submit a variable `ByRef` like `ParamA` then your procedure (or function) will return any changes of `ParamA` to your variable `VarA`. * if you submit a variable `ByVal` you don't submit a variable but only its value. Therefore your procedure (or function) cannot return any changes.
In VBA, within a function you can `access/assign` a value to the function name and no you cannot pass an actual function like you would do in C# `Func<T1, T2, TResult>` i.e. ``` Function g(a as integer) 'Here you are allowed do read or write values to the function name g. 'g = 10 ' assigning a return value 'debug.print g 'Now reading the value g = f(a,g) ' here you are not passing a function as parameter. You are passing the return value of g as a parameter. Which in your case g would be empty like. g = f(3, empty) End Function ```
59,085,586
I recently discovered this way of doing in VBA, you populate a function value by passing it as an argument of another function, and then, when the parameter of this other function is filled, its link to the first function value. **EDIT FOR CLARIFICATION** : This idea explained by the teacher was that sometimes, you have a complicated function and then we can extract several informations from the result. And those functions are meant to be used in excel, so instead of letting people calling the complicated one, you create "dummy" functions, like result1 et and result2, and it will be filled with the value we want. **Here is the code (edited, i forget things sorry):** ``` Function f(* a lot of parameters *, Optional result1 As Variant, Optional result2 as Variant) as Boolean raw_result = * a lot of calculus * result1 = raw_result result2 = -raw_result f = True End Function Function result1(* same parameters than f *) as Double ' I will give result1 Call f(* same parameters than f *, result1) End Function Function result2(* same parameters than f *) as Double 'Two coma on purpose to access the second optional parameters Call f(* same parameters than f *,, result2) End Function ``` Here, if i do `result1(* same parameter than f*)`, it will give me `raw_result` value. What is the theory behind this concept, how does it work and is it only a VBA thing ?
2019/11/28
[ "https://Stackoverflow.com/questions/59085586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6621137/" ]
I changed it into an example that can be run: ``` Option Explicit Sub Test() Debug.Print result1(1, 2, 3) Debug.Print result2(1, 2, 3) End Sub Function f(a, b, c, Optional result1 As Variant, Optional result2 As Variant) As Boolean Dim raw_result raw_result = a + b + c result1 = raw_result result2 = -raw_result f = True End Function Function result1(a, b, c) As Double ' I will give result1 Call f(a, b, c, result1) End Function Function result2(a, b, c) As Double 'Two coma on purpose to access the second optional parameters Call f(a, b, c, , result2) End Function ``` In this case `result1` and `result2` are both submitted `ByRef` (which is the default in VBA) and not `ByVal`. This line ``` Function f(a, b, c, Optional result1 As Variant, Optional result2 As Variant) As Boolean ``` is (by default) exactly the same like ``` Function f(a, b, c, Optional ByRef result1 As Variant, Optional ByRef result2 As Variant) As Boolean ``` if you change it to `ByVal` ``` Function f(a, b, c, Optional ByVal result1 As Variant, Optional ByVal result2 As Variant) As Boolean ``` then the result of `Test()` would be `0` because nothingt can be returned in `result1` and `result2` (no reference). **Here is another example** ``` Sub TestIt() Dim VarA As Long VarA = 1 Dim VarB As Long VarB = 2 MyProcedure VarA, VarB '≙ 1, 2 Debug.Print VarA, VarB 'output is 10, 2 End Sub Sub MyProcedure(ByRef ParamA As Long, ByVal ParamB As Long) ParamA = 10 'will be returned to VarA because it is referenced (ByRef) ParamB = 20 'will NOT be returned to VarB because it is NOT referenced. End Sub ``` The difference is that … * if you submit a variable `ByRef` like `ParamA` then your procedure (or function) will return any changes of `ParamA` to your variable `VarA`. * if you submit a variable `ByVal` you don't submit a variable but only its value. Therefore your procedure (or function) cannot return any changes.
I am not sure what you are meaning to do here, but the function is nothing but an unnecessarily nested function. The `g` in the second function is not used whatsoever in its execution, and neither is `b` as optional parameter. For example what happens for g(3): With `a` replaced by "3" ``` Function g("3" as integer) g = f("3", "blank") End Function ``` ``` Function f("3" As Integer, Optional "Blank" As Variant) b = "3" * 2 f = b (=6) End Function ``` Meaning when returning to the first function, your answer is 6. For clarification: `g` will hold no value unless everything after `=` is evaluated. Then after this is evaluated, `g` will hold a value, but it is not re-evaluated as the function will run only once. Despite this, even if you were to pass `g` as 6 for example, it is discarded by the second function (where it is called `b`) as its first action is to assign a new value to `b`, overwriting whatever value it held. Edit: As the question change, my answer will have to change as well. The issue with what you're doing is that whichever you call (`result1` or `result2`) this doesn't give a different result. Whichever way you call function `f`, and whatever you do inside of it, the only thing it will return is what you set `f` as, in this case `True`. So you can do a plethora of calculations in both `result1` and `result2`, the only return you will get from calling either of these will be "True". This way of nesting functions is not the correct way to get different results from a function. It can be done however, by declaring `result1` and `result2` in your `f` function as public, and accessing them later on for example.
324,162
I have a figure `fig_name.eps` with the surrounding text in `fig_name.tex`. They are in a sub directory called fig\_dir. I used the following in the beginning of my document to change the path for `input`. ``` \makeatletter \def\input@path{{/path/to/fig_dir/}} \makeatother ``` I am using `\input{fig_name}` to include the figure. On compilation it shows error that file not found. What did I do wrong? Edit : I am adding a MWE below. ``` \documentclass[a4paper,fleqn,usenatbib]{mnras} \usepackage[T1]{fontenc} \usepackage{graphicx} \usepackage{epsfig} %TO INCLUDE FIGURES FROM FOLDER NAMED fig_dir \makeatletter \def\input@path{{/path/to/fig_dir/}} \makeatother \begin{document} %THIS ONE WORKS FINE \begin{figure} \includegraphics[width=7cm]{fig_dir/bla_bla.png} \caption{bla_bla} \end{figure} %THIS ONE DOESN'T \begin{figure} \centering \resizebox{!}{0.30\textwidth}{\input{fig_name}} \caption{fig_name} \end{figure} \end{document} ```
2016/08/10
[ "https://tex.stackexchange.com/questions/324162", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/111739/" ]
gnuplot's `epslatex` terminal creates two files `fig_name.tex` and `fig_name.eps`. You have to call `fig_name.tex` from your main file with `\input{fig_name}`, but this one will load `fig_name.eps` with an `\includegraphics` command. Open `fig_name.tex` with an editor and will find a line with contents: ``` \put(0,0){\includegraphics{fig_name}}% ``` So the easyest solution would be to add a `\graphicspath` command with the `subfiles` folder and call the `.tex` file with `\input{subfile/fig_name}`. Now suppose gnuplot created `mytest.tex` and `mytest.eps`, and both are stored in subfolder `gnuplot`. Following code works: ``` \documentclass{article} \usepackage{graphicx} \graphicspath{{gnuplot/}} \begin{document} \input{gnuplot/mytest} \end{document} ```
Too long for a comment. The following works fine for me: ``` % My standard header for TeX.SX answers: \documentclass[a4paper]{article} % To avoid confusion, let us explicitly % declare the paper format. \usepackage[T1]{fontenc} % Not always necessary, but recommended. % End of standard header. What follows pertains to the problem at hand. \usepackage{graphics} \makeatletter \def\input@path{{Sub_dir/}} \makeatother \begin{document} Some random text. \begin{figure}[tbp] \centering \resizebox{0.5\textwidth}{!}{Where are you? \input{HereAmI}} \caption{My figure} \end{figure} \end{document} ``` Save the above code in a certain directory, then create, inside that same directory, a subdirectory named `Sub_dir`; save the following code in a file named `HereAmI.tex` placed inside `Sub_dir`: ``` Here am~I\@! ``` Does this work correctly?
11,015,807
I am successfully using zxing to scan codes, by calling the installed barcode reader's intent, but when it beeps and indicates a good scan I expect the zxing activity would return control so I can process the result, but it sits there and tries to scan again. I have to press the back button and *then* it returns and I can do the next step. Is there some obvious flag I'm missing when I call the scanner? Any advice gratefully received. Many thanks. Here's my code: ``` public boolean onTouchEvent(final MotionEvent event) { Intent intent = new Intent("com.google.zxing.client.android.SCAN"); intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE"); startActivityForResult(intent, 0); return true; } public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (requestCode == 0) { if (resultCode == RESULT_OK) { String contents = intent.getStringExtra("SCAN_RESULT"); String format = intent.getStringExtra("SCAN_RESULT_FORMAT"); // Handle successful scan String s = "http://www.google.com/search?q="; s += contents; Intent myIntent1 = new Intent(Intent.ACTION_VIEW, Uri.parse(s)); startActivity(myIntent1); } else if (resultCode == RESULT_CANCELED) { // Handle cancel } } } } ```
2012/06/13
[ "https://Stackoverflow.com/questions/11015807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/769506/" ]
Why not use the provided `IntentIntegrator` class? This is the only approach mentioned in the project docs, did you have a look at those? <https://github.com/zxing/zxing/wiki/Scanning-Via-Intent> I created it to wrap up these details of sending and parsing the Intent, so you don't make typos. For example, there's no such thing as extra "com.google.zxing.client.android.SCAN.SCAN\_MODE".
Add finishActivity(requestCode); at the end of onActivityResult() method. Try this: Replace your first 2 lines in onTouch with the below code. It seems the issue is while scanning codes other than QR. Please remove the scan filter and check once. Intent intent = new Intent("com.google.zxing.client.android.SCAN"); intent.addFlags(Intent.FLAG\_ACTIVITY\_CLEAR\_WHEN\_TASK\_RESET);
11,015,807
I am successfully using zxing to scan codes, by calling the installed barcode reader's intent, but when it beeps and indicates a good scan I expect the zxing activity would return control so I can process the result, but it sits there and tries to scan again. I have to press the back button and *then* it returns and I can do the next step. Is there some obvious flag I'm missing when I call the scanner? Any advice gratefully received. Many thanks. Here's my code: ``` public boolean onTouchEvent(final MotionEvent event) { Intent intent = new Intent("com.google.zxing.client.android.SCAN"); intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE"); startActivityForResult(intent, 0); return true; } public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (requestCode == 0) { if (resultCode == RESULT_OK) { String contents = intent.getStringExtra("SCAN_RESULT"); String format = intent.getStringExtra("SCAN_RESULT_FORMAT"); // Handle successful scan String s = "http://www.google.com/search?q="; s += contents; Intent myIntent1 = new Intent(Intent.ACTION_VIEW, Uri.parse(s)); startActivity(myIntent1); } else if (resultCode == RESULT_CANCELED) { // Handle cancel } } } } ```
2012/06/13
[ "https://Stackoverflow.com/questions/11015807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/769506/" ]
Here's the full answer to my own question, hope this helps someone: Go [here](http://code.google.com/p/zxing/source/browse/trunk/android-integration/src/com/google/zxing/integration/android/IntentIntegrator.java?r=860) and copy the whole IntentIntegrator class, add it to your app; also go [here](http://code.google.com/p/zxing/source/browse/trunk/android-integration/src/com/google/zxing/integration/android/IntentResult.java?r=1273) and copy the IntentResult class to your app. Now add this to your activity (or trigger the scan by a button / whatever): ``` public boolean onTouchEvent(final MotionEvent event) { IntentIntegrator integrator = new IntentIntegrator(this); integrator.initiateScan(); return true; } public void onActivityResult(int requestCode, int resultCode, Intent intent) { IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); if (scanResult != null) { // handle scan result String s = "http://www.google.com/search?q="; s += scanResult.getContents(); Intent myIntent1 = new Intent(Intent.ACTION_VIEW, Uri.parse(s)); startActivity(myIntent1); } // else continue with any other code you need in the method //... } ``` It would have been great to just call the services provided by the Barcode scanner app and not copy and paste chunks of code into your own app but this seems to be the recommended way :(
Add finishActivity(requestCode); at the end of onActivityResult() method. Try this: Replace your first 2 lines in onTouch with the below code. It seems the issue is while scanning codes other than QR. Please remove the scan filter and check once. Intent intent = new Intent("com.google.zxing.client.android.SCAN"); intent.addFlags(Intent.FLAG\_ACTIVITY\_CLEAR\_WHEN\_TASK\_RESET);
11,015,807
I am successfully using zxing to scan codes, by calling the installed barcode reader's intent, but when it beeps and indicates a good scan I expect the zxing activity would return control so I can process the result, but it sits there and tries to scan again. I have to press the back button and *then* it returns and I can do the next step. Is there some obvious flag I'm missing when I call the scanner? Any advice gratefully received. Many thanks. Here's my code: ``` public boolean onTouchEvent(final MotionEvent event) { Intent intent = new Intent("com.google.zxing.client.android.SCAN"); intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE"); startActivityForResult(intent, 0); return true; } public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (requestCode == 0) { if (resultCode == RESULT_OK) { String contents = intent.getStringExtra("SCAN_RESULT"); String format = intent.getStringExtra("SCAN_RESULT_FORMAT"); // Handle successful scan String s = "http://www.google.com/search?q="; s += contents; Intent myIntent1 = new Intent(Intent.ACTION_VIEW, Uri.parse(s)); startActivity(myIntent1); } else if (resultCode == RESULT_CANCELED) { // Handle cancel } } } } ```
2012/06/13
[ "https://Stackoverflow.com/questions/11015807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/769506/" ]
Add finishActivity(requestCode); at the end of onActivityResult() method. Try this: Replace your first 2 lines in onTouch with the below code. It seems the issue is while scanning codes other than QR. Please remove the scan filter and check once. Intent intent = new Intent("com.google.zxing.client.android.SCAN"); intent.addFlags(Intent.FLAG\_ACTIVITY\_CLEAR\_WHEN\_TASK\_RESET);
Here is the solution that I am using. It is working fine for me. ``` Intent intent = new Intent(SelectOptionActivity.this, CaptureActivity.class); intent.putExtra("SCAN_MODE", "ONE_D_MODE"); intent.putExtra("SCAN_FORMATS", "CODE_39,CODE_93,CODE_128,DATA_MATRIX,ITF,CODABAR,EAN_13,EAN_8,UPC_A,QR_CODE"); intent.setAction(Intents.Scan.ACTION); startActivityForResult(intent, 1); public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == 1 && resultCode == RESULT_OK) { final String contents = intent.getStringExtra(Intents.Scan.RESULT); final String formatName = intent.getStringExtra(Intents.Scan.RESULT_FORMAT); } } ```
11,015,807
I am successfully using zxing to scan codes, by calling the installed barcode reader's intent, but when it beeps and indicates a good scan I expect the zxing activity would return control so I can process the result, but it sits there and tries to scan again. I have to press the back button and *then* it returns and I can do the next step. Is there some obvious flag I'm missing when I call the scanner? Any advice gratefully received. Many thanks. Here's my code: ``` public boolean onTouchEvent(final MotionEvent event) { Intent intent = new Intent("com.google.zxing.client.android.SCAN"); intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE"); startActivityForResult(intent, 0); return true; } public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (requestCode == 0) { if (resultCode == RESULT_OK) { String contents = intent.getStringExtra("SCAN_RESULT"); String format = intent.getStringExtra("SCAN_RESULT_FORMAT"); // Handle successful scan String s = "http://www.google.com/search?q="; s += contents; Intent myIntent1 = new Intent(Intent.ACTION_VIEW, Uri.parse(s)); startActivity(myIntent1); } else if (resultCode == RESULT_CANCELED) { // Handle cancel } } } } ```
2012/06/13
[ "https://Stackoverflow.com/questions/11015807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/769506/" ]
Why not use the provided `IntentIntegrator` class? This is the only approach mentioned in the project docs, did you have a look at those? <https://github.com/zxing/zxing/wiki/Scanning-Via-Intent> I created it to wrap up these details of sending and parsing the Intent, so you don't make typos. For example, there's no such thing as extra "com.google.zxing.client.android.SCAN.SCAN\_MODE".
Here's the full answer to my own question, hope this helps someone: Go [here](http://code.google.com/p/zxing/source/browse/trunk/android-integration/src/com/google/zxing/integration/android/IntentIntegrator.java?r=860) and copy the whole IntentIntegrator class, add it to your app; also go [here](http://code.google.com/p/zxing/source/browse/trunk/android-integration/src/com/google/zxing/integration/android/IntentResult.java?r=1273) and copy the IntentResult class to your app. Now add this to your activity (or trigger the scan by a button / whatever): ``` public boolean onTouchEvent(final MotionEvent event) { IntentIntegrator integrator = new IntentIntegrator(this); integrator.initiateScan(); return true; } public void onActivityResult(int requestCode, int resultCode, Intent intent) { IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); if (scanResult != null) { // handle scan result String s = "http://www.google.com/search?q="; s += scanResult.getContents(); Intent myIntent1 = new Intent(Intent.ACTION_VIEW, Uri.parse(s)); startActivity(myIntent1); } // else continue with any other code you need in the method //... } ``` It would have been great to just call the services provided by the Barcode scanner app and not copy and paste chunks of code into your own app but this seems to be the recommended way :(
11,015,807
I am successfully using zxing to scan codes, by calling the installed barcode reader's intent, but when it beeps and indicates a good scan I expect the zxing activity would return control so I can process the result, but it sits there and tries to scan again. I have to press the back button and *then* it returns and I can do the next step. Is there some obvious flag I'm missing when I call the scanner? Any advice gratefully received. Many thanks. Here's my code: ``` public boolean onTouchEvent(final MotionEvent event) { Intent intent = new Intent("com.google.zxing.client.android.SCAN"); intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE"); startActivityForResult(intent, 0); return true; } public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (requestCode == 0) { if (resultCode == RESULT_OK) { String contents = intent.getStringExtra("SCAN_RESULT"); String format = intent.getStringExtra("SCAN_RESULT_FORMAT"); // Handle successful scan String s = "http://www.google.com/search?q="; s += contents; Intent myIntent1 = new Intent(Intent.ACTION_VIEW, Uri.parse(s)); startActivity(myIntent1); } else if (resultCode == RESULT_CANCELED) { // Handle cancel } } } } ```
2012/06/13
[ "https://Stackoverflow.com/questions/11015807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/769506/" ]
Why not use the provided `IntentIntegrator` class? This is the only approach mentioned in the project docs, did you have a look at those? <https://github.com/zxing/zxing/wiki/Scanning-Via-Intent> I created it to wrap up these details of sending and parsing the Intent, so you don't make typos. For example, there's no such thing as extra "com.google.zxing.client.android.SCAN.SCAN\_MODE".
I was having the same issue so I tried using the IntentIntegrator class as recommended by Sean Owen. I still had the problem until I realized this was only happening when trying to scan a barcode in portrait (most frequently on phones). It turns out that the orientation change from portrait to landscape causes the double scan. I resolved this by adding `android:configChanges="orientation|keyboardHidden|screenSize"` to the activity in my manifest. You probably only need the orientation one, but that is untested. For any users experiencing this issue when creating an Adobe AIR Native Extension, be sure to add that line not only to your android project manifest, but also to your activity tag in your android manifest additions in your app.xml.
11,015,807
I am successfully using zxing to scan codes, by calling the installed barcode reader's intent, but when it beeps and indicates a good scan I expect the zxing activity would return control so I can process the result, but it sits there and tries to scan again. I have to press the back button and *then* it returns and I can do the next step. Is there some obvious flag I'm missing when I call the scanner? Any advice gratefully received. Many thanks. Here's my code: ``` public boolean onTouchEvent(final MotionEvent event) { Intent intent = new Intent("com.google.zxing.client.android.SCAN"); intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE"); startActivityForResult(intent, 0); return true; } public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (requestCode == 0) { if (resultCode == RESULT_OK) { String contents = intent.getStringExtra("SCAN_RESULT"); String format = intent.getStringExtra("SCAN_RESULT_FORMAT"); // Handle successful scan String s = "http://www.google.com/search?q="; s += contents; Intent myIntent1 = new Intent(Intent.ACTION_VIEW, Uri.parse(s)); startActivity(myIntent1); } else if (resultCode == RESULT_CANCELED) { // Handle cancel } } } } ```
2012/06/13
[ "https://Stackoverflow.com/questions/11015807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/769506/" ]
Why not use the provided `IntentIntegrator` class? This is the only approach mentioned in the project docs, did you have a look at those? <https://github.com/zxing/zxing/wiki/Scanning-Via-Intent> I created it to wrap up these details of sending and parsing the Intent, so you don't make typos. For example, there's no such thing as extra "com.google.zxing.client.android.SCAN.SCAN\_MODE".
Here is the solution that I am using. It is working fine for me. ``` Intent intent = new Intent(SelectOptionActivity.this, CaptureActivity.class); intent.putExtra("SCAN_MODE", "ONE_D_MODE"); intent.putExtra("SCAN_FORMATS", "CODE_39,CODE_93,CODE_128,DATA_MATRIX,ITF,CODABAR,EAN_13,EAN_8,UPC_A,QR_CODE"); intent.setAction(Intents.Scan.ACTION); startActivityForResult(intent, 1); public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == 1 && resultCode == RESULT_OK) { final String contents = intent.getStringExtra(Intents.Scan.RESULT); final String formatName = intent.getStringExtra(Intents.Scan.RESULT_FORMAT); } } ```
11,015,807
I am successfully using zxing to scan codes, by calling the installed barcode reader's intent, but when it beeps and indicates a good scan I expect the zxing activity would return control so I can process the result, but it sits there and tries to scan again. I have to press the back button and *then* it returns and I can do the next step. Is there some obvious flag I'm missing when I call the scanner? Any advice gratefully received. Many thanks. Here's my code: ``` public boolean onTouchEvent(final MotionEvent event) { Intent intent = new Intent("com.google.zxing.client.android.SCAN"); intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE"); startActivityForResult(intent, 0); return true; } public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (requestCode == 0) { if (resultCode == RESULT_OK) { String contents = intent.getStringExtra("SCAN_RESULT"); String format = intent.getStringExtra("SCAN_RESULT_FORMAT"); // Handle successful scan String s = "http://www.google.com/search?q="; s += contents; Intent myIntent1 = new Intent(Intent.ACTION_VIEW, Uri.parse(s)); startActivity(myIntent1); } else if (resultCode == RESULT_CANCELED) { // Handle cancel } } } } ```
2012/06/13
[ "https://Stackoverflow.com/questions/11015807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/769506/" ]
Here's the full answer to my own question, hope this helps someone: Go [here](http://code.google.com/p/zxing/source/browse/trunk/android-integration/src/com/google/zxing/integration/android/IntentIntegrator.java?r=860) and copy the whole IntentIntegrator class, add it to your app; also go [here](http://code.google.com/p/zxing/source/browse/trunk/android-integration/src/com/google/zxing/integration/android/IntentResult.java?r=1273) and copy the IntentResult class to your app. Now add this to your activity (or trigger the scan by a button / whatever): ``` public boolean onTouchEvent(final MotionEvent event) { IntentIntegrator integrator = new IntentIntegrator(this); integrator.initiateScan(); return true; } public void onActivityResult(int requestCode, int resultCode, Intent intent) { IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); if (scanResult != null) { // handle scan result String s = "http://www.google.com/search?q="; s += scanResult.getContents(); Intent myIntent1 = new Intent(Intent.ACTION_VIEW, Uri.parse(s)); startActivity(myIntent1); } // else continue with any other code you need in the method //... } ``` It would have been great to just call the services provided by the Barcode scanner app and not copy and paste chunks of code into your own app but this seems to be the recommended way :(
I was having the same issue so I tried using the IntentIntegrator class as recommended by Sean Owen. I still had the problem until I realized this was only happening when trying to scan a barcode in portrait (most frequently on phones). It turns out that the orientation change from portrait to landscape causes the double scan. I resolved this by adding `android:configChanges="orientation|keyboardHidden|screenSize"` to the activity in my manifest. You probably only need the orientation one, but that is untested. For any users experiencing this issue when creating an Adobe AIR Native Extension, be sure to add that line not only to your android project manifest, but also to your activity tag in your android manifest additions in your app.xml.
11,015,807
I am successfully using zxing to scan codes, by calling the installed barcode reader's intent, but when it beeps and indicates a good scan I expect the zxing activity would return control so I can process the result, but it sits there and tries to scan again. I have to press the back button and *then* it returns and I can do the next step. Is there some obvious flag I'm missing when I call the scanner? Any advice gratefully received. Many thanks. Here's my code: ``` public boolean onTouchEvent(final MotionEvent event) { Intent intent = new Intent("com.google.zxing.client.android.SCAN"); intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE"); startActivityForResult(intent, 0); return true; } public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (requestCode == 0) { if (resultCode == RESULT_OK) { String contents = intent.getStringExtra("SCAN_RESULT"); String format = intent.getStringExtra("SCAN_RESULT_FORMAT"); // Handle successful scan String s = "http://www.google.com/search?q="; s += contents; Intent myIntent1 = new Intent(Intent.ACTION_VIEW, Uri.parse(s)); startActivity(myIntent1); } else if (resultCode == RESULT_CANCELED) { // Handle cancel } } } } ```
2012/06/13
[ "https://Stackoverflow.com/questions/11015807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/769506/" ]
Here's the full answer to my own question, hope this helps someone: Go [here](http://code.google.com/p/zxing/source/browse/trunk/android-integration/src/com/google/zxing/integration/android/IntentIntegrator.java?r=860) and copy the whole IntentIntegrator class, add it to your app; also go [here](http://code.google.com/p/zxing/source/browse/trunk/android-integration/src/com/google/zxing/integration/android/IntentResult.java?r=1273) and copy the IntentResult class to your app. Now add this to your activity (or trigger the scan by a button / whatever): ``` public boolean onTouchEvent(final MotionEvent event) { IntentIntegrator integrator = new IntentIntegrator(this); integrator.initiateScan(); return true; } public void onActivityResult(int requestCode, int resultCode, Intent intent) { IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); if (scanResult != null) { // handle scan result String s = "http://www.google.com/search?q="; s += scanResult.getContents(); Intent myIntent1 = new Intent(Intent.ACTION_VIEW, Uri.parse(s)); startActivity(myIntent1); } // else continue with any other code you need in the method //... } ``` It would have been great to just call the services provided by the Barcode scanner app and not copy and paste chunks of code into your own app but this seems to be the recommended way :(
Here is the solution that I am using. It is working fine for me. ``` Intent intent = new Intent(SelectOptionActivity.this, CaptureActivity.class); intent.putExtra("SCAN_MODE", "ONE_D_MODE"); intent.putExtra("SCAN_FORMATS", "CODE_39,CODE_93,CODE_128,DATA_MATRIX,ITF,CODABAR,EAN_13,EAN_8,UPC_A,QR_CODE"); intent.setAction(Intents.Scan.ACTION); startActivityForResult(intent, 1); public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == 1 && resultCode == RESULT_OK) { final String contents = intent.getStringExtra(Intents.Scan.RESULT); final String formatName = intent.getStringExtra(Intents.Scan.RESULT_FORMAT); } } ```
11,015,807
I am successfully using zxing to scan codes, by calling the installed barcode reader's intent, but when it beeps and indicates a good scan I expect the zxing activity would return control so I can process the result, but it sits there and tries to scan again. I have to press the back button and *then* it returns and I can do the next step. Is there some obvious flag I'm missing when I call the scanner? Any advice gratefully received. Many thanks. Here's my code: ``` public boolean onTouchEvent(final MotionEvent event) { Intent intent = new Intent("com.google.zxing.client.android.SCAN"); intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE"); startActivityForResult(intent, 0); return true; } public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (requestCode == 0) { if (resultCode == RESULT_OK) { String contents = intent.getStringExtra("SCAN_RESULT"); String format = intent.getStringExtra("SCAN_RESULT_FORMAT"); // Handle successful scan String s = "http://www.google.com/search?q="; s += contents; Intent myIntent1 = new Intent(Intent.ACTION_VIEW, Uri.parse(s)); startActivity(myIntent1); } else if (resultCode == RESULT_CANCELED) { // Handle cancel } } } } ```
2012/06/13
[ "https://Stackoverflow.com/questions/11015807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/769506/" ]
I was having the same issue so I tried using the IntentIntegrator class as recommended by Sean Owen. I still had the problem until I realized this was only happening when trying to scan a barcode in portrait (most frequently on phones). It turns out that the orientation change from portrait to landscape causes the double scan. I resolved this by adding `android:configChanges="orientation|keyboardHidden|screenSize"` to the activity in my manifest. You probably only need the orientation one, but that is untested. For any users experiencing this issue when creating an Adobe AIR Native Extension, be sure to add that line not only to your android project manifest, but also to your activity tag in your android manifest additions in your app.xml.
Here is the solution that I am using. It is working fine for me. ``` Intent intent = new Intent(SelectOptionActivity.this, CaptureActivity.class); intent.putExtra("SCAN_MODE", "ONE_D_MODE"); intent.putExtra("SCAN_FORMATS", "CODE_39,CODE_93,CODE_128,DATA_MATRIX,ITF,CODABAR,EAN_13,EAN_8,UPC_A,QR_CODE"); intent.setAction(Intents.Scan.ACTION); startActivityForResult(intent, 1); public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == 1 && resultCode == RESULT_OK) { final String contents = intent.getStringExtra(Intents.Scan.RESULT); final String formatName = intent.getStringExtra(Intents.Scan.RESULT_FORMAT); } } ```
8,580,656
I have an auinotebook, is there anyway to get a list of all pages in the notebook? When the user selects an action from a list, a new page is added to the notebook. If they select that action again, then the page should not be added again (instead, that page will be selected for them). I can't see to figure out how to do this?? Thanks!
2011/12/20
[ "https://Stackoverflow.com/questions/8580656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/563299/" ]
Assuming you are using wx.lib.agw.aui.AuiNotebook: ``` import wx.lib.agw.aui as aui class MyNotebook(aui.AuiNotebook): def __getitem__(self, index): ''' More pythonic way to get a specific page, also useful for iterating over all pages, e.g: for page in notebook: ... ''' if index < self.GetPageCount(): return self.GetPage(index) else: raise IndexError ``` Now you can iterate over the pages of the notebook: ``` notebook = MyNotebook(parent) notebook.AddPage(someWindow, "page 1") notebook.AddPage(someOtherWindow, "page 2") for page in notebook: ... ```
You don't mention which AuiNotebook you're using. Is it the one that comes with wx.aui or wx.lib.agw.aui? Either way, I would think you could use GetChildren() to get a list of the notebook's panels and iterate through those as necessary. There's also a GetPageCount that you might be able to use in conjunction with GetPageInfo and GetPageText (these last three methods are in the agw version...not sure if they're included in the other). See the documentation for more information: <http://xoomer.virgilio.it/infinity77/AGW_Docs/aui.auibook.AuiNotebook.html#aui-auibook-auinotebook> Or you could cross-post to the wxPython user's list.
478,060
We all have elaborative discussion in physics about classical mechanics as well as interaction of particles through forces and certain laws which all particles obey. I want to ask,Does a particle exert a force on itself? **EDIT** Thanks for the respectful answers and comments.I edited this question in order to make it more elaborated. I just want to convey that I assumed the particle to be a standard model of point mass in classical mechanics. As I don't know why there is a minimum requirement of two particles to interact with fundamental forces of nature,in the similar manner I wanted to ask does a particle exerts a force on itself?
2019/05/05
[ "https://physics.stackexchange.com/questions/478060", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/230533/" ]
This question is never addressed by teachers, altough students start asking it more and more every year (surprisingly). Here are two possible arguments. 1. A particle is meant to have 0 volume. Maybe you're used to exert a force on yourself, but you are an extended body. Particles are points in space. I find it quite hard to exert a force on the same point. Your stating that the sender is the same as the receiver. It's like saying that one point is gaining momentum from itself! Because forces are a gain in momentum, after all. So how can we expect that some point increases its momentum alone? That violates the conservation of momentum principle. 2. A visual example (because this question usually arises in Electromagnetism with Coulomb's law): $$\vec{F}=K \frac{Qq}{r^2} \hat{r}$$ If $r=0$, the force is not defined, what's more, the vector $\hat{r}$ doesn't even exist. How could such force "know" where to point to? A point is spherically symmetric. What "arrow" (vector) would the force follow? If all directions are equivalent...
This exact question is considered at the end of Jackson's (somewhat infamous) *Classical Electrodynamics*. I think it would be appropriate to simply quote the relevant passage: > > In the preceding chapters the problems of electrodynamics have been > divided into two classes: one in which the sources of charge and > current are specified and the resulting electromagnetic fields are > calculated, and the other in which the external electromagnetic fields > are specified and the motions of charged particles or currents are > calculated... > > > It is evident that this manner of handling problems in > electrodynamics can be of only approximate validity. The motion of > charged particles in external force fields necessarily involves the > emission of radiation whenever the charges are accelerated. The > emitted radiation carries off energy, momentum, and angular momentum > and so must influence the subsequent motion of the charged particles. > Consequently the motion of the sources of radiation is determined, in > part, by the manner of emission of the radiation. A correct treatment > must include the reaction of the radiation on the motion of the > sources. > > > Why is it that we have taken so long in our discussion of > electrodynamics to face this fact? Why is it that many answers > calculated in an apparently erroneous way agree so well with > experiment? A partial answer to the first question lies in the second. > There are very many problems in electrodynamics that can be put with > negligible error into one of the two categories described in the first > paragraph. Hence it is worthwhile discussing them without the > added and unnecessary complication of including reaction effects. The > remaining answer to the first question is that a completely > satisfactory classical treatment of the reactive effects of radiation > does not exist. The difficulties presented by this problem touch one > of the most fundamental aspects of physics, the nature of an > elementary particle. Although partial solutions, workable within > limited areas, can be given, the basic problem remains unsolved. > > > There are ways to try to handle these self-interactions in the classical context which he discusses in this chapter, i.e. the Abraham-Lorentz force, but it is not fully satisfactory. However, a naive answer to the question is that really particles are excitations of fields, classical mechanics is simply a certain limit of quantum field theory, and therefore these self-interactions should be considered within that context. This is also not entirely satisfactory, as in quantum field theory it is assumed that the *fields* interact with themselves, and this interaction is treated only perturbatively. Ultimately there is no universally-accepted, non-perturbative description of what these interactions really are, though string theorists might disagree with me there.
478,060
We all have elaborative discussion in physics about classical mechanics as well as interaction of particles through forces and certain laws which all particles obey. I want to ask,Does a particle exert a force on itself? **EDIT** Thanks for the respectful answers and comments.I edited this question in order to make it more elaborated. I just want to convey that I assumed the particle to be a standard model of point mass in classical mechanics. As I don't know why there is a minimum requirement of two particles to interact with fundamental forces of nature,in the similar manner I wanted to ask does a particle exerts a force on itself?
2019/05/05
[ "https://physics.stackexchange.com/questions/478060", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/230533/" ]
This exact question is considered at the end of Jackson's (somewhat infamous) *Classical Electrodynamics*. I think it would be appropriate to simply quote the relevant passage: > > In the preceding chapters the problems of electrodynamics have been > divided into two classes: one in which the sources of charge and > current are specified and the resulting electromagnetic fields are > calculated, and the other in which the external electromagnetic fields > are specified and the motions of charged particles or currents are > calculated... > > > It is evident that this manner of handling problems in > electrodynamics can be of only approximate validity. The motion of > charged particles in external force fields necessarily involves the > emission of radiation whenever the charges are accelerated. The > emitted radiation carries off energy, momentum, and angular momentum > and so must influence the subsequent motion of the charged particles. > Consequently the motion of the sources of radiation is determined, in > part, by the manner of emission of the radiation. A correct treatment > must include the reaction of the radiation on the motion of the > sources. > > > Why is it that we have taken so long in our discussion of > electrodynamics to face this fact? Why is it that many answers > calculated in an apparently erroneous way agree so well with > experiment? A partial answer to the first question lies in the second. > There are very many problems in electrodynamics that can be put with > negligible error into one of the two categories described in the first > paragraph. Hence it is worthwhile discussing them without the > added and unnecessary complication of including reaction effects. The > remaining answer to the first question is that a completely > satisfactory classical treatment of the reactive effects of radiation > does not exist. The difficulties presented by this problem touch one > of the most fundamental aspects of physics, the nature of an > elementary particle. Although partial solutions, workable within > limited areas, can be given, the basic problem remains unsolved. > > > There are ways to try to handle these self-interactions in the classical context which he discusses in this chapter, i.e. the Abraham-Lorentz force, but it is not fully satisfactory. However, a naive answer to the question is that really particles are excitations of fields, classical mechanics is simply a certain limit of quantum field theory, and therefore these self-interactions should be considered within that context. This is also not entirely satisfactory, as in quantum field theory it is assumed that the *fields* interact with themselves, and this interaction is treated only perturbatively. Ultimately there is no universally-accepted, non-perturbative description of what these interactions really are, though string theorists might disagree with me there.
> > The difficulties presented by this problem touch one of the most fundamental aspects of physics, the nature of the elementary particle. Although partial solutions, workable within limited areas, can be given, the basic problem remains unsolved. One might hope that the transition from classical to quantum-mechanical treatments would remove the difficulties. While there is still hope that this may eventually occur, the present quantum-mechanical discussions are beset with even more elaborate troubles than the classical ones. It is one of the triumphs of comparatively recent years (~ 1948–1950) that the concepts of Lorentz covariance and gauge invariance were exploited sufficiently cleverly to circumvent these difficulties in quantum electrodynamics and so allow the calculation of very small radiative effects to extremely high precision, in full agreement with experiment. From a fundamental point of view, however, the difficulties remain. > > > John David Jackson, Classical Electrodynamics.
478,060
We all have elaborative discussion in physics about classical mechanics as well as interaction of particles through forces and certain laws which all particles obey. I want to ask,Does a particle exert a force on itself? **EDIT** Thanks for the respectful answers and comments.I edited this question in order to make it more elaborated. I just want to convey that I assumed the particle to be a standard model of point mass in classical mechanics. As I don't know why there is a minimum requirement of two particles to interact with fundamental forces of nature,in the similar manner I wanted to ask does a particle exerts a force on itself?
2019/05/05
[ "https://physics.stackexchange.com/questions/478060", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/230533/" ]
This is one of those terribly simple questions which is also astonishingly insightful and surprisingly a big deal in physics. I'd like to commend you for the question! The classical mechanics answer is "because we say it doesn't." One of the peculiarities about science is that it doesn't tell you the *true* answer, in the philosophical sense. Science provides you with models which have a historical track record of being very good at letting you predict future outcomes. Particles do not apply forces to themselves in classical mechanics because the classical models which were effective for predicting the state of systems did not have them apply forces. Now one could provide a *justification* in classical mechanics. Newton's laws state that every action has an equal and opposite reaction. If I push on my table with 50N of force, it pushes back on me with 50N of force in the opposite direction. If you think about it, a particle which pushes on itself with some force is then pushed back by itself in the opposite direction with an equal force. This is like you pushing your hands together really hard. You apply a lot of force, but your hands don't move anywhere because you're just pushing on yourself. Every time you push, you push back. Now it gets more interesting in quantum mechanics. Without getting into the details, in quantum mechanics, we find that particles *do indeed* interact with themselves. And they have to interact with their own interactions, and so on and so forth. So once we get down to more fundamental levels, we actually *do* see meaningful self-interactions of particles. We just don't see them in classical mechanics. Why? Well, going back to the idea of science creating models of the universe, self-interactions are *messy*. QM has to do all sorts of clever integration and normalization tricks to make them sane. In classical mechanics, we didn't need self-interactions to properly model how systems evolve over time, so we didn't include any of that complexity. In QM, we found that the models without self-interaction simply weren't effective at predicting what we see. We were forced to bring in self-interaction terms to explain what we saw. In fact, these self-interactions turn out to be a *real* bugger. You may have heard of "quantum gravity." One of the things quantum mechanics does not explain very well is gravity. Gravity on these scales is typically too small to measure directly, so we can only infer what it should do. On the other end of the spectrum, general relativity is substantially focused on modeling how gravity works on a universal scale (where objects are big enough that measuring gravitational effects is relatively easy). In general relativity, we see the concept of gravity as distortions in space time, creating all sorts of wonderful visual images of objects resting on rubber sheets, distorting the fabric it rests on. Unfortunately, these distortions cause a huge problem for quantum mechanics. The normalization techniques they use to deal with all of those self-interaction terms don't work in the distorted spaces that general relativity predicts. The numbers balloon and explode off towards infinity. We predict infinite energy for all particles, and yet there's no reason to believe that is accurate. We simply cannot seem to combine the distortion of space time modeled by Einstein's relativity and the self-interactions of particles in quantum mechanics. So you ask a very simple question. It's well phrased. In fact, it is so well phrased that I can conclude by saying the answer to your question is one of the great questions physics is searching for to this very day. Entire teams of scientists are trying to tease apart this question of self-interaction and they search for models of gravity which function correctly in the quantum realm!
Interesting question. The majority of the present answers seems to limit the possibility of self-interaction to the case of charges, referring in a direct or indirect way to the radiation reaction force. References to self-interaction in QFT, although interesting, seem to go beyond the limits of the original question, which is explicitly in the realm of classical mechanics and also implicitly, taking into account that the concept of force is pivotal in classical mechanics, but not in QM. Without any claim to write the ultimate answer, I would like to add a few thoughts from a more general perspective, entirely based on classical mechanics. 1. radiation reaction, or similar mechanisms, are not truly self interaction forces. They can be seen as interaction of a particle with itself mediated by the interaction with a different system which allows a feedback mechanism. Such a feedback cannot be instantaneous, but this is not a problem: retarded potentials (and therefore retarded forces) are almost obvious in the case of electromagnetic (EM) interaction. But also without EM fields, retarded self interaction may be mediated by the presence of a continuum fluid. However, the key point is that in all those cases, the self interaction is an effect of the existence of a second physical system. Integrating out such second system, results in an effective self-interaction. 2. A real self interaction should correspond to a force depending only on the state variables (position and velocity) and characteristic properties of just one particle. This excludes typical one-body interactions. For example, even though a viscous force $-\gamma {\bf v}$ apparently depends only on the velocity of one particle, we know that the meaning of that velocity is the relative velocity of the particle with respect to the surrounding fluid. Moreover the friction coefficient $\gamma$ depends on quantities characterizing the surrounding fluid. 3. We arrive to the key point: a real self-interaction would imply a force acting on one *isolated* particle. However, the presence of such self-interaction would undermine at the basis the whole Newtonian mechanics, because it would imply that **an isolated particle would not move in a straight line with constant speed.** Or, said in a different way, we would not have the possibility of defining inertial systems. Therefore, my partial conclusion is that a real self-interaction is excluded by the principles of Newtonian mechanics. On the experimental side, such non-Newtonian behavior has never been observed, at the best of my knowledge.
478,060
We all have elaborative discussion in physics about classical mechanics as well as interaction of particles through forces and certain laws which all particles obey. I want to ask,Does a particle exert a force on itself? **EDIT** Thanks for the respectful answers and comments.I edited this question in order to make it more elaborated. I just want to convey that I assumed the particle to be a standard model of point mass in classical mechanics. As I don't know why there is a minimum requirement of two particles to interact with fundamental forces of nature,in the similar manner I wanted to ask does a particle exerts a force on itself?
2019/05/05
[ "https://physics.stackexchange.com/questions/478060", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/230533/" ]
This exact question is considered at the end of Jackson's (somewhat infamous) *Classical Electrodynamics*. I think it would be appropriate to simply quote the relevant passage: > > In the preceding chapters the problems of electrodynamics have been > divided into two classes: one in which the sources of charge and > current are specified and the resulting electromagnetic fields are > calculated, and the other in which the external electromagnetic fields > are specified and the motions of charged particles or currents are > calculated... > > > It is evident that this manner of handling problems in > electrodynamics can be of only approximate validity. The motion of > charged particles in external force fields necessarily involves the > emission of radiation whenever the charges are accelerated. The > emitted radiation carries off energy, momentum, and angular momentum > and so must influence the subsequent motion of the charged particles. > Consequently the motion of the sources of radiation is determined, in > part, by the manner of emission of the radiation. A correct treatment > must include the reaction of the radiation on the motion of the > sources. > > > Why is it that we have taken so long in our discussion of > electrodynamics to face this fact? Why is it that many answers > calculated in an apparently erroneous way agree so well with > experiment? A partial answer to the first question lies in the second. > There are very many problems in electrodynamics that can be put with > negligible error into one of the two categories described in the first > paragraph. Hence it is worthwhile discussing them without the > added and unnecessary complication of including reaction effects. The > remaining answer to the first question is that a completely > satisfactory classical treatment of the reactive effects of radiation > does not exist. The difficulties presented by this problem touch one > of the most fundamental aspects of physics, the nature of an > elementary particle. Although partial solutions, workable within > limited areas, can be given, the basic problem remains unsolved. > > > There are ways to try to handle these self-interactions in the classical context which he discusses in this chapter, i.e. the Abraham-Lorentz force, but it is not fully satisfactory. However, a naive answer to the question is that really particles are excitations of fields, classical mechanics is simply a certain limit of quantum field theory, and therefore these self-interactions should be considered within that context. This is also not entirely satisfactory, as in quantum field theory it is assumed that the *fields* interact with themselves, and this interaction is treated only perturbatively. Ultimately there is no universally-accepted, non-perturbative description of what these interactions really are, though string theorists might disagree with me there.
This answer may a bit technical but the clearest argument that there is always self interaction, that is, a force of a particle on itself comes from lagrangian formalism. If we calculate the EM potential of a charge then the source of the potential, the charge, is given by $q=dL/dV$. This means that $L$ must contain a self interaction term $qV$, which leads to a self force. This is true in classical and in quantum electrodynamics. If this term were absent the charge would have no field at all! In classical ED the self force is ignored, because attempts to describe have so far been problematic. In QED it gives rise to infinities. Renormalisation techniques in QED are successfully used to tame the infinities and extract physically meaningful, even very accurate effects so called radiation effects originating from the self interaction.
478,060
We all have elaborative discussion in physics about classical mechanics as well as interaction of particles through forces and certain laws which all particles obey. I want to ask,Does a particle exert a force on itself? **EDIT** Thanks for the respectful answers and comments.I edited this question in order to make it more elaborated. I just want to convey that I assumed the particle to be a standard model of point mass in classical mechanics. As I don't know why there is a minimum requirement of two particles to interact with fundamental forces of nature,in the similar manner I wanted to ask does a particle exerts a force on itself?
2019/05/05
[ "https://physics.stackexchange.com/questions/478060", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/230533/" ]
This exact question is considered at the end of Jackson's (somewhat infamous) *Classical Electrodynamics*. I think it would be appropriate to simply quote the relevant passage: > > In the preceding chapters the problems of electrodynamics have been > divided into two classes: one in which the sources of charge and > current are specified and the resulting electromagnetic fields are > calculated, and the other in which the external electromagnetic fields > are specified and the motions of charged particles or currents are > calculated... > > > It is evident that this manner of handling problems in > electrodynamics can be of only approximate validity. The motion of > charged particles in external force fields necessarily involves the > emission of radiation whenever the charges are accelerated. The > emitted radiation carries off energy, momentum, and angular momentum > and so must influence the subsequent motion of the charged particles. > Consequently the motion of the sources of radiation is determined, in > part, by the manner of emission of the radiation. A correct treatment > must include the reaction of the radiation on the motion of the > sources. > > > Why is it that we have taken so long in our discussion of > electrodynamics to face this fact? Why is it that many answers > calculated in an apparently erroneous way agree so well with > experiment? A partial answer to the first question lies in the second. > There are very many problems in electrodynamics that can be put with > negligible error into one of the two categories described in the first > paragraph. Hence it is worthwhile discussing them without the > added and unnecessary complication of including reaction effects. The > remaining answer to the first question is that a completely > satisfactory classical treatment of the reactive effects of radiation > does not exist. The difficulties presented by this problem touch one > of the most fundamental aspects of physics, the nature of an > elementary particle. Although partial solutions, workable within > limited areas, can be given, the basic problem remains unsolved. > > > There are ways to try to handle these self-interactions in the classical context which he discusses in this chapter, i.e. the Abraham-Lorentz force, but it is not fully satisfactory. However, a naive answer to the question is that really particles are excitations of fields, classical mechanics is simply a certain limit of quantum field theory, and therefore these self-interactions should be considered within that context. This is also not entirely satisfactory, as in quantum field theory it is assumed that the *fields* interact with themselves, and this interaction is treated only perturbatively. Ultimately there is no universally-accepted, non-perturbative description of what these interactions really are, though string theorists might disagree with me there.
Interesting question. The majority of the present answers seems to limit the possibility of self-interaction to the case of charges, referring in a direct or indirect way to the radiation reaction force. References to self-interaction in QFT, although interesting, seem to go beyond the limits of the original question, which is explicitly in the realm of classical mechanics and also implicitly, taking into account that the concept of force is pivotal in classical mechanics, but not in QM. Without any claim to write the ultimate answer, I would like to add a few thoughts from a more general perspective, entirely based on classical mechanics. 1. radiation reaction, or similar mechanisms, are not truly self interaction forces. They can be seen as interaction of a particle with itself mediated by the interaction with a different system which allows a feedback mechanism. Such a feedback cannot be instantaneous, but this is not a problem: retarded potentials (and therefore retarded forces) are almost obvious in the case of electromagnetic (EM) interaction. But also without EM fields, retarded self interaction may be mediated by the presence of a continuum fluid. However, the key point is that in all those cases, the self interaction is an effect of the existence of a second physical system. Integrating out such second system, results in an effective self-interaction. 2. A real self interaction should correspond to a force depending only on the state variables (position and velocity) and characteristic properties of just one particle. This excludes typical one-body interactions. For example, even though a viscous force $-\gamma {\bf v}$ apparently depends only on the velocity of one particle, we know that the meaning of that velocity is the relative velocity of the particle with respect to the surrounding fluid. Moreover the friction coefficient $\gamma$ depends on quantities characterizing the surrounding fluid. 3. We arrive to the key point: a real self-interaction would imply a force acting on one *isolated* particle. However, the presence of such self-interaction would undermine at the basis the whole Newtonian mechanics, because it would imply that **an isolated particle would not move in a straight line with constant speed.** Or, said in a different way, we would not have the possibility of defining inertial systems. Therefore, my partial conclusion is that a real self-interaction is excluded by the principles of Newtonian mechanics. On the experimental side, such non-Newtonian behavior has never been observed, at the best of my knowledge.
478,060
We all have elaborative discussion in physics about classical mechanics as well as interaction of particles through forces and certain laws which all particles obey. I want to ask,Does a particle exert a force on itself? **EDIT** Thanks for the respectful answers and comments.I edited this question in order to make it more elaborated. I just want to convey that I assumed the particle to be a standard model of point mass in classical mechanics. As I don't know why there is a minimum requirement of two particles to interact with fundamental forces of nature,in the similar manner I wanted to ask does a particle exerts a force on itself?
2019/05/05
[ "https://physics.stackexchange.com/questions/478060", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/230533/" ]
Interesting question. The majority of the present answers seems to limit the possibility of self-interaction to the case of charges, referring in a direct or indirect way to the radiation reaction force. References to self-interaction in QFT, although interesting, seem to go beyond the limits of the original question, which is explicitly in the realm of classical mechanics and also implicitly, taking into account that the concept of force is pivotal in classical mechanics, but not in QM. Without any claim to write the ultimate answer, I would like to add a few thoughts from a more general perspective, entirely based on classical mechanics. 1. radiation reaction, or similar mechanisms, are not truly self interaction forces. They can be seen as interaction of a particle with itself mediated by the interaction with a different system which allows a feedback mechanism. Such a feedback cannot be instantaneous, but this is not a problem: retarded potentials (and therefore retarded forces) are almost obvious in the case of electromagnetic (EM) interaction. But also without EM fields, retarded self interaction may be mediated by the presence of a continuum fluid. However, the key point is that in all those cases, the self interaction is an effect of the existence of a second physical system. Integrating out such second system, results in an effective self-interaction. 2. A real self interaction should correspond to a force depending only on the state variables (position and velocity) and characteristic properties of just one particle. This excludes typical one-body interactions. For example, even though a viscous force $-\gamma {\bf v}$ apparently depends only on the velocity of one particle, we know that the meaning of that velocity is the relative velocity of the particle with respect to the surrounding fluid. Moreover the friction coefficient $\gamma$ depends on quantities characterizing the surrounding fluid. 3. We arrive to the key point: a real self-interaction would imply a force acting on one *isolated* particle. However, the presence of such self-interaction would undermine at the basis the whole Newtonian mechanics, because it would imply that **an isolated particle would not move in a straight line with constant speed.** Or, said in a different way, we would not have the possibility of defining inertial systems. Therefore, my partial conclusion is that a real self-interaction is excluded by the principles of Newtonian mechanics. On the experimental side, such non-Newtonian behavior has never been observed, at the best of my knowledge.
> > The difficulties presented by this problem touch one of the most fundamental aspects of physics, the nature of the elementary particle. Although partial solutions, workable within limited areas, can be given, the basic problem remains unsolved. One might hope that the transition from classical to quantum-mechanical treatments would remove the difficulties. While there is still hope that this may eventually occur, the present quantum-mechanical discussions are beset with even more elaborate troubles than the classical ones. It is one of the triumphs of comparatively recent years (~ 1948–1950) that the concepts of Lorentz covariance and gauge invariance were exploited sufficiently cleverly to circumvent these difficulties in quantum electrodynamics and so allow the calculation of very small radiative effects to extremely high precision, in full agreement with experiment. From a fundamental point of view, however, the difficulties remain. > > > John David Jackson, Classical Electrodynamics.
478,060
We all have elaborative discussion in physics about classical mechanics as well as interaction of particles through forces and certain laws which all particles obey. I want to ask,Does a particle exert a force on itself? **EDIT** Thanks for the respectful answers and comments.I edited this question in order to make it more elaborated. I just want to convey that I assumed the particle to be a standard model of point mass in classical mechanics. As I don't know why there is a minimum requirement of two particles to interact with fundamental forces of nature,in the similar manner I wanted to ask does a particle exerts a force on itself?
2019/05/05
[ "https://physics.stackexchange.com/questions/478060", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/230533/" ]
What even *is* a particle in classical mechanics? Particles do exist in the real world, but their discovery pretty much made the invention of quantum mechanics necessary. So to answer this question, you have to set up some straw man of a "classical mechanics particle" and then destroy that. For instance, we may pretend that atoms have the exact same properties as the bulk material, they're just for inexplicable reasons indivisible. At this point, we cannot say any more whether particles do or do not exert forces on themselves. The particle might exert a gravitational force on itself, compressing it every so slightly. We could not detect this force, because it would always be there and it would linearly add up with other forces. Instead, this force would show up as part of the physical properties of the material, in particular its density. And in classical mechanics, those properties are mostly treated as constants of nature.
This answer may a bit technical but the clearest argument that there is always self interaction, that is, a force of a particle on itself comes from lagrangian formalism. If we calculate the EM potential of a charge then the source of the potential, the charge, is given by $q=dL/dV$. This means that $L$ must contain a self interaction term $qV$, which leads to a self force. This is true in classical and in quantum electrodynamics. If this term were absent the charge would have no field at all! In classical ED the self force is ignored, because attempts to describe have so far been problematic. In QED it gives rise to infinities. Renormalisation techniques in QED are successfully used to tame the infinities and extract physically meaningful, even very accurate effects so called radiation effects originating from the self interaction.
478,060
We all have elaborative discussion in physics about classical mechanics as well as interaction of particles through forces and certain laws which all particles obey. I want to ask,Does a particle exert a force on itself? **EDIT** Thanks for the respectful answers and comments.I edited this question in order to make it more elaborated. I just want to convey that I assumed the particle to be a standard model of point mass in classical mechanics. As I don't know why there is a minimum requirement of two particles to interact with fundamental forces of nature,in the similar manner I wanted to ask does a particle exerts a force on itself?
2019/05/05
[ "https://physics.stackexchange.com/questions/478060", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/230533/" ]
Well a point particle is just an idealization that has spherical symmetry, and we can imagine that in reality we have some finite volume associated with the "point", in which the total charge is distributed. The argument, at least in electromagnetism, is that the spherical symmetry of the charge together with its own spherically symmetric field will lead to a cancellation when computing the total force of the field on the charge distribution. So we relax the idealization of a point particle and think of it as a little ball with radius $a$ and some uniform charge distribution: $\rho= \rho\_{o}$ for $r<{a}$, and $\rho=0$ otherwise. We first consider the $r<a$ region and draw a nice little Gaussian sphere of radius $r$ inside of the ball. We have: $$\int\_{} \vec{E}\cdot{d\vec{A}} =\dfrac{Q\_{enc}}{\epsilon\_{0}}$$ $$4\pi r^{2}E(r) = \frac{1}{\epsilon\_{0}}\frac{4}{3}\pi r^{3}\rho\_{0} \qquad , \qquad r<a$$ Now we say that the total charge in this ball is $q=\frac{4}{3}\pi r^{3}\rho\_{0}$, then we can take the previous line and do $$4\pi r^{2}E(r) = \frac{1}{\epsilon\_{0}}\frac{4}{3}\pi a^{3}\*\frac{r^{3}}{a^3}\rho\_{0}=\frac{q}{\epsilon\_0}\frac{r^{3}}{a^{3}}\rho\_0$$ or $$\vec{E}(r)=\frac{q}{4\pi\epsilon\_{0}}\frac{r}{a^{3}}\hat{r} \qquad,\qquad r<a$$ Outside the ball, we have the usual: $$\vec{E}(r)=\frac{q}{4\pi\epsilon\_{0}}\frac{1}{r^{2}}\hat{r} \qquad,\qquad r>a$$ So we see that even if the ball has a finite volume, it still *looks* like a point generating a spherically symmetric field if we're looking from the outside. This justifies our treatment of a point charge as a spherical distribution of charge instead (the point limit is just when $a$ goes to $0$). Now we've established that the field that this finite-sized ball generates is also spherically symmetric, with the origin taken to be the origin of the ball. Since we now have a spherically symmetric charge *distribution*, centered at the origin of a spherically symmetric field, then the force that charge distribution feels from its own field is now $$\vec{F}=\int \vec{E} \, dq =\int\_{sphere}\vec{E} \rho dV = \int\_{sphere} E(r)\hat{r}\rho dV$$ which will cancel due to spherical symmetry. I think this argument works in most cases where we have a spherically symmetric interaction (Coulomb, gravitational, etc).
This exact question is considered at the end of Jackson's (somewhat infamous) *Classical Electrodynamics*. I think it would be appropriate to simply quote the relevant passage: > > In the preceding chapters the problems of electrodynamics have been > divided into two classes: one in which the sources of charge and > current are specified and the resulting electromagnetic fields are > calculated, and the other in which the external electromagnetic fields > are specified and the motions of charged particles or currents are > calculated... > > > It is evident that this manner of handling problems in > electrodynamics can be of only approximate validity. The motion of > charged particles in external force fields necessarily involves the > emission of radiation whenever the charges are accelerated. The > emitted radiation carries off energy, momentum, and angular momentum > and so must influence the subsequent motion of the charged particles. > Consequently the motion of the sources of radiation is determined, in > part, by the manner of emission of the radiation. A correct treatment > must include the reaction of the radiation on the motion of the > sources. > > > Why is it that we have taken so long in our discussion of > electrodynamics to face this fact? Why is it that many answers > calculated in an apparently erroneous way agree so well with > experiment? A partial answer to the first question lies in the second. > There are very many problems in electrodynamics that can be put with > negligible error into one of the two categories described in the first > paragraph. Hence it is worthwhile discussing them without the > added and unnecessary complication of including reaction effects. The > remaining answer to the first question is that a completely > satisfactory classical treatment of the reactive effects of radiation > does not exist. The difficulties presented by this problem touch one > of the most fundamental aspects of physics, the nature of an > elementary particle. Although partial solutions, workable within > limited areas, can be given, the basic problem remains unsolved. > > > There are ways to try to handle these self-interactions in the classical context which he discusses in this chapter, i.e. the Abraham-Lorentz force, but it is not fully satisfactory. However, a naive answer to the question is that really particles are excitations of fields, classical mechanics is simply a certain limit of quantum field theory, and therefore these self-interactions should be considered within that context. This is also not entirely satisfactory, as in quantum field theory it is assumed that the *fields* interact with themselves, and this interaction is treated only perturbatively. Ultimately there is no universally-accepted, non-perturbative description of what these interactions really are, though string theorists might disagree with me there.
478,060
We all have elaborative discussion in physics about classical mechanics as well as interaction of particles through forces and certain laws which all particles obey. I want to ask,Does a particle exert a force on itself? **EDIT** Thanks for the respectful answers and comments.I edited this question in order to make it more elaborated. I just want to convey that I assumed the particle to be a standard model of point mass in classical mechanics. As I don't know why there is a minimum requirement of two particles to interact with fundamental forces of nature,in the similar manner I wanted to ask does a particle exerts a force on itself?
2019/05/05
[ "https://physics.stackexchange.com/questions/478060", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/230533/" ]
This question is never addressed by teachers, altough students start asking it more and more every year (surprisingly). Here are two possible arguments. 1. A particle is meant to have 0 volume. Maybe you're used to exert a force on yourself, but you are an extended body. Particles are points in space. I find it quite hard to exert a force on the same point. Your stating that the sender is the same as the receiver. It's like saying that one point is gaining momentum from itself! Because forces are a gain in momentum, after all. So how can we expect that some point increases its momentum alone? That violates the conservation of momentum principle. 2. A visual example (because this question usually arises in Electromagnetism with Coulomb's law): $$\vec{F}=K \frac{Qq}{r^2} \hat{r}$$ If $r=0$, the force is not defined, what's more, the vector $\hat{r}$ doesn't even exist. How could such force "know" where to point to? A point is spherically symmetric. What "arrow" (vector) would the force follow? If all directions are equivalent...
What even *is* a particle in classical mechanics? Particles do exist in the real world, but their discovery pretty much made the invention of quantum mechanics necessary. So to answer this question, you have to set up some straw man of a "classical mechanics particle" and then destroy that. For instance, we may pretend that atoms have the exact same properties as the bulk material, they're just for inexplicable reasons indivisible. At this point, we cannot say any more whether particles do or do not exert forces on themselves. The particle might exert a gravitational force on itself, compressing it every so slightly. We could not detect this force, because it would always be there and it would linearly add up with other forces. Instead, this force would show up as part of the physical properties of the material, in particular its density. And in classical mechanics, those properties are mostly treated as constants of nature.
478,060
We all have elaborative discussion in physics about classical mechanics as well as interaction of particles through forces and certain laws which all particles obey. I want to ask,Does a particle exert a force on itself? **EDIT** Thanks for the respectful answers and comments.I edited this question in order to make it more elaborated. I just want to convey that I assumed the particle to be a standard model of point mass in classical mechanics. As I don't know why there is a minimum requirement of two particles to interact with fundamental forces of nature,in the similar manner I wanted to ask does a particle exerts a force on itself?
2019/05/05
[ "https://physics.stackexchange.com/questions/478060", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/230533/" ]
This question is never addressed by teachers, altough students start asking it more and more every year (surprisingly). Here are two possible arguments. 1. A particle is meant to have 0 volume. Maybe you're used to exert a force on yourself, but you are an extended body. Particles are points in space. I find it quite hard to exert a force on the same point. Your stating that the sender is the same as the receiver. It's like saying that one point is gaining momentum from itself! Because forces are a gain in momentum, after all. So how can we expect that some point increases its momentum alone? That violates the conservation of momentum principle. 2. A visual example (because this question usually arises in Electromagnetism with Coulomb's law): $$\vec{F}=K \frac{Qq}{r^2} \hat{r}$$ If $r=0$, the force is not defined, what's more, the vector $\hat{r}$ doesn't even exist. How could such force "know" where to point to? A point is spherically symmetric. What "arrow" (vector) would the force follow? If all directions are equivalent...
> > The difficulties presented by this problem touch one of the most fundamental aspects of physics, the nature of the elementary particle. Although partial solutions, workable within limited areas, can be given, the basic problem remains unsolved. One might hope that the transition from classical to quantum-mechanical treatments would remove the difficulties. While there is still hope that this may eventually occur, the present quantum-mechanical discussions are beset with even more elaborate troubles than the classical ones. It is one of the triumphs of comparatively recent years (~ 1948–1950) that the concepts of Lorentz covariance and gauge invariance were exploited sufficiently cleverly to circumvent these difficulties in quantum electrodynamics and so allow the calculation of very small radiative effects to extremely high precision, in full agreement with experiment. From a fundamental point of view, however, the difficulties remain. > > > John David Jackson, Classical Electrodynamics.
53,003
My toddler dropped a toothbrush down a bathroom sink. Unfortunately, the stopper wasn't in the sink at the time. When looking down from above the sink, I believe the toothbrush is in the PVC section of the picture, and leaning against the side. The PVC is a larger diameter so even if I could reach the toothbrush from above, I'd need to pull it center before pulling up. How do I remove the toothbrush and get the sink functional again? ![Under the Sink](https://i.stack.imgur.com/OFIRn.jpg) ![Under the Sink with bottom of trap](https://i.stack.imgur.com/QM4Ku.jpg)
2014/11/17
[ "https://diy.stackexchange.com/questions/53003", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/7648/" ]
In my part of the world, PVC P-traps for sinks and basins are universally designed so that you can easily remove the U-bend from below without tools. ![enter image description here](https://i.stack.imgur.com/MU8FV.jpg) I wouldn't hesitate very long before undoing all the obvious nuts visible in your picture† and attempting to gain access to the U-bend. In some cases a strap-wrench may be useful, but usually those joints between PVC sections are sealed by a simple rubber ring and shouldn't have any kind of putty or sealant applied (which can make them hard to remove by hand) ![enter image description here](https://i.stack.imgur.com/otqZH.jpg) *† Obviously, except the one on the flexible tap connector(s)!*
Before you start taking things apart..... try this! Get a dowel and your glue gun. Dab hot glue onto tip of dowel, quickly put down drain onto toothbrush ( or whatever you've dropped down there) leave for a minute or 2 and pull dowel out!! Nothing to take apart! This probably would not work for a small item in the water but worth a try!!!
53,003
My toddler dropped a toothbrush down a bathroom sink. Unfortunately, the stopper wasn't in the sink at the time. When looking down from above the sink, I believe the toothbrush is in the PVC section of the picture, and leaning against the side. The PVC is a larger diameter so even if I could reach the toothbrush from above, I'd need to pull it center before pulling up. How do I remove the toothbrush and get the sink functional again? ![Under the Sink](https://i.stack.imgur.com/OFIRn.jpg) ![Under the Sink with bottom of trap](https://i.stack.imgur.com/QM4Ku.jpg)
2014/11/17
[ "https://diy.stackexchange.com/questions/53003", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/7648/" ]
You could try using a pick-up or claw tool to reach down in the drain to grab it and pull it out. Something like this [one at Amazon.com](http://rads.stackoverflow.com/amzn/click/B002RHP7TS). ![enter image description here](https://i.stack.imgur.com/xUBtP.jpg)
Before you start taking things apart..... try this! Get a dowel and your glue gun. Dab hot glue onto tip of dowel, quickly put down drain onto toothbrush ( or whatever you've dropped down there) leave for a minute or 2 and pull dowel out!! Nothing to take apart! This probably would not work for a small item in the water but worth a try!!!
39,407,605
I am building a website and wish to serve a video if the user is on a desktop device, and if on a mobile I am going to serve a gif. Does anyone have any guidance for best practices on this? Is the below code enough? When I test this on chrome it doesn't show the mobile gif, but perhaps something is incorrect here. Should I be using modernizr to cover browser/device inconsistencies I may not be aware of? Is there a `data-src` approach that I should be taking perhaps? ``` <div id="main"></div> <script type="text/javascript"> var main = document.getElementById('main'); //check if a mobile device if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) { main.innerHTML = '<img src="http://static1.squarespace.com/static/552a5cc4e4b059a56a050501/565f6b57e4b0d9b44ab87107/566024f5e4b0354e5b79dd24/1449141991793/NYCGifathon12.gif>"'; } else { main.innerHTML = '<video width="640" height="360" controls="" autoplay=""><source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/mp4"><source src="http://clips.vorwaerts-gmbh.de/VfE.webm" type="video/webm"><source src="http://clips.vorwaerts-gmbh.de/VfE.ogv" type="video/ogg"></video>'; } </script> ```
2016/09/09
[ "https://Stackoverflow.com/questions/39407605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Please do not test for a device, test for a screen size. ``` var windowWidth = $(window).width(); var maxDeviceWidth = 768; if (windowWidth > maxDeviceWidth) { //Server the desktop version //You can get the content with Ajax or load both and hide the other } else { //Load the mobile content - either with Ajax, or hide the desktop content } ``` I'd suggest that you just load content with Ajax based on the screen width. Make sure you also put this in ``` $(window).resize(); ``` To make sure you account for screens turning sideways.
Update: I've included dynamic insertion based on the `innerWidth` so this should be cool now, it includes a video on wide screens, and a gif on small ones. HTML: ``` <div class="wrapper"> <div id="video-container"> <video></video> </div> <div id="gif-container"> <img src="gif.gif"> </div> </div> ``` CSS: ``` #video-container { display: none; } #gif-container { display: block; } // Mobile first = win! @media screen and (min-width: 40em) { #video-container { display: block; } #gif-container { display: none; } } ``` JavaScript: ``` function videoOrImage() { console.log('hit') if(window.innerWidth > 800) { document.getElementById('gif-container').innerHTML = '' var container = document.getElementById('video-container') container.innerHTML = '<video width="320" height="240" controls><source src="movie.mp4" type="video/mp4"><source src="movie.ogg" type="video/ogg">Your browser does not support the video tag.</video>' } else { document.getElementById('video-container').innerHTML = '' var container = document.getElementById('gif-container') container.innerHTML = '<img src="https://placehold.it/200">'; } } window.onresize = videoOrImage(); ```
68,490,691
I'm trying to "translate" some of my R scripts to Python, but I notice, that working with data frames in Python is tremendously slower than doing it in R, e.g. exctracting cells according to some conditions. I've done a little investigation, this is how much time it takes to look for a specific value in Python: ``` import pandas as pd from timeit import default_timer as timer code = 145896 # real df is way bigger df = pd.DataFrame(data={ 'code1': [145896, 800175, 633974, 774521, 416109], 'code2': [100, 800, 600, 700, 400], 'code3': [1, 8, 6, 7, 4]} ) start = timer() for _ in range(100000): desired = df.loc[df['code1']==code, 'code2'][0] print(timer() - start) # 19.866242500000226 (sec) ``` and in R: ``` code <- 145896 df <- data.frame("code1" = c(145896, 800175, 633974, 774521, 416109), "code2" = c(100, 800, 600, 700, 400), "code3" = c(1, 8, 6, 7, 4)) start <- Sys.time() for (i in 1:100000) { desired <- df[df$code1 == code, "code2"] } print(Sys.time() - start) # Time difference of 1.140949 secs ``` I'm relatively new to Python, and I'm probably missing something. Is there some way to speed up this process? Maybe the whole idea of transferring this script to Python is pointless? In other operations Python is faster (namely working with strings), and it would be very inconvenient to jump between two or more scripts once working with data frames is required. Any help on this, please? **UPDATE** Real script block iterates over rows of initial data frame (which is fairly large, 500-1500k rows) and creates a new one with rows, containing value from original column "code1" and codes, that correspond it, from another data frame, and many other values, that are newly created. I believe, I can clarify it with the picture: [![enter image description here](https://i.stack.imgur.com/89h2R.png)](https://i.stack.imgur.com/89h2R.png) Later in the script I will need to search for specific values in loops based on different conditions too. So the speed of search is essential.
2021/07/22
[ "https://Stackoverflow.com/questions/68490691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15005884/" ]
Since you are looking to select a **single** value from a DataFrame there are a few things you can do to improve performance. 1. Use `.item()` instead of `[0]`, which has a small, but decent improvement especially for smaller DataFrames. 2. It's wasteful to mask the **entire DataFrame** just to then select a known Series. Instead mask only the Series and select the value. Though you might think "oh this is chained -- the forbidden `][`", it's only chained *assignment* which is worrisome, not chained selection. 3. **Use numpy**. Pandas has a lot of overhead due to the indexing and alingment. But you just want to select a single value from a rectangular data structure, so dropping down to `numpy` will be faster. --- Below are illustrations of the timing for different ways to select the data [Each with it's own method below]. Using `numpy` is by far the fastest, especially for a smaller DataFrame like in your sample. For those, it will be more than 20x faster than your original way to select data, which looking at your initial comparisons with R should make it *slightly faster* than selecting data in R. As the DataFrames get larger the relative performance of the numpy solution isn't as good, but it's still the fastest method (shown here). ``` import perfplot import pandas as pd import numpy as np def DataFrame_Slice(df, code=0): return df.loc[df['code1'] == code, 'code2'].iloc[0] def DataFrame_Slice_Item(df, code=0): return df.loc[df['code1'] == code, 'code2'].item() def Series_Slice_Item(df, code=0): return df['code2'][df['code1'] == code].item() def with_numpy(df, code=0): return df['code2'].to_numpy()[df['code1'].to_numpy() == code].item() perfplot.show( setup=lambda N: pd.DataFrame({'code1': range(N), 'code2': range(50, N+50), 'code3': range(100, N+100)}), kernels=[ lambda df: DataFrame_Slice(df), lambda df: DataFrame_Slice_Item(df), lambda df: Series_Slice_Item(df), lambda df: with_numpy(df) ], labels=['DataFrame_Slice', 'DataFrame_Slice_Item', 'Series_Slice_Item', 'with_numpy'], n_range=[2 ** k for k in range(1, 21)], equality_check=np.allclose, relative_to=3, xlabel='len(df)' ) ``` [![enter image description here](https://i.stack.imgur.com/yZ8hy.png)](https://i.stack.imgur.com/yZ8hy.png)
You can cut it in about half just by reusing the filter expression. ```py In [1]: import pandas as pd In [2]: code = 145896 ...: df = pd.DataFrame(data={ ...: 'code1': [145896, 800175, 633974, 774521, 416109], ...: 'code2': [100, 800, 600, 700, 400], ...: 'code3': [1, 8, 6, 7, 4] ...: }) In [3]: %timeit df.loc[df['code1'] == code, 'code2'][0] 197 µs ± 5.14 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [4]: filter_expr = df['code1'] == code In [5]: %timeit df.loc[filter_expr, 'code2'][0] 106 µs ± 3.3 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) ``` Indexing the dataframe by the key column (assuming the lookup is frequent) should be the way to go because the dataframe's index is a hash table (see [this answer](https://stackoverflow.com/a/27238758/2072035) and [these slides](https://www.slideshare.net/wesm/a-look-at-pandas-design-and-development) for more details). ```py In [6]: df_idx = df.set_index('code1') In [7]: %timeit df_idx.loc[code]['code2'] 72.7 µs ± 1.58 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) ``` And depending on other use cases that you have, having data a true embedded (in-memory) database, SQLite or [DuckDB](https://duckdb.org/) (*can run queries directly on Pandas data without ever importing or copying any data*), may also be a solution.
68,490,691
I'm trying to "translate" some of my R scripts to Python, but I notice, that working with data frames in Python is tremendously slower than doing it in R, e.g. exctracting cells according to some conditions. I've done a little investigation, this is how much time it takes to look for a specific value in Python: ``` import pandas as pd from timeit import default_timer as timer code = 145896 # real df is way bigger df = pd.DataFrame(data={ 'code1': [145896, 800175, 633974, 774521, 416109], 'code2': [100, 800, 600, 700, 400], 'code3': [1, 8, 6, 7, 4]} ) start = timer() for _ in range(100000): desired = df.loc[df['code1']==code, 'code2'][0] print(timer() - start) # 19.866242500000226 (sec) ``` and in R: ``` code <- 145896 df <- data.frame("code1" = c(145896, 800175, 633974, 774521, 416109), "code2" = c(100, 800, 600, 700, 400), "code3" = c(1, 8, 6, 7, 4)) start <- Sys.time() for (i in 1:100000) { desired <- df[df$code1 == code, "code2"] } print(Sys.time() - start) # Time difference of 1.140949 secs ``` I'm relatively new to Python, and I'm probably missing something. Is there some way to speed up this process? Maybe the whole idea of transferring this script to Python is pointless? In other operations Python is faster (namely working with strings), and it would be very inconvenient to jump between two or more scripts once working with data frames is required. Any help on this, please? **UPDATE** Real script block iterates over rows of initial data frame (which is fairly large, 500-1500k rows) and creates a new one with rows, containing value from original column "code1" and codes, that correspond it, from another data frame, and many other values, that are newly created. I believe, I can clarify it with the picture: [![enter image description here](https://i.stack.imgur.com/89h2R.png)](https://i.stack.imgur.com/89h2R.png) Later in the script I will need to search for specific values in loops based on different conditions too. So the speed of search is essential.
2021/07/22
[ "https://Stackoverflow.com/questions/68490691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15005884/" ]
You can cut it in about half just by reusing the filter expression. ```py In [1]: import pandas as pd In [2]: code = 145896 ...: df = pd.DataFrame(data={ ...: 'code1': [145896, 800175, 633974, 774521, 416109], ...: 'code2': [100, 800, 600, 700, 400], ...: 'code3': [1, 8, 6, 7, 4] ...: }) In [3]: %timeit df.loc[df['code1'] == code, 'code2'][0] 197 µs ± 5.14 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [4]: filter_expr = df['code1'] == code In [5]: %timeit df.loc[filter_expr, 'code2'][0] 106 µs ± 3.3 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) ``` Indexing the dataframe by the key column (assuming the lookup is frequent) should be the way to go because the dataframe's index is a hash table (see [this answer](https://stackoverflow.com/a/27238758/2072035) and [these slides](https://www.slideshare.net/wesm/a-look-at-pandas-design-and-development) for more details). ```py In [6]: df_idx = df.set_index('code1') In [7]: %timeit df_idx.loc[code]['code2'] 72.7 µs ± 1.58 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) ``` And depending on other use cases that you have, having data a true embedded (in-memory) database, SQLite or [DuckDB](https://duckdb.org/) (*can run queries directly on Pandas data without ever importing or copying any data*), may also be a solution.
R-lang was probably designed around this kind of operations. Pandas is a third-party library in python, so it has additional limitations and overheads to work around. Namely, upon each intermediate step a new dataframe or series is generated. Almost each equals sign or a bracket is an intermediate step. If you really want to extract single element at a time from a single column, you can try setting index: ``` df2 = df.set_index('code1') def getel(df2,code): desired = None if code in df2.index: desired = df2['code2'][code] if isinstance(desired, pd.Series): desired = desired.iloc[0] return code ``` This is three times faster than original if the value is duplicated. If the value is unique, then `desired = df2['code2'][code]` does not generate new series and the code is 17 times faster than original. Also, notice that selecting columns before everything else tends to be a notable reduction in the unnecessary work pandas do. If you instead want to do similar operations on different values, then you should probably look at `groupby`. Or at least filter all the values to be processed at once: ``` codes = {145896,774521} pad = df['code1'].apply(lambda x: x in codes) #this is good when there are many codes #or pad = df['code1'].isin(codes) #this is linear time in len(codes) result = df[pad].apply(do_stuff, axis = 1) #or df[pad].transform(do_stuff, axis = 1) ```
68,490,691
I'm trying to "translate" some of my R scripts to Python, but I notice, that working with data frames in Python is tremendously slower than doing it in R, e.g. exctracting cells according to some conditions. I've done a little investigation, this is how much time it takes to look for a specific value in Python: ``` import pandas as pd from timeit import default_timer as timer code = 145896 # real df is way bigger df = pd.DataFrame(data={ 'code1': [145896, 800175, 633974, 774521, 416109], 'code2': [100, 800, 600, 700, 400], 'code3': [1, 8, 6, 7, 4]} ) start = timer() for _ in range(100000): desired = df.loc[df['code1']==code, 'code2'][0] print(timer() - start) # 19.866242500000226 (sec) ``` and in R: ``` code <- 145896 df <- data.frame("code1" = c(145896, 800175, 633974, 774521, 416109), "code2" = c(100, 800, 600, 700, 400), "code3" = c(1, 8, 6, 7, 4)) start <- Sys.time() for (i in 1:100000) { desired <- df[df$code1 == code, "code2"] } print(Sys.time() - start) # Time difference of 1.140949 secs ``` I'm relatively new to Python, and I'm probably missing something. Is there some way to speed up this process? Maybe the whole idea of transferring this script to Python is pointless? In other operations Python is faster (namely working with strings), and it would be very inconvenient to jump between two or more scripts once working with data frames is required. Any help on this, please? **UPDATE** Real script block iterates over rows of initial data frame (which is fairly large, 500-1500k rows) and creates a new one with rows, containing value from original column "code1" and codes, that correspond it, from another data frame, and many other values, that are newly created. I believe, I can clarify it with the picture: [![enter image description here](https://i.stack.imgur.com/89h2R.png)](https://i.stack.imgur.com/89h2R.png) Later in the script I will need to search for specific values in loops based on different conditions too. So the speed of search is essential.
2021/07/22
[ "https://Stackoverflow.com/questions/68490691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15005884/" ]
You can cut it in about half just by reusing the filter expression. ```py In [1]: import pandas as pd In [2]: code = 145896 ...: df = pd.DataFrame(data={ ...: 'code1': [145896, 800175, 633974, 774521, 416109], ...: 'code2': [100, 800, 600, 700, 400], ...: 'code3': [1, 8, 6, 7, 4] ...: }) In [3]: %timeit df.loc[df['code1'] == code, 'code2'][0] 197 µs ± 5.14 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [4]: filter_expr = df['code1'] == code In [5]: %timeit df.loc[filter_expr, 'code2'][0] 106 µs ± 3.3 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) ``` Indexing the dataframe by the key column (assuming the lookup is frequent) should be the way to go because the dataframe's index is a hash table (see [this answer](https://stackoverflow.com/a/27238758/2072035) and [these slides](https://www.slideshare.net/wesm/a-look-at-pandas-design-and-development) for more details). ```py In [6]: df_idx = df.set_index('code1') In [7]: %timeit df_idx.loc[code]['code2'] 72.7 µs ± 1.58 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) ``` And depending on other use cases that you have, having data a true embedded (in-memory) database, SQLite or [DuckDB](https://duckdb.org/) (*can run queries directly on Pandas data without ever importing or copying any data*), may also be a solution.
One way to do it is to fall back on numpy by first getting the underlying arrays and then looping: ``` import pandas as pd from timeit import default_timer as timer code = 145896 # real df is way bigger df = pd.DataFrame(data={ 'code1': [145896, 800175, 633974, 774521, 416109], 'code2': [100, 800, 600, 700, 400], 'code3': [1, 8, 6, 7, 4]} ) start = timer() code1 = df['code1'].values code2 = df['code2'].values code3 = df['code3'].values for _ in range(100000): desired = code1 == code desired_code2 = code2[desired][0] desired_code3 = code3[desired][0] print(timer() - start) # 0.26 (sec) ``` The following code adapted from [ALollz](https://stackoverflow.com/users/4333359/alollz)'s answer illustrates the difference in performance of the different techniques with several more added and an increased dataset size range that shows changing behavior affected by orders of magnitude. ``` import perfplot import pandas as pd import numpy as np def DataFrame_Slice(df, code=0): return df.loc[df['code1'] == code, 'code2'].iloc[0] def DataFrame_Slice_Item(df, code=0): return df.loc[df['code1'] == code, 'code2'].item() def Series_Slice_Item(df, code=0): return df['code2'][df['code1'] == code].item() def with_numpy(df, code=0): return df['code2'].to_numpy()[df['code1'].to_numpy() == code].item() def with_numpy_values(code1, code2, code=0): desired = code1 == code desired_code2 = code2[desired][0] return desired_code2 def DataFrameIndex(df, code=0): return df.loc[code].code2 def with_numpy_argmax(code1, code2, code=0): return code2[np.argmax(code1==code)] def numpy_search_sorted(code1, code2, sorter, code=0): return code2[sorter[np.searchsorted(code1, code, sorter=sorter)]] def python_dict(code1_dict, code2, code=0): return code2[code1_dict[code]] def shuffled_array(N): a = np.arange(0, N) np.random.shuffle(a) return a def setup(N): print(f'setup {N}') df = pd.DataFrame({'code1': shuffled_array(N), 'code2': shuffled_array(N), 'code3': shuffled_array(N)}) code = df.iloc[min(len(df)//2, len(df)//2 + 20)].code1 sorted_index = df['code1'].values.argsort() code1 = df['code1'].values code2 = df['code2'].values code1_dict = {code1[i]: i for i in range(len(code1))} return df, df.set_index('code1'), code1, code2, sorted_index, code1_dict, code for relative_to in [5, 6, 7]: perfplot.show( setup=setup, kernels=[ lambda df, _, __, ___, sorted_index, ____, code: DataFrame_Slice(df, code), lambda df, _, __, ___, sorted_index, ____, code: DataFrame_Slice_Item(df, code), lambda df, _, __, ___, sorted_index, ____, code: Series_Slice_Item(df, code), lambda df, _, __, ___, sorted_index, ____, code: with_numpy(df, code), lambda _, __, code1, code2, sorted_index, ____, code: with_numpy_values(code1, code2, code), lambda _, __, code1, code2, sorted_index, ____, code: with_numpy_argmax(code1, code2, code), lambda _, df, __, ___, sorted_index, ____, code: DataFrameIndex(df, code), lambda _, __, code1, code2, search_index, ____, code: numpy_search_sorted(code1, code2, search_index, code), lambda _, __, ___, code2, _____, code1_dict, code: python_dict(code1_dict, code2, code) ], logy=True, labels=['DataFrame_Slice', 'DataFrame_Slice_Item', 'Series_Slice_Item', 'with_numpy', 'with_numpy_values', 'with_numpy_argmax', 'DataFrameIndex', 'numpy_search_sorted', 'python_dict'], n_range=[2 ** k for k in range(1, 25)], equality_check=np.allclose, relative_to=relative_to, xlabel='len(df)') ``` Conclusion: Numpy search sorted is the best performing technique except for very small data sets below 100 mark. Sequential search using the underlying `numpy` arrays is the next best option for datasets roughly below 100,000 after which the best option is to use the `DataFrame` index. However, when hitting the multi-million records mark, `DataFrame` indexes no longer perform well, probably due to hashing collisions. [EDIT 03/24/2022] Using a Python dictionary beats all other techniques by at least one order of magnitude. [![Figure 1](https://i.stack.imgur.com/4TqEZ.png)](https://i.stack.imgur.com/4TqEZ.png) [![Figure 2](https://i.stack.imgur.com/Aw4nR.png)](https://i.stack.imgur.com/Aw4nR.png) [![Figure 3](https://i.stack.imgur.com/bkDta.png)](https://i.stack.imgur.com/bkDta.png) Note: We are assuming repeated searches within the DataFrame, so as to offset the cost of acquiring the underlying numpy arrays, indexing the DataFrame or sorting the numpy array.
68,490,691
I'm trying to "translate" some of my R scripts to Python, but I notice, that working with data frames in Python is tremendously slower than doing it in R, e.g. exctracting cells according to some conditions. I've done a little investigation, this is how much time it takes to look for a specific value in Python: ``` import pandas as pd from timeit import default_timer as timer code = 145896 # real df is way bigger df = pd.DataFrame(data={ 'code1': [145896, 800175, 633974, 774521, 416109], 'code2': [100, 800, 600, 700, 400], 'code3': [1, 8, 6, 7, 4]} ) start = timer() for _ in range(100000): desired = df.loc[df['code1']==code, 'code2'][0] print(timer() - start) # 19.866242500000226 (sec) ``` and in R: ``` code <- 145896 df <- data.frame("code1" = c(145896, 800175, 633974, 774521, 416109), "code2" = c(100, 800, 600, 700, 400), "code3" = c(1, 8, 6, 7, 4)) start <- Sys.time() for (i in 1:100000) { desired <- df[df$code1 == code, "code2"] } print(Sys.time() - start) # Time difference of 1.140949 secs ``` I'm relatively new to Python, and I'm probably missing something. Is there some way to speed up this process? Maybe the whole idea of transferring this script to Python is pointless? In other operations Python is faster (namely working with strings), and it would be very inconvenient to jump between two or more scripts once working with data frames is required. Any help on this, please? **UPDATE** Real script block iterates over rows of initial data frame (which is fairly large, 500-1500k rows) and creates a new one with rows, containing value from original column "code1" and codes, that correspond it, from another data frame, and many other values, that are newly created. I believe, I can clarify it with the picture: [![enter image description here](https://i.stack.imgur.com/89h2R.png)](https://i.stack.imgur.com/89h2R.png) Later in the script I will need to search for specific values in loops based on different conditions too. So the speed of search is essential.
2021/07/22
[ "https://Stackoverflow.com/questions/68490691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15005884/" ]
Since you are looking to select a **single** value from a DataFrame there are a few things you can do to improve performance. 1. Use `.item()` instead of `[0]`, which has a small, but decent improvement especially for smaller DataFrames. 2. It's wasteful to mask the **entire DataFrame** just to then select a known Series. Instead mask only the Series and select the value. Though you might think "oh this is chained -- the forbidden `][`", it's only chained *assignment* which is worrisome, not chained selection. 3. **Use numpy**. Pandas has a lot of overhead due to the indexing and alingment. But you just want to select a single value from a rectangular data structure, so dropping down to `numpy` will be faster. --- Below are illustrations of the timing for different ways to select the data [Each with it's own method below]. Using `numpy` is by far the fastest, especially for a smaller DataFrame like in your sample. For those, it will be more than 20x faster than your original way to select data, which looking at your initial comparisons with R should make it *slightly faster* than selecting data in R. As the DataFrames get larger the relative performance of the numpy solution isn't as good, but it's still the fastest method (shown here). ``` import perfplot import pandas as pd import numpy as np def DataFrame_Slice(df, code=0): return df.loc[df['code1'] == code, 'code2'].iloc[0] def DataFrame_Slice_Item(df, code=0): return df.loc[df['code1'] == code, 'code2'].item() def Series_Slice_Item(df, code=0): return df['code2'][df['code1'] == code].item() def with_numpy(df, code=0): return df['code2'].to_numpy()[df['code1'].to_numpy() == code].item() perfplot.show( setup=lambda N: pd.DataFrame({'code1': range(N), 'code2': range(50, N+50), 'code3': range(100, N+100)}), kernels=[ lambda df: DataFrame_Slice(df), lambda df: DataFrame_Slice_Item(df), lambda df: Series_Slice_Item(df), lambda df: with_numpy(df) ], labels=['DataFrame_Slice', 'DataFrame_Slice_Item', 'Series_Slice_Item', 'with_numpy'], n_range=[2 ** k for k in range(1, 21)], equality_check=np.allclose, relative_to=3, xlabel='len(df)' ) ``` [![enter image description here](https://i.stack.imgur.com/yZ8hy.png)](https://i.stack.imgur.com/yZ8hy.png)
R-lang was probably designed around this kind of operations. Pandas is a third-party library in python, so it has additional limitations and overheads to work around. Namely, upon each intermediate step a new dataframe or series is generated. Almost each equals sign or a bracket is an intermediate step. If you really want to extract single element at a time from a single column, you can try setting index: ``` df2 = df.set_index('code1') def getel(df2,code): desired = None if code in df2.index: desired = df2['code2'][code] if isinstance(desired, pd.Series): desired = desired.iloc[0] return code ``` This is three times faster than original if the value is duplicated. If the value is unique, then `desired = df2['code2'][code]` does not generate new series and the code is 17 times faster than original. Also, notice that selecting columns before everything else tends to be a notable reduction in the unnecessary work pandas do. If you instead want to do similar operations on different values, then you should probably look at `groupby`. Or at least filter all the values to be processed at once: ``` codes = {145896,774521} pad = df['code1'].apply(lambda x: x in codes) #this is good when there are many codes #or pad = df['code1'].isin(codes) #this is linear time in len(codes) result = df[pad].apply(do_stuff, axis = 1) #or df[pad].transform(do_stuff, axis = 1) ```
68,490,691
I'm trying to "translate" some of my R scripts to Python, but I notice, that working with data frames in Python is tremendously slower than doing it in R, e.g. exctracting cells according to some conditions. I've done a little investigation, this is how much time it takes to look for a specific value in Python: ``` import pandas as pd from timeit import default_timer as timer code = 145896 # real df is way bigger df = pd.DataFrame(data={ 'code1': [145896, 800175, 633974, 774521, 416109], 'code2': [100, 800, 600, 700, 400], 'code3': [1, 8, 6, 7, 4]} ) start = timer() for _ in range(100000): desired = df.loc[df['code1']==code, 'code2'][0] print(timer() - start) # 19.866242500000226 (sec) ``` and in R: ``` code <- 145896 df <- data.frame("code1" = c(145896, 800175, 633974, 774521, 416109), "code2" = c(100, 800, 600, 700, 400), "code3" = c(1, 8, 6, 7, 4)) start <- Sys.time() for (i in 1:100000) { desired <- df[df$code1 == code, "code2"] } print(Sys.time() - start) # Time difference of 1.140949 secs ``` I'm relatively new to Python, and I'm probably missing something. Is there some way to speed up this process? Maybe the whole idea of transferring this script to Python is pointless? In other operations Python is faster (namely working with strings), and it would be very inconvenient to jump between two or more scripts once working with data frames is required. Any help on this, please? **UPDATE** Real script block iterates over rows of initial data frame (which is fairly large, 500-1500k rows) and creates a new one with rows, containing value from original column "code1" and codes, that correspond it, from another data frame, and many other values, that are newly created. I believe, I can clarify it with the picture: [![enter image description here](https://i.stack.imgur.com/89h2R.png)](https://i.stack.imgur.com/89h2R.png) Later in the script I will need to search for specific values in loops based on different conditions too. So the speed of search is essential.
2021/07/22
[ "https://Stackoverflow.com/questions/68490691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15005884/" ]
Since you are looking to select a **single** value from a DataFrame there are a few things you can do to improve performance. 1. Use `.item()` instead of `[0]`, which has a small, but decent improvement especially for smaller DataFrames. 2. It's wasteful to mask the **entire DataFrame** just to then select a known Series. Instead mask only the Series and select the value. Though you might think "oh this is chained -- the forbidden `][`", it's only chained *assignment* which is worrisome, not chained selection. 3. **Use numpy**. Pandas has a lot of overhead due to the indexing and alingment. But you just want to select a single value from a rectangular data structure, so dropping down to `numpy` will be faster. --- Below are illustrations of the timing for different ways to select the data [Each with it's own method below]. Using `numpy` is by far the fastest, especially for a smaller DataFrame like in your sample. For those, it will be more than 20x faster than your original way to select data, which looking at your initial comparisons with R should make it *slightly faster* than selecting data in R. As the DataFrames get larger the relative performance of the numpy solution isn't as good, but it's still the fastest method (shown here). ``` import perfplot import pandas as pd import numpy as np def DataFrame_Slice(df, code=0): return df.loc[df['code1'] == code, 'code2'].iloc[0] def DataFrame_Slice_Item(df, code=0): return df.loc[df['code1'] == code, 'code2'].item() def Series_Slice_Item(df, code=0): return df['code2'][df['code1'] == code].item() def with_numpy(df, code=0): return df['code2'].to_numpy()[df['code1'].to_numpy() == code].item() perfplot.show( setup=lambda N: pd.DataFrame({'code1': range(N), 'code2': range(50, N+50), 'code3': range(100, N+100)}), kernels=[ lambda df: DataFrame_Slice(df), lambda df: DataFrame_Slice_Item(df), lambda df: Series_Slice_Item(df), lambda df: with_numpy(df) ], labels=['DataFrame_Slice', 'DataFrame_Slice_Item', 'Series_Slice_Item', 'with_numpy'], n_range=[2 ** k for k in range(1, 21)], equality_check=np.allclose, relative_to=3, xlabel='len(df)' ) ``` [![enter image description here](https://i.stack.imgur.com/yZ8hy.png)](https://i.stack.imgur.com/yZ8hy.png)
One way to do it is to fall back on numpy by first getting the underlying arrays and then looping: ``` import pandas as pd from timeit import default_timer as timer code = 145896 # real df is way bigger df = pd.DataFrame(data={ 'code1': [145896, 800175, 633974, 774521, 416109], 'code2': [100, 800, 600, 700, 400], 'code3': [1, 8, 6, 7, 4]} ) start = timer() code1 = df['code1'].values code2 = df['code2'].values code3 = df['code3'].values for _ in range(100000): desired = code1 == code desired_code2 = code2[desired][0] desired_code3 = code3[desired][0] print(timer() - start) # 0.26 (sec) ``` The following code adapted from [ALollz](https://stackoverflow.com/users/4333359/alollz)'s answer illustrates the difference in performance of the different techniques with several more added and an increased dataset size range that shows changing behavior affected by orders of magnitude. ``` import perfplot import pandas as pd import numpy as np def DataFrame_Slice(df, code=0): return df.loc[df['code1'] == code, 'code2'].iloc[0] def DataFrame_Slice_Item(df, code=0): return df.loc[df['code1'] == code, 'code2'].item() def Series_Slice_Item(df, code=0): return df['code2'][df['code1'] == code].item() def with_numpy(df, code=0): return df['code2'].to_numpy()[df['code1'].to_numpy() == code].item() def with_numpy_values(code1, code2, code=0): desired = code1 == code desired_code2 = code2[desired][0] return desired_code2 def DataFrameIndex(df, code=0): return df.loc[code].code2 def with_numpy_argmax(code1, code2, code=0): return code2[np.argmax(code1==code)] def numpy_search_sorted(code1, code2, sorter, code=0): return code2[sorter[np.searchsorted(code1, code, sorter=sorter)]] def python_dict(code1_dict, code2, code=0): return code2[code1_dict[code]] def shuffled_array(N): a = np.arange(0, N) np.random.shuffle(a) return a def setup(N): print(f'setup {N}') df = pd.DataFrame({'code1': shuffled_array(N), 'code2': shuffled_array(N), 'code3': shuffled_array(N)}) code = df.iloc[min(len(df)//2, len(df)//2 + 20)].code1 sorted_index = df['code1'].values.argsort() code1 = df['code1'].values code2 = df['code2'].values code1_dict = {code1[i]: i for i in range(len(code1))} return df, df.set_index('code1'), code1, code2, sorted_index, code1_dict, code for relative_to in [5, 6, 7]: perfplot.show( setup=setup, kernels=[ lambda df, _, __, ___, sorted_index, ____, code: DataFrame_Slice(df, code), lambda df, _, __, ___, sorted_index, ____, code: DataFrame_Slice_Item(df, code), lambda df, _, __, ___, sorted_index, ____, code: Series_Slice_Item(df, code), lambda df, _, __, ___, sorted_index, ____, code: with_numpy(df, code), lambda _, __, code1, code2, sorted_index, ____, code: with_numpy_values(code1, code2, code), lambda _, __, code1, code2, sorted_index, ____, code: with_numpy_argmax(code1, code2, code), lambda _, df, __, ___, sorted_index, ____, code: DataFrameIndex(df, code), lambda _, __, code1, code2, search_index, ____, code: numpy_search_sorted(code1, code2, search_index, code), lambda _, __, ___, code2, _____, code1_dict, code: python_dict(code1_dict, code2, code) ], logy=True, labels=['DataFrame_Slice', 'DataFrame_Slice_Item', 'Series_Slice_Item', 'with_numpy', 'with_numpy_values', 'with_numpy_argmax', 'DataFrameIndex', 'numpy_search_sorted', 'python_dict'], n_range=[2 ** k for k in range(1, 25)], equality_check=np.allclose, relative_to=relative_to, xlabel='len(df)') ``` Conclusion: Numpy search sorted is the best performing technique except for very small data sets below 100 mark. Sequential search using the underlying `numpy` arrays is the next best option for datasets roughly below 100,000 after which the best option is to use the `DataFrame` index. However, when hitting the multi-million records mark, `DataFrame` indexes no longer perform well, probably due to hashing collisions. [EDIT 03/24/2022] Using a Python dictionary beats all other techniques by at least one order of magnitude. [![Figure 1](https://i.stack.imgur.com/4TqEZ.png)](https://i.stack.imgur.com/4TqEZ.png) [![Figure 2](https://i.stack.imgur.com/Aw4nR.png)](https://i.stack.imgur.com/Aw4nR.png) [![Figure 3](https://i.stack.imgur.com/bkDta.png)](https://i.stack.imgur.com/bkDta.png) Note: We are assuming repeated searches within the DataFrame, so as to offset the cost of acquiring the underlying numpy arrays, indexing the DataFrame or sorting the numpy array.
68,490,691
I'm trying to "translate" some of my R scripts to Python, but I notice, that working with data frames in Python is tremendously slower than doing it in R, e.g. exctracting cells according to some conditions. I've done a little investigation, this is how much time it takes to look for a specific value in Python: ``` import pandas as pd from timeit import default_timer as timer code = 145896 # real df is way bigger df = pd.DataFrame(data={ 'code1': [145896, 800175, 633974, 774521, 416109], 'code2': [100, 800, 600, 700, 400], 'code3': [1, 8, 6, 7, 4]} ) start = timer() for _ in range(100000): desired = df.loc[df['code1']==code, 'code2'][0] print(timer() - start) # 19.866242500000226 (sec) ``` and in R: ``` code <- 145896 df <- data.frame("code1" = c(145896, 800175, 633974, 774521, 416109), "code2" = c(100, 800, 600, 700, 400), "code3" = c(1, 8, 6, 7, 4)) start <- Sys.time() for (i in 1:100000) { desired <- df[df$code1 == code, "code2"] } print(Sys.time() - start) # Time difference of 1.140949 secs ``` I'm relatively new to Python, and I'm probably missing something. Is there some way to speed up this process? Maybe the whole idea of transferring this script to Python is pointless? In other operations Python is faster (namely working with strings), and it would be very inconvenient to jump between two or more scripts once working with data frames is required. Any help on this, please? **UPDATE** Real script block iterates over rows of initial data frame (which is fairly large, 500-1500k rows) and creates a new one with rows, containing value from original column "code1" and codes, that correspond it, from another data frame, and many other values, that are newly created. I believe, I can clarify it with the picture: [![enter image description here](https://i.stack.imgur.com/89h2R.png)](https://i.stack.imgur.com/89h2R.png) Later in the script I will need to search for specific values in loops based on different conditions too. So the speed of search is essential.
2021/07/22
[ "https://Stackoverflow.com/questions/68490691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15005884/" ]
One way to do it is to fall back on numpy by first getting the underlying arrays and then looping: ``` import pandas as pd from timeit import default_timer as timer code = 145896 # real df is way bigger df = pd.DataFrame(data={ 'code1': [145896, 800175, 633974, 774521, 416109], 'code2': [100, 800, 600, 700, 400], 'code3': [1, 8, 6, 7, 4]} ) start = timer() code1 = df['code1'].values code2 = df['code2'].values code3 = df['code3'].values for _ in range(100000): desired = code1 == code desired_code2 = code2[desired][0] desired_code3 = code3[desired][0] print(timer() - start) # 0.26 (sec) ``` The following code adapted from [ALollz](https://stackoverflow.com/users/4333359/alollz)'s answer illustrates the difference in performance of the different techniques with several more added and an increased dataset size range that shows changing behavior affected by orders of magnitude. ``` import perfplot import pandas as pd import numpy as np def DataFrame_Slice(df, code=0): return df.loc[df['code1'] == code, 'code2'].iloc[0] def DataFrame_Slice_Item(df, code=0): return df.loc[df['code1'] == code, 'code2'].item() def Series_Slice_Item(df, code=0): return df['code2'][df['code1'] == code].item() def with_numpy(df, code=0): return df['code2'].to_numpy()[df['code1'].to_numpy() == code].item() def with_numpy_values(code1, code2, code=0): desired = code1 == code desired_code2 = code2[desired][0] return desired_code2 def DataFrameIndex(df, code=0): return df.loc[code].code2 def with_numpy_argmax(code1, code2, code=0): return code2[np.argmax(code1==code)] def numpy_search_sorted(code1, code2, sorter, code=0): return code2[sorter[np.searchsorted(code1, code, sorter=sorter)]] def python_dict(code1_dict, code2, code=0): return code2[code1_dict[code]] def shuffled_array(N): a = np.arange(0, N) np.random.shuffle(a) return a def setup(N): print(f'setup {N}') df = pd.DataFrame({'code1': shuffled_array(N), 'code2': shuffled_array(N), 'code3': shuffled_array(N)}) code = df.iloc[min(len(df)//2, len(df)//2 + 20)].code1 sorted_index = df['code1'].values.argsort() code1 = df['code1'].values code2 = df['code2'].values code1_dict = {code1[i]: i for i in range(len(code1))} return df, df.set_index('code1'), code1, code2, sorted_index, code1_dict, code for relative_to in [5, 6, 7]: perfplot.show( setup=setup, kernels=[ lambda df, _, __, ___, sorted_index, ____, code: DataFrame_Slice(df, code), lambda df, _, __, ___, sorted_index, ____, code: DataFrame_Slice_Item(df, code), lambda df, _, __, ___, sorted_index, ____, code: Series_Slice_Item(df, code), lambda df, _, __, ___, sorted_index, ____, code: with_numpy(df, code), lambda _, __, code1, code2, sorted_index, ____, code: with_numpy_values(code1, code2, code), lambda _, __, code1, code2, sorted_index, ____, code: with_numpy_argmax(code1, code2, code), lambda _, df, __, ___, sorted_index, ____, code: DataFrameIndex(df, code), lambda _, __, code1, code2, search_index, ____, code: numpy_search_sorted(code1, code2, search_index, code), lambda _, __, ___, code2, _____, code1_dict, code: python_dict(code1_dict, code2, code) ], logy=True, labels=['DataFrame_Slice', 'DataFrame_Slice_Item', 'Series_Slice_Item', 'with_numpy', 'with_numpy_values', 'with_numpy_argmax', 'DataFrameIndex', 'numpy_search_sorted', 'python_dict'], n_range=[2 ** k for k in range(1, 25)], equality_check=np.allclose, relative_to=relative_to, xlabel='len(df)') ``` Conclusion: Numpy search sorted is the best performing technique except for very small data sets below 100 mark. Sequential search using the underlying `numpy` arrays is the next best option for datasets roughly below 100,000 after which the best option is to use the `DataFrame` index. However, when hitting the multi-million records mark, `DataFrame` indexes no longer perform well, probably due to hashing collisions. [EDIT 03/24/2022] Using a Python dictionary beats all other techniques by at least one order of magnitude. [![Figure 1](https://i.stack.imgur.com/4TqEZ.png)](https://i.stack.imgur.com/4TqEZ.png) [![Figure 2](https://i.stack.imgur.com/Aw4nR.png)](https://i.stack.imgur.com/Aw4nR.png) [![Figure 3](https://i.stack.imgur.com/bkDta.png)](https://i.stack.imgur.com/bkDta.png) Note: We are assuming repeated searches within the DataFrame, so as to offset the cost of acquiring the underlying numpy arrays, indexing the DataFrame or sorting the numpy array.
R-lang was probably designed around this kind of operations. Pandas is a third-party library in python, so it has additional limitations and overheads to work around. Namely, upon each intermediate step a new dataframe or series is generated. Almost each equals sign or a bracket is an intermediate step. If you really want to extract single element at a time from a single column, you can try setting index: ``` df2 = df.set_index('code1') def getel(df2,code): desired = None if code in df2.index: desired = df2['code2'][code] if isinstance(desired, pd.Series): desired = desired.iloc[0] return code ``` This is three times faster than original if the value is duplicated. If the value is unique, then `desired = df2['code2'][code]` does not generate new series and the code is 17 times faster than original. Also, notice that selecting columns before everything else tends to be a notable reduction in the unnecessary work pandas do. If you instead want to do similar operations on different values, then you should probably look at `groupby`. Or at least filter all the values to be processed at once: ``` codes = {145896,774521} pad = df['code1'].apply(lambda x: x in codes) #this is good when there are many codes #or pad = df['code1'].isin(codes) #this is linear time in len(codes) result = df[pad].apply(do_stuff, axis = 1) #or df[pad].transform(do_stuff, axis = 1) ```
19,227,124
I have upgraded my project to rails 4 but now I am getting some deprecation warnings and one of them is **DEPRECATION: any\_number\_of\_times is deprecated.**. Code for which I am gettings this warning is ``` sponsorship = RSpec::Mocks::Mock.new(:sponsorship) SPONSORSHIP.should_receive(:[]).with('sponsorship').any_number_of_times.and_return(sponsorship) ``` and another scenario is ``` sponsorship.should_receive(:[]).with(key).any_number_of_times.and_return(value) ``` I have used stub for above code but it is not stubbing correctly. Can you find where I am doing it wrong. For stubbing I have used ``` SPONSORSHIP.stub(:[]).with('sponsorship').and_return(sponsorship) ```
2013/10/07
[ "https://Stackoverflow.com/questions/19227124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2086124/" ]
The method `any_number_of_times` is deprecated (and is going away in RSpec 3) because it's not really testing anything. It will never fail, since it can be called 0 times as well. See extended argument in <https://trello.com/c/p2OsobvA/78-update-website-menu-architecture-to-accommodate-pledging-as-well-as-weddings-memorials-etc>. If you expect it to be called at least once, you can use `at_least(1).times`.
Since **`any_number_of_times`** is not of any help other alternative methods like **`at_least(n)`** and **`at_most(n)`** helped removing those deprecation warnings.
58,965,861
I am scratching my head trying to understand the point of the following code ``` Map<String Set<MyOtherObj>> myMap = myapi.getMyMap(); final MyObj[] myObjList; { final List<MyObj> list = new ArrayList<>(myMap.size()); for (Entry<String, Set<MyOtherObj>> entry : myMap.entrySet()) { final int myCount = MyUtility.getCount(entry.getValue()); if (myCount <= 0) continue; list.add(new MyObj(entry.getKey(), myCount)); } if (list.isEmpty()) return; myObjList = list.toArray(new MyObj[list.size()]); } ``` Which can be rewrite into the following ``` Map<String Set<MyOtherObj>> myMap = myapi.getMyMap(); final List<MyObj> list = new ArrayList<>(myMap.size()); for (Entry<String, Set<MyOtherObj>> entry : myMap.entrySet()) { final int myCount = MyUtility.getCount(entry.getValue()); if (myCount <= 0) continue; list.add(new MyObj(entry.getKey(), myCount)); } if (list.isEmpty()) return; ``` The only reason I can think of why we put the `ArrayList` in a block and then reassign the content to an array is 1. The size of `ArrayList` is bigger than the size of `list`, so reassigning `ArrayList` to `array` save space 2. There is some sort of compiler magic or gc magic that deallocates and reclaim the memory use by `ArrayList` immediately after the block scope ends (eg. like rust), otherwise we are now sitting on up to 2 times amount of space until gc kicks in. So my question is, does the first code sample make sense, is it more efficient? This code currently executes 20k message per second.
2019/11/21
[ "https://Stackoverflow.com/questions/58965861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10714010/" ]
As stated in [this answer](https://stackoverflow.com/a/24380219/2711488): > > *Scope* is a language concept that determines the validity of names. Whether an object can be garbage collected (and therefore finalized) depends on whether it is *reachable*. > > > So, no, the scope is not relevant to garbage collection, but for maintainable code, it’s recommended to limit the names to the smallest scope needed for their purpose. This, however, does not apply to your scenario, where a new name is introduced to represent the same thing that apparently still is needed. You suggested the possible motivation > > 1. The size of `ArrayList` is bigger than the size of `list`, so reassigning `ArrayList` to `array` save space > > > but you can achieve the same when declaring the variable `list` as `ArrayList<MyObj>` rather than `List<MyObj>` and call `trimToSize()` on it after populating it. There’s another possible reason, the idea that subsequently using a plain array was more efficient than using the array encapsulated in an `ArrayList`. But, of course, the differences between these constructs, if any, rarely matter. Speaking of esoteric optimizations, specifying an initial array size when calling `toArray` was believed to be an advantage, until [someone measured and analyzed](https://shipilev.net/blog/2016/arrays-wisdom-ancients/), to find that, i.e. `myObjList = list.toArray(new MyObj[0]);` would be actually more efficient in real life. Anyway, we can’t look into the author’s mind, which is the reason why any deviation from straight-forward code should be documented. Your alternative suggestion: > > 2. There is some sort of compiler magic or gc magic that deallocates and reclaim the memory use by `ArrayList` immediately after the block scope ends (eg. like rust), otherwise we are now sitting on up to 2 times amount of space until gc kicks in. > > > is missing the point. Any space optimization in Java is about minimizing the amount of memory occupied by objects still alive. It doesn’t matter whether unreachable objects have been identified as such, it’s already sufficient that they are unreachable, hence, potentially reclaimable. The garbage collector will run when there is an actual need for memory, i.e. to serve a new allocation request. Until then, it doesn’t matter whether the unused memory contains old objects or not. So the code may be motivated by a space saving attempt and in that regard, it’s valid, even without an immediate freeing. As said, you could achieve the same in a simpler fashion by just calling `trimToSize()` on the `ArrayList`. But note that if the capacity does not happen to match the size, `trimToSize()`’s shrinking of the array doesn’t work differently behind the scenes, it implies creating a new array and letting the old one become subject to garbage collection. But the fact that there’s no immediate freeing and there’s rarely a need for immediate freeing should allow the conclusion that space saving attempts like this would only matter in practice, when the resulting object is supposed to persist a very long time. When the lifetime of the copy is shorter than the time to the next garbage collection, it didn’t save anything and all that remains, is the unnecessary creation of a copy. Since we can’t predict the time to the next garbage collection, we can only make a rough categorization of the object’s expected lifetime (long or not so long)… The general approach is to assume that in most cases, the higher capacity of an `ArrayList` is not a problem and the performance gain matters more. That’s why this class maintains a higher capacity in the first place.
No, it is done for the same reason as empty lines are added to the code. The variables in the block are scoped to that block, and can no longer be used after the block. So one does not need to pay attention to those block variables. So this is more readable: ``` A a; { B b; C c; ... } ... ``` Than: ``` A a; B b; C c; ... ... ``` It is an attempt to structure the code more readable. For instance above one can read "a declaration of `A a;` and then a block probably filling `a`. Life time analysis in the JVM is fine. Just as there is absolutely no need to set variables to null at the end of their usage. Sometimes blocks are also abused to repeat blocks with same local variables: ``` A a1; { B b; C c; ... a1 ... } A a2; { B b; C c; ... a2 ... } A a3; { B b; C c; ... a3 ... } ``` Needless to say that this is the opposite of making code better style.
21,371,732
I have a `Workshop` Django app. Each `Workshop` can have multiple attendees via a related `WorkshopAttendee` model (simplified below). I am using Django's `ModelForm` in a Class Based View, and in `forms.py` I am using [crispy-forms](http://django-crispy-forms.readthedocs.org): **models.py (relevant parts)** ```python class Workshop(models.Model): title = models.CharField(max_length=100) information = models.TextField() location = models.TextField() class WorkshopAttendee(models.Model): workshop = models.ForeignKey(Workshop) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) ``` **views.py (relevant parts)** ```python from django.views.generic.edit import FormView from workshop.forms import WorkshopAttendeeForm class WorkshopAttendeeFormView(FormView): def form_valid(self, form): # Clean the data form_data = form.cleaned_data form.save(commit=False) return super(WorkshopAttendeeFormView, self).form_valid(form) ``` **forms.py** ```python from django.forms import ModelForm from workshop.models import WorkshopAttendee from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, HTML, Field, \ Fieldset, Button, Hidden, Submit, Reset from crispy_forms.bootstrap import FormActions # Create the form class class WorkshopAttendeeForm(ModelForm): def __init__(self, *args, **kwargs): # Crispy form Layouts, Fieldsets, etc super(WorkshopAttendeeForm, self).__init__(*args, **kwargs) class Meta: model = WorkshopAttendee ``` **urls.py (relevant parts)** ```python urlpatterns = patterns('', url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<slug>[\w\-.]+)/(?P<action>[\w\-.]+)/$', WorkshopAttendeeFormView.as_view( form_class=WorkshopAttendeeForm, success_url="success/", template_name='workshop/workshop_registration.html', ), name='workshop-attendee-register' ), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<slug>[\w\-.]+)/$', WorkshopDetailView.as_view( context_object_name='workshop_detail', queryset=Workshop.objects.select_related(), template_name='workshop/workshop_detail.html', ), name='workshop-detail' ), ) ``` My question is, how can I seed the form with the **workshop\_id** (i.e. the FK relation) in a hidden form field? Obviously because the form hasn't been submitted yet, there is no FK relation yet. But in the URL I have the **kwarg** of `Workshop` **slug**. I can hard-code the `workshop_id` as a `Hidden()` crispy-forms field on a per workshop basis, but this is totally unDRY. Any ideas? I don't think I can use the `select_related()` or `prefetch_related()` methods on the model in **urls.py**, so maybe I have to somehow get both models into the form view somehow? I don't feel like this is an edge-case scenario, and I am sure someone else has had a similar app workflow. Thanks in advance. **UPDATE** After further research it appears that I can do this, using [Django Formsets](https://docs.djangoproject.com/en/dev/topics/forms/formsets/). Not figured out exactly how yet..... hints welcome.
2014/01/27
[ "https://Stackoverflow.com/questions/21371732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109554/" ]
You don't need to pass the PK - you got it already in your URL as the slug. So let's say this is your URL: <http://example.com/workshops/awesome-workshop-slug/sign_in/> Your `urls.py` should look like this: ``` url(r'^workshop/(?P<workshop_slug>\w+)/sign_in/$', # ../workshops/awesome-workshop-slug/sign_in/ view = 'workshop_signin', name = 'workshop-signin', ), ``` Ok, in your `views.py` you're able to do this: ``` @login_required def workshop_signin(request, workshop_slug, template='workshop/sign_in.html'): """Register user to workshop.""" form = WorkshopForm() workshop = Workshop.objects.filter(slug=workshop_slug)[0] if request.method == 'POST': form = WorkshopForm(request.POST, instance=workshop) if form.is_valid(): messages.info(request, 'Yay!') kwargs = { 'workshop_form': form, } return render_to_response(template, kwargs, context_instance=RequestContext(request)) ``` \*untested quick and dirty code
Turns out I was overly complicating this. All I needed to do was modify the `form_valid` method for Django's GCBV `FormView` to this: **workshop/views.py** ```python from django.views.generic.edit import FormView from workshop.models import Workshop, WorkshopAttendee from workshop.forms import WorkshopAttendeeForm from django.http import HttpResponseRedirect class WorkshopAttendeeFormView(FormView): def form_valid(self, form): self.object = form.save(commit=False) self.object.workshop = Workshop.objects.filter(slug=self.kwargs['slug'])[0] self.object.save() return HttpResponseRedirect(self.get_success_url()) ``` Which basically does not save the form on submit, but instead overrides it and first updates the object it is about to save (the `WorkshopAttendee` object) with the relevant `Workshop` (based on the Workshop slug field, which is unique), **then** saves the updated object (`self.object.save`) and kicks me to the success url. Big thanks to @init3 for his helpful pointers. Much appreciated.
130,027
I'm trying to import this SVG; which I imported before earlier but now it seems to don't work that well anymore? The original SVG file has not been modified, so I don't know where the issue could be, closing Photoshop didn't help. Illustrator doesn't have this issue. [![enter image description here](https://i.stack.imgur.com/SyFRt.png)](https://i.stack.imgur.com/SyFRt.png) It is supposed to look like this: [![enter image description here](https://i.stack.imgur.com/WwmRB.png)](https://i.stack.imgur.com/WwmRB.png) When you drag and drop the SVG inside you can choose a height and width and I choosed 1080 and it gave me that pixelated one. How can I fix it?
2019/10/03
[ "https://graphicdesign.stackexchange.com/questions/130027", "https://graphicdesign.stackexchange.com", "https://graphicdesign.stackexchange.com/users/123192/" ]
I believe it is a mix of two fonts: * Akrobat Black: <https://www.fontfabric.com/fonts/akrobat/> * Gear Proportion Regular1: <https://www.dafont.com/gear.font> In the below image you can see the different fonts. The top row is your original image. Second row is Akrobat Black. Third row is Gear Proportion. Final row are Akrobat and Gear properly sized and overlayed in red on top of the original. As you can see, it is pretty close. [![enter image description here](https://i.stack.imgur.com/CQiJS.png)](https://i.stack.imgur.com/CQiJS.png) --- 1. You should always try to get a font from its original creator or foundry. Partly because a lot of fonts are stolen, partly because a lot of fonts are re-encoded and/or compressed and thus damaged. The original foundry site is <http://bridgeco.jp/home.html>, but this is nigh unusable (and only available in Japanese), so here I have opted for a respected font site.
If your goal is to reproduce the logo here, I would suggest you find a typeface close to the logo and then convert it to vector shapes to customize some parts of the word. I think 'Decima+ Bold' is very close to the original. You just need to work on the 'R' and squish the 'O's Hope this helps.
130,027
I'm trying to import this SVG; which I imported before earlier but now it seems to don't work that well anymore? The original SVG file has not been modified, so I don't know where the issue could be, closing Photoshop didn't help. Illustrator doesn't have this issue. [![enter image description here](https://i.stack.imgur.com/SyFRt.png)](https://i.stack.imgur.com/SyFRt.png) It is supposed to look like this: [![enter image description here](https://i.stack.imgur.com/WwmRB.png)](https://i.stack.imgur.com/WwmRB.png) When you drag and drop the SVG inside you can choose a height and width and I choosed 1080 and it gave me that pixelated one. How can I fix it?
2019/10/03
[ "https://graphicdesign.stackexchange.com/questions/130027", "https://graphicdesign.stackexchange.com", "https://graphicdesign.stackexchange.com/users/123192/" ]
If your goal is to reproduce the logo here, I would suggest you find a typeface close to the logo and then convert it to vector shapes to customize some parts of the word. I think 'Decima+ Bold' is very close to the original. You just need to work on the 'R' and squish the 'O's Hope this helps.
I can't find an exact match, which suggests it might be a custom design, or perhaps an existing font (or a mix of 2) which has been modified. For a quick and dirty solution you could auto trace it using vector editing software, such as Adobe Illustrator or free software such as Inkscape. Or, depending on how good your lettering skills are, and how much time you have, it would be possible to manually trace all of the characters with the Pen/Bézier tool in vector editing software. An example using Inkscape to manually trace over the S and R from the logotype: [![enter image description here](https://i.stack.imgur.com/Un54e.png)](https://i.stack.imgur.com/Un54e.png)
130,027
I'm trying to import this SVG; which I imported before earlier but now it seems to don't work that well anymore? The original SVG file has not been modified, so I don't know where the issue could be, closing Photoshop didn't help. Illustrator doesn't have this issue. [![enter image description here](https://i.stack.imgur.com/SyFRt.png)](https://i.stack.imgur.com/SyFRt.png) It is supposed to look like this: [![enter image description here](https://i.stack.imgur.com/WwmRB.png)](https://i.stack.imgur.com/WwmRB.png) When you drag and drop the SVG inside you can choose a height and width and I choosed 1080 and it gave me that pixelated one. How can I fix it?
2019/10/03
[ "https://graphicdesign.stackexchange.com/questions/130027", "https://graphicdesign.stackexchange.com", "https://graphicdesign.stackexchange.com/users/123192/" ]
I believe it is a mix of two fonts: * Akrobat Black: <https://www.fontfabric.com/fonts/akrobat/> * Gear Proportion Regular1: <https://www.dafont.com/gear.font> In the below image you can see the different fonts. The top row is your original image. Second row is Akrobat Black. Third row is Gear Proportion. Final row are Akrobat and Gear properly sized and overlayed in red on top of the original. As you can see, it is pretty close. [![enter image description here](https://i.stack.imgur.com/CQiJS.png)](https://i.stack.imgur.com/CQiJS.png) --- 1. You should always try to get a font from its original creator or foundry. Partly because a lot of fonts are stolen, partly because a lot of fonts are re-encoded and/or compressed and thus damaged. The original foundry site is <http://bridgeco.jp/home.html>, but this is nigh unusable (and only available in Japanese), so here I have opted for a respected font site.
I can't find an exact match, which suggests it might be a custom design, or perhaps an existing font (or a mix of 2) which has been modified. For a quick and dirty solution you could auto trace it using vector editing software, such as Adobe Illustrator or free software such as Inkscape. Or, depending on how good your lettering skills are, and how much time you have, it would be possible to manually trace all of the characters with the Pen/Bézier tool in vector editing software. An example using Inkscape to manually trace over the S and R from the logotype: [![enter image description here](https://i.stack.imgur.com/Un54e.png)](https://i.stack.imgur.com/Un54e.png)
47,176,823
I've been trying to sort this out for weeks, but can't get anywhere. My issue is that I have an array in javascript but the individual phrases in the array also have commas in them. I am passing the array as a variable to php using POST and php is exploding the array into variables, but is also separating parts of the array members that have a comma. Step 1: Array in javascript ``` wrongOnes = ("blah blah blah", "bing, boing, bing"); ``` Step 2: read by php ``` $myArray = explode(',', $_POST["wrongOnes"]); ``` Step 3: this is then made into a message to be posted ``` foreach($myArray as $my_Array){ $message .= "\r\n".$my_Array; } ``` You can see that the problem is exploding and separating at the commas makes extra members of $myArray. I feel that the answer should be easy, but my current level of php is weak. Can anyone help? Cheers Charco.
2017/11/08
[ "https://Stackoverflow.com/questions/47176823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8905789/" ]
The most obvious issue is that your filters are never applied, because $gendre, $country and $year are never passed to the function. Assuming that you read those values correctly from the request object, look at the tags in the HTML, you never set name attribute for either of them, so I think they are never passed to the code correctly if you use regular submit. It is a bit hard to say, because we cannot see the jQuery code, but that is where the problem is I think - in jQuery building your request parameters. To fix paging, when you are building query like this: ``` $query .= " and m_country in('$countrydata') LIMIT {$startpoint} , {$per_page} "; ``` first, add only filter: ``` $query .= " and m_country in('$countrydata') "; ``` and then after all filters are done, before executing your query add this: ``` $query .= " LIMIT {$startpoint} , {$per_page} "; ``` For debugging purposes consider printing out the value of $query just before this line: ``` $rs = mysqli_query($mysqli,$query) or die("Error : ".mysqli_error($mysqli)); ``` And compare them on page 1 and page 2 to see if anything sticks out as a sore thumb.
Tadasbub's answer should be sufficient. I just write out the changes based on his suggestions. ``` <?php $query = "SELECT * FROM movies WHERE movie_status = '1'"; //filter query start if(!empty($genre)){ $genredata =implode("','",$genre); $query .= " and m_genre in('$genredata')"; } if(!empty($country)){ $countrydata =implode("','",$country); $query .= " and m_country in('$countrydata')"; } if(!empty($year)){ $yeardata =implode("','",$year); $query .= " and m_year in('$yeardata')"; } //filter query end $query .= " LIMIT {$startpoint} , {$per_page} "; $rs = mysqli_query($mysqli,$query) or die("Error : ".mysqli_error($mysqli)); ``` Just change the query block as written over here. It should work as you expected. BTW, the problem is only with php logic. It is not related to sql/mysql.
43,690,169
I'm reposting my question because someone closed my question when it wasn't answered correctly and I can't reopen it myself. I'm trying to convert a list of words to a 2D array without using any of the numpy and any of the extension methods. I want to figure it out without the extra methods, but I'm very stuck. ``` def __init__(self, array = [], row, col): self.row = row self.col = col self.array = array ``` I want to convert the list within the `__init__` method, but not really sure how to do this. Would it be better to create a separate method, or should I add it to my `__init__` method? I want to be efficient. ``` ['apple', 'banana', 'dog', 'spider', 'koala'] ``` should be ``` [['apple,' 'banana', 'dog'], ['spider', 'koala', None]] ``` when rows = 3 and cols = 3. I'm also trying to implement other methods, but need to first convert the list to a 2D array. To clarify, a 2 row 3 column array would look like: ``` [['apple', 'banana'], ['dog', 'spider'], ['koala', None]] ```
2017/04/28
[ "https://Stackoverflow.com/questions/43690169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7937034/" ]
well, I'd say your issue is that it looks like you've learned how to make classes, and before thinking about the problem you're trying to solve, you're writing a class. But what you want can simply be done with a loop in a function, without any magic or external thing: ``` def to_matrix(array, nb_rows, nb_cols): # initialise the matrix and a row matrix = [] row = [] # for each item of the array, O(n) for item in array: # add an item to the row row.append(item) # if the row has reached the number of columns if len(row) == nb_cols: # add the row to the matrix matrix.append(row) # reset the row for a new iteration row = [] # if once the loop is finished the row isn't empty # and has less elements than the number of columns if len(row) <= nb_cols: # pad the row with Nones row += [None]*(nb_cols-len(row)) # and add it to the matrix matrix.append(row) # return the matrix return matrix ``` here's how to run it: ``` >>> to_matrix(['apple', 'banana', 'dog', 'spider', 'koala'], 3, 3) [['apple', 'banana', 'dog'], ['spider', 'koala', None]] >>> to_matrix(['apple', 'banana', 'dog', 'spider', 'koala'], 3,2) [['apple', 'banana'], ['dog', 'spider'], ['koala', None]] ``` that algorithm: * is `O(n)`, which means it's linear to the number of elements in the array, * ignores empty rows, * strip the array from overflowing elements, in case the matrix "surface" is smaller than the array's "length". > > *I want to convert the list within the **init** method, but not really sure how to do this. Would it be better to create a separate method, or should I add it to my **init** method? I want to be efficient.* > > > wherever you put the function won't impact efficiency, just readability of your code, its modularity, flexibility and SOLID properties of your class. Because you're not manipulating your class with that method (no need for *self*), you should simply make it a function as above, and call it where you need it. And the constructor is as good a place as any other, it's really depending on the *higher order* algorithm the whole fits. e.g.: ``` def __init__(self, array, row, col): self.array = to_matrix(array, row, col) ```
A quick version using generators: ``` def gen_array(data, count): for i, v in enumerate(data): if i == count: # Shorten too long arrays break yield v for c in range(count - len(data)): # Extend if needed yield None def matrix(array, row, col): l = list(gen_array(array, row * col)) for i in range(0, len(l), col): yield l[i:i + col] mat = list(matrix([1, 2, 3, 4, 5], 3, 4)) ``` Can take empty lists, too short and too long lists. The code can probably also be simplified even more.
5,472,526
I have switched over to Netbeans and am finding accessing files in packages quite perplexing. Usually I would just have everything in the one folder. I have created packages in my project which is structured like so: ``` project_name ......Source Packages ............Game ............Players ............Resources ..................Levels ..................Images ``` I want to access a text file that resides in the Resources.Levels package from my Gui class which resides in my Game package. How would I do this? Ideally I want to create a String = "mapFile.txt" Thanks
2011/03/29
[ "https://Stackoverflow.com/questions/5472526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` MyClass.class.getResources("/Resources/Image/myImage.jpg"); ```
This has nothing to do with NetBeans, but everything to do with Java. To access a resource in the classpath, you should use [`Class.getResourceAsStream()`](http://download.oracle.com/javase/6/docs/api/java/lang/Class.html#getResourceAsStream%28java.lang.String%29) method. Read its documentatino carefully. In your case, you should use ``` Gui.class.getResourceAsStream("/Resources/Levels/mapFile.txt"); ``` Also, packages in Java should be in all lowercase.
47,207,671
i'm trying to segue from objective-c to swift. However when I try this using the object below I receive the following error [![enter image description here](https://i.stack.imgur.com/sF7Fu.png)](https://i.stack.imgur.com/sF7Fu.png) I don't know what i'm doing wrong, i've setup the segue on the storyboard and assigned it to the same ID, created the prepare function and the perform. ``` - (void)renderer:(id<SCNSceneRenderer>)renderer willRenderScene:(SCNScene *)scene atTime:(NSTimeInterval)time { // Look for trackables, and draw on each found one. size_t trackableCount = trackableIds.size(); for (size_t i = 0; i < trackableCount; i++) { // NSLog(@"this is the variable value: %d", trackableIds[i]); // Find the trackable for the given trackable ID. ARTrackable *trackable = arController->findTrackable(trackableIds[i]); // SCNCamera *camera = self.cameraNode.camera; SCNNode *trackableNode = self.trackableNodes[i]; if (trackable->visible) { if (trackableIds[i] == 0) { NSLog(@"Starbucks"); [self performSegueWithIdentifier:@"brandSegue" sender:self]; } else if (trackableIds[i] == 1) { NSLog(@"Dortios"); } } else { trackableNode.opacity = 0; } } } - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([segue.identifier isEqualToString:@"brandSegue"]) { JSONViewController *destViewController = segue.destinationViewController; } } ``` **EDIT - ERROR MESSAGE** ``` 2017-11-09 16:57:05.232992+0000 MyARApp[2573:1099927] *** Assertion failure in -[UIApplication _cachedSystemAnimationFenceCreatingIfNecessary:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit/UIKit-3698.21.8/UIApplication.m:1707 2017-11-09 16:57:05.233169+0000 MyARApp[2573:1099927] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'accessing _cachedSystemAnimationFence requires the main thread' *** First throw call stack: (0x186f51d04 0x1861a0528 0x186f51bd8 0x1878e1c24 0x1905e9c4c 0x19064646c 0x190432338 0x19038fe5c 0x1903fb6a8 0x190470bf0 0x1906ffb00 0x190701434 0x190703cd8 0x19070420c 0x190703c28 0x190467ab4 0x190707ae4 0x190b38854 0x190ca6b30 0x190ca69d4 0x1906f7e18 0x1020a27cc 0x19a66c610 0x19a725a84 0x19a723e00 0x19a724d1c 0x19a5a0cc4 0x19a6717ac 0x19a671b14 0x19a671f8c 0x19a71a67c 0x19a5d24a0 0x19a6e1c90 0x1035b949c 0x1035b945c 0x1035c8110 0x1035bc9a4 0x1035c9104 0x1035d0100 0x186b7afd0 0x186b7ac20) libc++abi.dylib: terminating with uncaught exception of type NSException (lldb) ```
2017/11/09
[ "https://Stackoverflow.com/questions/47207671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5034263/" ]
After discussion in Chat and fixing various issues, I'll take them one by one: ``` > *** Assertion failure in -[UIApplication _cachedSystemAnimationFenceCreatingIfNecessary:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit/UIKit-3698.21.8/UIApplication.m:1707 > *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'accessing _cachedSystemAnimationFence requires the main thread' ``` That's the first issue causing a crash. This is talking about an internal method of CocoaTouch needed to be called in main thread. The issue lies on your `performSegueWithIdentifier:sender:`. All UI related calls have to be done in main thread. To fix it: ``` dispatch_async(dispatch_get_main_queue(), ^(){ [self performSegueWithIdentifier:@"brandSegue" sender:self]; }); ``` Fixing this revealed a second issue: > > it segues but it trigger twice, do you know why this may happen? > > > You are doing this: ``` for (size_t i = 0; i < trackableCount; i++) { if (somethingTest) { [self performSegueWithIdentifier:@"brandSegue" sender:self]; } } ``` Who said that in your for loop you don't valid multiple times `somethingTest`? To fix it (I'm talking about the logic, I didn't do the `dispatch_async(dispatch_get_main_queue(){()}` part to avoid adding noise to the algorithm). ``` //Declare a var before the for loop BOOL seguedNeedsToBeDone = FALSE; for (size_t i = 0; i < trackableCount; i++) { if (somethingTest) { seguedNeedsToBeDone = TRUE; } } //Perform the segue after the for loop if needed if (seguedNeedsToBeDone) { [self performSegueWithIdentifier:@"brandSegue" sender:self]; } ``` Next issue, passing data to the Destination ViewController: ``` JSONViewController *destViewController = segue.destinationViewController; destViewController.brand = @"something"; ``` You are mixing Swift & Objective-C, since XCode was complaining about not knowing `brand` being a property of `JSONViewController` object, you needed to add `@objc` before the declaration of the var. More detailed answer can be found [here](https://stackoverflow.com/questions/45656671/unable-to-access-swift-class-from-objective-c-property-not-found-on-object-of). Finally, a tip to pass the data of you for loop is using the sender (it's faster in term of coding than creating another var, etc.): ``` //Calling the performSegue with custom value to pass [self performSegueWithIdentifier:@"brandSegue" sender:someVarToSend]; //Passing the custom value destViewController.brand = someVarToSend; ```
I guess the more safe way is to use navigationController?.pushViewController(\_:animated:), instead of using segues.
166,338
My hubby and I purchased the home in 2015. We are currently noticing cracks both inside and outside of the home. Moreover, we noticed the area had been fixed and covered up before. As I'm not a professional, I am pretty concerned about it. Please help and diagnose if I should be concerned. Thank you ahead of time! It is much appreciated. [![enter image description here](https://i.stack.imgur.com/vgusC.jpg)](https://i.stack.imgur.com/vgusC.jpg) [More pictures](https://www.dropbox.com/sh/hylu5pw58vbc4ct/AABTow6C3cOLA-C6pwUSXvXla?dl=0)
2019/05/31
[ "https://diy.stackexchange.com/questions/166338", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/102237/" ]
The short answer to the question in your Heading is: Yes, the culprit for the stucco crack is probably footing/foundation settling. But it doesn't look serious. Most building move, some more than others. Traditional stucco shows it; concrete foundations/basements show it; and even drywall shows cracks in buildings that move enough. Unfortunately, stucco seems to highlight the tell-tell signs of a building's nefarious activity for all to see. The work for many stucco contractors is primarily repairing cracks. Your stucco crack is very typical - at a window sill. Interior dry wall usually cracks at the wall board seams. You can worry and spend lots of money trying to make a building hold still, but most people just fix the cracks. Fortunately, developments in plaster/stucco/drywall have created materials that offer much more flexibility, to let the building do it thing without displaying cracks to prove it. Crack repairs tend to last longer now with the flexible materials. The art is in matching the original texture. A seasoned stucco contractor can make a long-lasting repair that blends in with its surroundings. If you want to do it yourself, there are plentiful youtube "How To" videos on the topic. Kirk Giordano has posted several good videos that apply directly the issue that you and numerous other homeowners are experiencing.
When stucco is mixed without enough sand in it the first place it's going to crack is at the corners of your windows. This does not indicated structural problem. More often than not it's a problem caused by subcontractors working for builders who build houses on spec and cut corners don't use enough material or don't properly apply the material. Some of these houses the stucco is not even a half inch thick. However, the crack in the photo above does not look good and in my opinion is more than a hairline crack. If it was my house I would be concerned. And I'd get an engineer out there quick. Also it appears there's a giant Gap around the entire window. That Gap should not be there. Water can get inside that Gap and come down behind your stucco causing cracks or allow water to seep inside your walls.
84,125
I am the proud recipient of a brand new, EMV-equipped Visa Debit card through my financial institution -- this card is capable of being used for PIN debit/EFTPOS, signature debit, and ATM transactions, at least in the North American senses of the terms. However, can such a card support EMV chip-and-PIN debit transactions for use overseas in areas where magnetic stripe PIN debit/EFTPOS is no longer supported, or is it limited to chip-and-signature for chip transactions? Note: [our question about credit cards](https://travel.stackexchange.com/questions/83913) is different because it covers North American EMV *credit* card products -- which do not support PIN debit/EFTPOS or the full panoply of ATM transactions. A Visa signature debit (Check Card) product supports not only signature debit (i.e. credit card like), but PIN debit/EFTPOS and ATM (bank card like) transactions as well. I'm concerned about *all* usage contexts (such as foreign ATMs and automated kiosks that do not have the ability to accept a chip and signature transaction), not just a card-present/manned environment where chip-and-signature fallback is an option, as well.
2016/12/11
[ "https://travel.stackexchange.com/questions/84125", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/22968/" ]
Because they think more people will pay more to fly to Flagstaff than Cancún. It's as simple as that: airlines set prices to maximize their profit. In this case, Cancun is normally thought of as a budget leisure destination. The airline knows from long experience that many vacationers headed to Cancun will simply find another place to go if the flight is too expensive. They believe travelers to Flagstaff will pay more right now. Prices may be seasonal, especially for these destinations, and are based on supply and demand. Competition also plays a role. The airline knows who flies between the cities, their prices, and how convenient their connections are, and they'll price accordingly. Multiple carriers competing aggressively on a route will typically drive prices down, while they generally remain high when few alternatives exist. And when it comes to Flagstaff, there's no competition. Flagstaff is a small airport served only by one carrier, American Eagle, with a couple of flights a day to nearby Phoenix. The airline pretty much has you over a barrel because you have only a couple of choices: pay whatever they want to go to Flagstaff, fly to Phoenix (or an even further away airport) and make your way to Flagstaff some other way, travel by a less convenient method such as a bus or trains, give up and go someplace else entirely, or give up and don't travel at all. In contrast, you can get to Cancun through connections on several different airlines. American knows this, and will happily use its monopoly over flights to Flagstaff to charge you for the convenience of flying there rather than making you drive from a farther away airport. But the real answer is that airline ticket prices don't make "sense" in the way you're trying to understand them. They cost as much as the airline thinks the market will bear in a way that maximizes their profit, not on a per-mile basis or other "logical" structure.
It is called supply and demand. There is more competition going to Cancun hence lower more competitve airfares. Less competition gping to Flagstaff.
84,125
I am the proud recipient of a brand new, EMV-equipped Visa Debit card through my financial institution -- this card is capable of being used for PIN debit/EFTPOS, signature debit, and ATM transactions, at least in the North American senses of the terms. However, can such a card support EMV chip-and-PIN debit transactions for use overseas in areas where magnetic stripe PIN debit/EFTPOS is no longer supported, or is it limited to chip-and-signature for chip transactions? Note: [our question about credit cards](https://travel.stackexchange.com/questions/83913) is different because it covers North American EMV *credit* card products -- which do not support PIN debit/EFTPOS or the full panoply of ATM transactions. A Visa signature debit (Check Card) product supports not only signature debit (i.e. credit card like), but PIN debit/EFTPOS and ATM (bank card like) transactions as well. I'm concerned about *all* usage contexts (such as foreign ATMs and automated kiosks that do not have the ability to accept a chip and signature transaction), not just a card-present/manned environment where chip-and-signature fallback is an option, as well.
2016/12/11
[ "https://travel.stackexchange.com/questions/84125", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/22968/" ]
It is called supply and demand. There is more competition going to Cancun hence lower more competitve airfares. Less competition gping to Flagstaff.
It's basically "whatever the market will bear" with some important exceptions. Fare history for the city pair plays a role and helps predict the future. A carrier new to the route may lower the fare to attract business. Flagstaff has relatively few people, and by laws of chance, there will be far fewer people going PIT-FLG than PIT-CUN. Also, it costs a carrier quite a lot to touch down anywhere, so those costs must be spread between only a few passengers. Finally, Flagstaff is at high altitude, with adverse winter weather. Both factors increase operating costs. With far lower fares, some greeters may consider a quick dash down I-17 to PHX (Phoenix) a good alternative.
84,125
I am the proud recipient of a brand new, EMV-equipped Visa Debit card through my financial institution -- this card is capable of being used for PIN debit/EFTPOS, signature debit, and ATM transactions, at least in the North American senses of the terms. However, can such a card support EMV chip-and-PIN debit transactions for use overseas in areas where magnetic stripe PIN debit/EFTPOS is no longer supported, or is it limited to chip-and-signature for chip transactions? Note: [our question about credit cards](https://travel.stackexchange.com/questions/83913) is different because it covers North American EMV *credit* card products -- which do not support PIN debit/EFTPOS or the full panoply of ATM transactions. A Visa signature debit (Check Card) product supports not only signature debit (i.e. credit card like), but PIN debit/EFTPOS and ATM (bank card like) transactions as well. I'm concerned about *all* usage contexts (such as foreign ATMs and automated kiosks that do not have the ability to accept a chip and signature transaction), not just a card-present/manned environment where chip-and-signature fallback is an option, as well.
2016/12/11
[ "https://travel.stackexchange.com/questions/84125", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/22968/" ]
Because they think more people will pay more to fly to Flagstaff than Cancún. It's as simple as that: airlines set prices to maximize their profit. In this case, Cancun is normally thought of as a budget leisure destination. The airline knows from long experience that many vacationers headed to Cancun will simply find another place to go if the flight is too expensive. They believe travelers to Flagstaff will pay more right now. Prices may be seasonal, especially for these destinations, and are based on supply and demand. Competition also plays a role. The airline knows who flies between the cities, their prices, and how convenient their connections are, and they'll price accordingly. Multiple carriers competing aggressively on a route will typically drive prices down, while they generally remain high when few alternatives exist. And when it comes to Flagstaff, there's no competition. Flagstaff is a small airport served only by one carrier, American Eagle, with a couple of flights a day to nearby Phoenix. The airline pretty much has you over a barrel because you have only a couple of choices: pay whatever they want to go to Flagstaff, fly to Phoenix (or an even further away airport) and make your way to Flagstaff some other way, travel by a less convenient method such as a bus or trains, give up and go someplace else entirely, or give up and don't travel at all. In contrast, you can get to Cancun through connections on several different airlines. American knows this, and will happily use its monopoly over flights to Flagstaff to charge you for the convenience of flying there rather than making you drive from a farther away airport. But the real answer is that airline ticket prices don't make "sense" in the way you're trying to understand them. They cost as much as the airline thinks the market will bear in a way that maximizes their profit, not on a per-mile basis or other "logical" structure.
It's basically "whatever the market will bear" with some important exceptions. Fare history for the city pair plays a role and helps predict the future. A carrier new to the route may lower the fare to attract business. Flagstaff has relatively few people, and by laws of chance, there will be far fewer people going PIT-FLG than PIT-CUN. Also, it costs a carrier quite a lot to touch down anywhere, so those costs must be spread between only a few passengers. Finally, Flagstaff is at high altitude, with adverse winter weather. Both factors increase operating costs. With far lower fares, some greeters may consider a quick dash down I-17 to PHX (Phoenix) a good alternative.
16
When I am downloading large files I need to stop my phone from sleeping , how do I keep my wi-fi on when the phone is in sleep mode.
2010/09/13
[ "https://android.stackexchange.com/questions/16", "https://android.stackexchange.com", "https://android.stackexchange.com/users/17/" ]
Go to: Settings > Wireless & networks > Wi-Fi settings. Hit your Menu button and select Advanced. You should now see an option for changing the Wi-Fi sleep policy.
For Android 4.0 (Ice Cream Sandwich) and later upto Android 5.x (Lollipop) Goto: > > Settings > Wifi > Advanced (from options menu) > Keep Wi-Fi on during sleep > Always > > > For previous versions of Android(i.e. 2.x) please consider Rohan Singh's answer.
5,131,887
The site is appearing fine in Mozilla, Chrome, and IE6. But IE7 onwards, the menu background image was not appearing at all. In the file moo.menu.css, I made the following changes in li: ``` .ry-cssmnu ul li { margin: 0; /* all list items */ padding: 0; float: left; display: block; background: url(../images/mainnav-bg.gif) repeat-x center top blue;/*added this line*/ cursor: pointer;} ``` After this, the background repeat is appearing only where the menu text is present. <http://bit.ly/ie8issue> The site is at: www.agmrcet.com/cons Thanks in advance.
2011/02/27
[ "https://Stackoverflow.com/questions/5131887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636231/" ]
You have to declare a height to that container. Your floating list items are not giving their parent container height because `float` removes them from the document flow. Your `<ul>` has a current height of nothing, and the background image won't remedy that. ``` #mainnav { height:44px; ... } ```
First of all, I would change the CSS **background** property according to the CSS syntax: ``` background: blue url(../images/mainnav-bg.gif) repeat-x center top; ```
5,131,887
The site is appearing fine in Mozilla, Chrome, and IE6. But IE7 onwards, the menu background image was not appearing at all. In the file moo.menu.css, I made the following changes in li: ``` .ry-cssmnu ul li { margin: 0; /* all list items */ padding: 0; float: left; display: block; background: url(../images/mainnav-bg.gif) repeat-x center top blue;/*added this line*/ cursor: pointer;} ``` After this, the background repeat is appearing only where the menu text is present. <http://bit.ly/ie8issue> The site is at: www.agmrcet.com/cons Thanks in advance.
2011/02/27
[ "https://Stackoverflow.com/questions/5131887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636231/" ]
You have to declare a height to that container. Your floating list items are not giving their parent container height because `float` removes them from the document flow. Your `<ul>` has a current height of nothing, and the background image won't remedy that. ``` #mainnav { height:44px; ... } ```
Looks like the problem is with your ``` <div class="clearfix" id="mainnav"> ``` tag. Have you tried adding a pink border or something (to debug it) to the mainnav element and then setting a fixed width on it to make sure it goes the full width?
19,483,230
I need some help with creating my pattern. I've got the basic parts done, but one issue remains. Let's say I have a string as follows: ``` John: I can type in :red:colour! :white:Not in the same :red:wo:green:rd :white:though :( ``` I have this code setup to separate the colors from the actual value: ``` line = "John: I can type in :red:colour! :white:Not in the same :red:wo:green:rd :white:though :(" for token in string.gmatch(line, "%s?[(%S)]+[^.]?") do for startpos, token2, endpos in string.gmatch(token, "()(%b::)()") do print(token2) token = string.gsub(token, token2, "") end print(token) end ``` Will output: ``` John: I can type in :red: colour! :white: Not in the same :red: :green: word :white: though :( ``` When I want it to print out: ``` John: I can type in :red: colour! :white: Not in the same :red: wo :green: rd :white: though :( ``` Any help would be greatly appreciated.
2013/10/20
[ "https://Stackoverflow.com/questions/19483230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1773027/" ]
The following code will give your [desired output](https://eval.in/56063): ``` for token in line:gmatch( "(%S+)" ) do if not token:match( "(:%w-:)([^:]+)" ) then print(token) else for col, w in token:gmatch( "(:%w-:)([^:]+)" ) do print( col ) print( w ) end end end ``` Though, it will fail for a string such as: ``` in the sa:yellow:me:pink:long-Words! ```
A more generic solution works: `line = "John: I can type in :red:colour! :white:Not in the same :red:wo:green:rd :white:though :("` ``` for i in string.gmatch(line ,"%S+") do if (i:match(":%w+")) then for k,r in string.gmatch(i,"(:%w+:)(%w+[^:]*)") do print(k) print(r) end else print(i) end end ``` Will also work for the string: "in the sa:yellow:me:pink:long-Words!"
58,091,429
I have a log file I am attempting to extract particular lines from. When I crop the file to a few lines above and below I am able to get it. However, there is multiple instances of what I am trying to find preventing using the FULL file. Following is some code I have tried... ``` for /f "tokens=1* delims=[]" %%a in ('find /n " <Line Text="***********TEST1 TEST TEST************" />" ^< TEST.LOG') do (set H=%%a ) for /f "tokens=1* delims=[]" %%a in ('find /n "</Report>" ^< TEST.LOG') do ( set T=%%a ) for /f "tokens=1* delims=[]" %%a in ('find /n /v "" ^< TEST.LOG') do ( if %%a GEQ !H! if %%a LEQ !T! echo.%%b )>> newfile.txt ``` I am hoping to get the following: ``` <Line Text="***********TEST1 TEST TEST************" /> ~ALL LINES IN BETWEEN~ </Report> ```
2019/09/25
[ "https://Stackoverflow.com/questions/58091429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3380038/" ]
Windows command processor designed for executing commands and executables and not for text file processing is definitely the worst choice to filter `TEST.LOG`. For the reasons read completely my answer on [How to read and print contents of text file line by line?](https://stackoverflow.com/a/51579256/3074564) The batch file code described there in detail was used as template for the batch file code below: ``` @echo off setlocal EnableExtensions DisableDelayedExpansion if not exist "Test.log" goto EndBatch set "OutputLines=" (for /F delims^=^ eol^= %%I in ('%SystemRoot%\System32\findstr.exe /N "^" "Test.log"') do ( set "Line=%%I" setlocal EnableDelayedExpansion if defined OutputLines ( echo(!Line:*:=! if not "!Line:</Report>=!" == "!Line!" ( endlocal & set "OutputLines=" ) else endlocal ) else if not "!Line:<Line Text=!" == "!Line!" ( echo(!Line:*:=! endlocal & set "OutputLines=1" ) else endlocal ))>"newfile.txt" if exist "newfile.txt" for %%I in ("newfile.txt") do if %%~zI == 0 del "newfile.txt" :EndBatch endlocal ``` This batch file writes all lines from a line containing case-insensitive the string `<Line Text` to a line containing case-insensitive the string `</Report>` or end of file from `Test.log` into file `newfile.txt`. **Note:** The search string between `!Line:` and `=` cannot contain an equal sign because of the equal sign is interpreted by Windows command processor as separator between search string, here `</Report>` and `<Line Text`, and the replace string, here twice an empty string. And an asterisk `*` at beginning of search string is interpreted by Windows command processor as order to replace everything from beginning of line to first occurrence of found string on doing the string substitution and not as character to find in the line. But this does not matter for this use case. If the two lines marking beginning and end of block to extract are fixed and do not contain any variable part, the two string comparisons could be done without string substitution making it possible to compare also strings containing an equal sign. ``` @echo off setlocal EnableExtensions DisableDelayedExpansion if not exist "Test.log" goto EndBatch set "BlockBegin= <Line Text="***********TEST1 TEST TEST************" />" set "BlockEnd= </Report>" set "OutputLines=" (for /F delims^=^ eol^= %%I in ('%SystemRoot%\System32\findstr.exe /N "^" "Test.log"') do ( set "Line=%%I" setlocal EnableDelayedExpansion if defined OutputLines ( echo(!Line:*:=! if "!Line:*:=!" == "!BlockEnd!" ( endlocal & set "OutputLines=" ) else endlocal ) else if "!Line:*:=!" == "!BlockBegin!" ( echo(!Line:*:=! endlocal & set "OutputLines=1" ) else endlocal ))>"newfile.txt" if exist "newfile.txt" for %%I in ("newfile.txt") do if %%~zI == 0 del "newfile.txt" :EndBatch endlocal ``` This variant compares each entire line case-sensitive with the strings assigned to the environment variables `BlockBegin` and `BlockEnd` to determine on which line to start and on which line to stop the output of the lines. For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully. * `del /?` * `echo /?` * `endlocal /?` * `findstr /?` * `for /?` * `goto /?` * `if /?` * `set /?` * `setlocal /?` See also: * [Single line with multiple commands using Windows batch file](https://stackoverflow.com/a/25344009/3074564) * [This answer](https://stackoverflow.com/a/38676582/3074564) for details about the commands **SETLOCAL** and **ENDLOCAL** which are needed in loop and are responsible for very inefficient processing of the lines because of lots of memory copies are additionally done in background.
You can give a try with this code : ``` @echo off Title Extract Data between two tags Set "InputFile=InputFile.txt" Set From_Start="<Line" Set To_End="</Report>" Set "OutputFile=OutputFile.txt" Call :ExtractData %InputFile% %From_Start% %To_End% Call :ExtractData %InputFile% %From_Start% %To_End%>%OutputFile% If Exist %OutputFile% Start "" %OutputFile% Exit ::'************************************************************* :ExtractData <InputFile> <From_Start> <To_End> ( echo Set fso = CreateObject^("Scripting.FileSystemObject"^) echo Set f=fso.opentextfile^("%~1",1^) echo Data = f.ReadAll echo Data = Extract(Data,"(%~2.*\r\n)([\w\W]*)(\r\n)(%~3)"^) echo WScript.StdOut.WriteLine Data echo '************************************************ echo Function Extract(Data,Pattern^) echo Dim oRE,oMatches,Match,Line echo set oRE = New RegExp echo oRE.IgnoreCase = True echo oRE.Global = True echo oRE.Pattern = Pattern echo set Matches = oRE.Execute(Data^) echo If Matches.Count ^> 0 Then Data = Matches^(0^).SubMatches^(1^) echo Extract = Data echo End Function echo '************************************************ )>"%tmp%\%~n0.vbs" cscript //nologo "%tmp%\%~n0.vbs" If Exist "%tmp%\%~n0.vbs" Del "%tmp%\%~n0.vbs" exit /b ::**************************************************** ```
58,091,429
I have a log file I am attempting to extract particular lines from. When I crop the file to a few lines above and below I am able to get it. However, there is multiple instances of what I am trying to find preventing using the FULL file. Following is some code I have tried... ``` for /f "tokens=1* delims=[]" %%a in ('find /n " <Line Text="***********TEST1 TEST TEST************" />" ^< TEST.LOG') do (set H=%%a ) for /f "tokens=1* delims=[]" %%a in ('find /n "</Report>" ^< TEST.LOG') do ( set T=%%a ) for /f "tokens=1* delims=[]" %%a in ('find /n /v "" ^< TEST.LOG') do ( if %%a GEQ !H! if %%a LEQ !T! echo.%%b )>> newfile.txt ``` I am hoping to get the following: ``` <Line Text="***********TEST1 TEST TEST************" /> ~ALL LINES IN BETWEEN~ </Report> ```
2019/09/25
[ "https://Stackoverflow.com/questions/58091429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3380038/" ]
Updated: -------- > > > > > > You want to find `<Line Text="***********TEST1 TEST TEST************" />` then print it and any line until the First `</Report>` is encountered, then look for the next `<Line Text="***********TEST1 TEST TEST************" />` and print it and every following line until the next `</Report>` for every time it occurs throughout? > > > > > > > > > – Ben Personick 1 hour ago > > > > > > > OR do you just want to take from the first `<Line Text="***********TEST1 TEST TEST************" />` to the first `</Report>`? > > > > > > > > > – Ben Personick 1 hour ago > > > > > > > Find `<Line Text="***********TEST1 TEST TEST************" />` then print it and any line until the First `</Report>` is encountered, then look fo rthe next `<Line Text="***********TEST1 TEST TEST************" />` and print it and every followinng line until the next `</Report>` for every time it occurs. I feel there should ONLY be 1 sequence, however, at times this situation could very well be possible. Thanks for asking, very solid question! > > > > > > > > > – T-Diddy 1 hour ago > > > Okay, this should work the way you expect then, **however, if there are a lot of unexpected characters it might make more sense to amend how the lines are being outputted** to use `SET` instead of echo. ``` @(setlocal ECHO OFF SET "_LogFile=C:\Admin\TestLog.log" SET "_ResultFile=C:\Admin\TestLog.txt" SET "_MatchString_Begin=<Line Text="***********AAAAA BBBB CCCC************" />" SET "_MatchString_End=</Report>" SET "_Line#_Begin=" ) CALL :Main ( ENDLOCAL EXIT/B ) :Main IF EXIST "%_ResultFile%" ( DEL /F /Q "%_ResultFile%" ) ECHO.&ECHO.== Processing ==&ECHO. FOR /F "Delims=[]" %%# IN (' Find /N "%_MatchString_Begin:"=""%" "%_LogFile%" ^| FIND "[" ') DO ( ECHO. Found Match On Line %%# SET /A "_Line#_Begin=%%#-1" CALL :Output ) ECHO.&ECHO.== Completed ==&ECHO.&ECHO.Results to Screen will Start in 5 Seconds: timeout 5 Type "%_ResultFile%" GOTO :EOF :Output FOR /F "SKIP=%_Line#_Begin% Tokens=* usebackq" %%_ IN ( "%_LogFile%" ) DO ( ECHO(%%_ ECHO("%%_" | FIND /I "%_MatchString_End%" >NUL&&( GOTO :EOF ) )>>"%_ResultFile%" GOTO :EOF ``` Original Response Only Shows First Matched Content, based on this Comment: -------------------------------------------------------------------------- > > This works great with my "cropped" file. However, in the ORIGINAL, ONLY unique line I have is `<Line Text="***********AAAAA BBBB CCCC************" />`. I can't seem to be able to use the full line as my batch just exits out, but am able to input "`***********AAAAA BBBB CCCC************`" and does not kick my batch out, however, exists elsewhere. Thus, requiring the other parameters as it is unique within the file. and I want the next following: in sequence. Otherwise this "`</Report>`" exists above in another section I don't want and believe is causing issue. – T-Diddy 3 mins ago > > > Okay, I thought so. Try this: ``` @(setlocal ECHO OFF SET "_LogFile=C:\Admin\TestLog.log" SET "_MatchString_Begin=<Line Text="***********AAAAA BBBB CCCC************" />" SET "_MatchString_End=</Report>" SET "_Line#_Begin=" SET "_Line#_End=" ) REM SET FOR /F "Delims=[]" %%# IN (' Find /N "%_MatchString_Begin:"=""%" "%_LogFile%" ^| FIND "[" ') DO ( IF NOT DEFINED _Line#_Begin ( SET /A "_Line#_Begin=%%#-1" ECHO.SET /A "_Line#_Begin=%%#-1" ) ) FOR /F "SKIP=%_Line#_Begin% Tokens=* usebackq" %%_ IN ( "%_LogFile%" ) DO ( IF NOT DEFINED _Line#_End ( ECHO(%%_ ECHO("%%_" | FIND /I "%_MatchString_End%" &&( SET "_Line#_End=1" ) ) ) PAUSE ```
Windows command processor designed for executing commands and executables and not for text file processing is definitely the worst choice to filter `TEST.LOG`. For the reasons read completely my answer on [How to read and print contents of text file line by line?](https://stackoverflow.com/a/51579256/3074564) The batch file code described there in detail was used as template for the batch file code below: ``` @echo off setlocal EnableExtensions DisableDelayedExpansion if not exist "Test.log" goto EndBatch set "OutputLines=" (for /F delims^=^ eol^= %%I in ('%SystemRoot%\System32\findstr.exe /N "^" "Test.log"') do ( set "Line=%%I" setlocal EnableDelayedExpansion if defined OutputLines ( echo(!Line:*:=! if not "!Line:</Report>=!" == "!Line!" ( endlocal & set "OutputLines=" ) else endlocal ) else if not "!Line:<Line Text=!" == "!Line!" ( echo(!Line:*:=! endlocal & set "OutputLines=1" ) else endlocal ))>"newfile.txt" if exist "newfile.txt" for %%I in ("newfile.txt") do if %%~zI == 0 del "newfile.txt" :EndBatch endlocal ``` This batch file writes all lines from a line containing case-insensitive the string `<Line Text` to a line containing case-insensitive the string `</Report>` or end of file from `Test.log` into file `newfile.txt`. **Note:** The search string between `!Line:` and `=` cannot contain an equal sign because of the equal sign is interpreted by Windows command processor as separator between search string, here `</Report>` and `<Line Text`, and the replace string, here twice an empty string. And an asterisk `*` at beginning of search string is interpreted by Windows command processor as order to replace everything from beginning of line to first occurrence of found string on doing the string substitution and not as character to find in the line. But this does not matter for this use case. If the two lines marking beginning and end of block to extract are fixed and do not contain any variable part, the two string comparisons could be done without string substitution making it possible to compare also strings containing an equal sign. ``` @echo off setlocal EnableExtensions DisableDelayedExpansion if not exist "Test.log" goto EndBatch set "BlockBegin= <Line Text="***********TEST1 TEST TEST************" />" set "BlockEnd= </Report>" set "OutputLines=" (for /F delims^=^ eol^= %%I in ('%SystemRoot%\System32\findstr.exe /N "^" "Test.log"') do ( set "Line=%%I" setlocal EnableDelayedExpansion if defined OutputLines ( echo(!Line:*:=! if "!Line:*:=!" == "!BlockEnd!" ( endlocal & set "OutputLines=" ) else endlocal ) else if "!Line:*:=!" == "!BlockBegin!" ( echo(!Line:*:=! endlocal & set "OutputLines=1" ) else endlocal ))>"newfile.txt" if exist "newfile.txt" for %%I in ("newfile.txt") do if %%~zI == 0 del "newfile.txt" :EndBatch endlocal ``` This variant compares each entire line case-sensitive with the strings assigned to the environment variables `BlockBegin` and `BlockEnd` to determine on which line to start and on which line to stop the output of the lines. For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully. * `del /?` * `echo /?` * `endlocal /?` * `findstr /?` * `for /?` * `goto /?` * `if /?` * `set /?` * `setlocal /?` See also: * [Single line with multiple commands using Windows batch file](https://stackoverflow.com/a/25344009/3074564) * [This answer](https://stackoverflow.com/a/38676582/3074564) for details about the commands **SETLOCAL** and **ENDLOCAL** which are needed in loop and are responsible for very inefficient processing of the lines because of lots of memory copies are additionally done in background.
58,091,429
I have a log file I am attempting to extract particular lines from. When I crop the file to a few lines above and below I am able to get it. However, there is multiple instances of what I am trying to find preventing using the FULL file. Following is some code I have tried... ``` for /f "tokens=1* delims=[]" %%a in ('find /n " <Line Text="***********TEST1 TEST TEST************" />" ^< TEST.LOG') do (set H=%%a ) for /f "tokens=1* delims=[]" %%a in ('find /n "</Report>" ^< TEST.LOG') do ( set T=%%a ) for /f "tokens=1* delims=[]" %%a in ('find /n /v "" ^< TEST.LOG') do ( if %%a GEQ !H! if %%a LEQ !T! echo.%%b )>> newfile.txt ``` I am hoping to get the following: ``` <Line Text="***********TEST1 TEST TEST************" /> ~ALL LINES IN BETWEEN~ </Report> ```
2019/09/25
[ "https://Stackoverflow.com/questions/58091429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3380038/" ]
Updated: -------- > > > > > > You want to find `<Line Text="***********TEST1 TEST TEST************" />` then print it and any line until the First `</Report>` is encountered, then look for the next `<Line Text="***********TEST1 TEST TEST************" />` and print it and every following line until the next `</Report>` for every time it occurs throughout? > > > > > > > > > – Ben Personick 1 hour ago > > > > > > > OR do you just want to take from the first `<Line Text="***********TEST1 TEST TEST************" />` to the first `</Report>`? > > > > > > > > > – Ben Personick 1 hour ago > > > > > > > Find `<Line Text="***********TEST1 TEST TEST************" />` then print it and any line until the First `</Report>` is encountered, then look fo rthe next `<Line Text="***********TEST1 TEST TEST************" />` and print it and every followinng line until the next `</Report>` for every time it occurs. I feel there should ONLY be 1 sequence, however, at times this situation could very well be possible. Thanks for asking, very solid question! > > > > > > > > > – T-Diddy 1 hour ago > > > Okay, this should work the way you expect then, **however, if there are a lot of unexpected characters it might make more sense to amend how the lines are being outputted** to use `SET` instead of echo. ``` @(setlocal ECHO OFF SET "_LogFile=C:\Admin\TestLog.log" SET "_ResultFile=C:\Admin\TestLog.txt" SET "_MatchString_Begin=<Line Text="***********AAAAA BBBB CCCC************" />" SET "_MatchString_End=</Report>" SET "_Line#_Begin=" ) CALL :Main ( ENDLOCAL EXIT/B ) :Main IF EXIST "%_ResultFile%" ( DEL /F /Q "%_ResultFile%" ) ECHO.&ECHO.== Processing ==&ECHO. FOR /F "Delims=[]" %%# IN (' Find /N "%_MatchString_Begin:"=""%" "%_LogFile%" ^| FIND "[" ') DO ( ECHO. Found Match On Line %%# SET /A "_Line#_Begin=%%#-1" CALL :Output ) ECHO.&ECHO.== Completed ==&ECHO.&ECHO.Results to Screen will Start in 5 Seconds: timeout 5 Type "%_ResultFile%" GOTO :EOF :Output FOR /F "SKIP=%_Line#_Begin% Tokens=* usebackq" %%_ IN ( "%_LogFile%" ) DO ( ECHO(%%_ ECHO("%%_" | FIND /I "%_MatchString_End%" >NUL&&( GOTO :EOF ) )>>"%_ResultFile%" GOTO :EOF ``` Original Response Only Shows First Matched Content, based on this Comment: -------------------------------------------------------------------------- > > This works great with my "cropped" file. However, in the ORIGINAL, ONLY unique line I have is `<Line Text="***********AAAAA BBBB CCCC************" />`. I can't seem to be able to use the full line as my batch just exits out, but am able to input "`***********AAAAA BBBB CCCC************`" and does not kick my batch out, however, exists elsewhere. Thus, requiring the other parameters as it is unique within the file. and I want the next following: in sequence. Otherwise this "`</Report>`" exists above in another section I don't want and believe is causing issue. – T-Diddy 3 mins ago > > > Okay, I thought so. Try this: ``` @(setlocal ECHO OFF SET "_LogFile=C:\Admin\TestLog.log" SET "_MatchString_Begin=<Line Text="***********AAAAA BBBB CCCC************" />" SET "_MatchString_End=</Report>" SET "_Line#_Begin=" SET "_Line#_End=" ) REM SET FOR /F "Delims=[]" %%# IN (' Find /N "%_MatchString_Begin:"=""%" "%_LogFile%" ^| FIND "[" ') DO ( IF NOT DEFINED _Line#_Begin ( SET /A "_Line#_Begin=%%#-1" ECHO.SET /A "_Line#_Begin=%%#-1" ) ) FOR /F "SKIP=%_Line#_Begin% Tokens=* usebackq" %%_ IN ( "%_LogFile%" ) DO ( IF NOT DEFINED _Line#_End ( ECHO(%%_ ECHO("%%_" | FIND /I "%_MatchString_End%" &&( SET "_Line#_End=1" ) ) ) PAUSE ```
You can give a try with this code : ``` @echo off Title Extract Data between two tags Set "InputFile=InputFile.txt" Set From_Start="<Line" Set To_End="</Report>" Set "OutputFile=OutputFile.txt" Call :ExtractData %InputFile% %From_Start% %To_End% Call :ExtractData %InputFile% %From_Start% %To_End%>%OutputFile% If Exist %OutputFile% Start "" %OutputFile% Exit ::'************************************************************* :ExtractData <InputFile> <From_Start> <To_End> ( echo Set fso = CreateObject^("Scripting.FileSystemObject"^) echo Set f=fso.opentextfile^("%~1",1^) echo Data = f.ReadAll echo Data = Extract(Data,"(%~2.*\r\n)([\w\W]*)(\r\n)(%~3)"^) echo WScript.StdOut.WriteLine Data echo '************************************************ echo Function Extract(Data,Pattern^) echo Dim oRE,oMatches,Match,Line echo set oRE = New RegExp echo oRE.IgnoreCase = True echo oRE.Global = True echo oRE.Pattern = Pattern echo set Matches = oRE.Execute(Data^) echo If Matches.Count ^> 0 Then Data = Matches^(0^).SubMatches^(1^) echo Extract = Data echo End Function echo '************************************************ )>"%tmp%\%~n0.vbs" cscript //nologo "%tmp%\%~n0.vbs" If Exist "%tmp%\%~n0.vbs" Del "%tmp%\%~n0.vbs" exit /b ::**************************************************** ```
179,571
For example, if a client submits a file to a server, and the server opens the file in read-mode with Python: ``` with open(uploaded_file, "r") as f: # Do something ``` Could the act of opening a file be abused with a cleverly-crafted file from the client? Does it depend on the language used by the server?
2018/02/11
[ "https://security.stackexchange.com/questions/179571", "https://security.stackexchange.com", "https://security.stackexchange.com/users/170466/" ]
No. If the filename is controlled by the user, then you might open yourself up to vulnerabilities (e.g. an attacker might try to read config files with the database password). But just opening a file handle for an uploaded file can't do much. Perhaps if the underlying mechanism would try to read the whole file for buffering purposes, it might fill up RAM and crash the process, but Python doesn't do that: to read the whole file, you would first have to call `f.read()` -- but that is just what you do with it, and not opening the file. Only opening the file is harmless.
Operating systems generally have a limited number of files they can open at once (specifically, a limited number of file descriptors or `fd`s in Unix-like systems, or `HANDLE`s in Windows). If you allow people to open an arbitrary number of those without closing them, then it might be possible to deplete that limit, which would prevent the OS from opening more files and probably cause it to misbehave or even crash. It would be hard to exploit it for anything more than denial of service, though. Also, programs may have quotas (lower than the system limit) of how many files they can open, so a single misbehaving program couldn't do too much, and all of a process' files are released when the process exits so normally it's easy enough to restore function (indeed, most programs would crash themselves before long). Still, if you're letting people tell your server to open a file, it would be a good idea to have a limit on how many can be open at once, and close the file (automatically, if the user doesn't instruct it to happen first) after as short a time as possible. Another risk could be opening up network connections, depending on what OS you're running on and what path types it accepts. For example, if the system accepts Windows networking style paths (`\\server\share\path\to\file`) or SMB (the Windows networking protocol, implemented on Unix-likes in the Samba toolkit) paths (`smb://server/share/path`), or other ways to access any kind of network file system that isn't yet mounted (or "mapped" to use the old Windows term) to the local file system, that could cause your server to open a network connection to an attacker's box and possibly try to authenticate. This might reveal info about the server, and could provide a vector for attackers to try to compromise the server via malicious responses. So, you should also restrict file names to things you can be really sure aren't remote paths. In general, you should probably avoid letting paths be specified at all; just allow file names only. Those are the only two risks I can think of, though. Otherwise, it's pretty safe.
179,571
For example, if a client submits a file to a server, and the server opens the file in read-mode with Python: ``` with open(uploaded_file, "r") as f: # Do something ``` Could the act of opening a file be abused with a cleverly-crafted file from the client? Does it depend on the language used by the server?
2018/02/11
[ "https://security.stackexchange.com/questions/179571", "https://security.stackexchange.com", "https://security.stackexchange.com/users/170466/" ]
No. If the filename is controlled by the user, then you might open yourself up to vulnerabilities (e.g. an attacker might try to read config files with the database password). But just opening a file handle for an uploaded file can't do much. Perhaps if the underlying mechanism would try to read the whole file for buffering purposes, it might fill up RAM and crash the process, but Python doesn't do that: to read the whole file, you would first have to call `f.read()` -- but that is just what you do with it, and not opening the file. Only opening the file is harmless.
**Not the act of opening, but the act of reading (in text mode).** The `open()` function falls back on several defaults when you don't specify the parameters. This is what the code snippet you provided does: * Opens the file in text mode (no "b" in mode flags). * Calls `locale.getpreferredencoding(False)` to determine which decoder to use (no `encoding` specified). * Configures the decoder to throw exceptions when it encounters an error (no `errors` specified). Now, say you want to actually `# Do something` like read from the file, e.g. with `f.readline()`. This is what happens: 1. Binary data is read from the file. 2. **The decoder interprets the bytes in order to turn them into a Python string.** * If it encounters an invalid byte sequence, it raises a ValueError. 3. Newline sequences are substituted. Even if you remember to handle the ValueError, there is still some risk. Decoders can have rather complicated logic, so it is very possible for them to have vulnerabilities that are triggered by a cleverly crafted sequence of bytes. For example, at one point a [problem in the decoder used by the language Go](https://nvd.nist.gov/vuln/detail/CVE-2020-14040) made it possible to send it into an infinite loop. This only happens because the file is opened in text mode. If you open it in binary mode ("rb") instead, you can safely read the raw bytes from it.
19,570,774
This is a program that stores 10 unique strings. If the user enters a string that already exists in the array, the user will get an error. My code is working perfectly for the first string that I enter, but throws an exception after that and I don't know why. How do I fix this and make it work? P.S. I don't want to use a Set. I want to do it with an array. Edit: Error name: Exception in thread "main" java.lang.NullPointerException Java Result: 1 Thanks. ``` public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); int stringNumber = 0; String[] stringArray = new String[10]; for (int i = 0; i <= stringArray.length; i++) { boolean itemExists = false; out.println("\nEnter a string"); String input = keyboard.next(); if (i > 0) { for (int j = 0; j < stringArray.length; j++) { if (stringArray[j].equalsIgnoreCase(input)) { itemExists = true; out.println("Item \"" + input + "\" already exists."); break; } else { continue; // Unhandled exception error. If I don't have "continue" here, the program doesn't work properly after the first number. } } } if (itemExists == false) { stringArray[stringNumber] = input; out.println("\"" + stringArray[stringNumber] + "\"" + " has been stored."); } else { out.println("Try again."); } PrintArray(stringArray); stringNumber++; } } public static void PrintArray(String[] stringArray) { for (int i = 0; i <= 9; i++) { if (stringArray[i] == null) { out.print(" "); } else { out.print("\nYour strings:"); out.print(" " +stringArray[i] + " "); } } } ```
2013/10/24
[ "https://Stackoverflow.com/questions/19570774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915567/" ]
you problem is this `if (stringArray[j].equalsIgnoreCase(input)) {`, you refern to null element as you array do not contain nothing. You can solve this `if (input.equalsIgnoreCase(stringArray[j])) {` Now you compare the value agains the array items that may be null. Check the example code ``` private final static Scanner keyboard = new Scanner(System.in); private final static String[] stringArray = new String[10]; public static void main(String[] args) { int stringNumber = 0; for (int i = 0; i < stringArray.length; i++) { System.out.println("\nEnter a string"); String input = readNextItem(); if(isInputExist(input)) { System.out.println("Item \"" + input + "\" already exists."); System.out.println("Try again."); } else { stringArray[stringNumber++] = input; System.out.println("\"" + input + "\"" + " has been stored."); } printArray(stringArray); } } private static String readNextItem() { return keyboard.next(); } private static boolean isInputExist(String input) { for(String stored : stringArray) { if(input.equalsIgnoreCase(stored)) { return true; } } return false; } ```
You're getting the NullPointerException because you're accessing an empty array. In the second loop you're looping over the entire stringArray array but you've inserted the first i elements. Change this: ``` for (int j = 0; j < stringArray.length; j++) { ``` with this: ``` for (int j = 0; j < i; j++) { ``` P.s. I suggest you to use a Set instead of the array. Here a version with Set: ``` int numStrings = 10; Set<String> inserted = new HashSet<String>(); while(inserted.size()<=numStrings) { out.println("\nEnter a string"); String input = keyboard.next(); if (inserted.contains(input)) { out.println("Item \"" + input + "\" already exists."); out.println("Try again."); } else { inserted.add(input); out.println("\"" + input + "\"" + " has been stored."); } } out.println(inserted); ```
19,570,774
This is a program that stores 10 unique strings. If the user enters a string that already exists in the array, the user will get an error. My code is working perfectly for the first string that I enter, but throws an exception after that and I don't know why. How do I fix this and make it work? P.S. I don't want to use a Set. I want to do it with an array. Edit: Error name: Exception in thread "main" java.lang.NullPointerException Java Result: 1 Thanks. ``` public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); int stringNumber = 0; String[] stringArray = new String[10]; for (int i = 0; i <= stringArray.length; i++) { boolean itemExists = false; out.println("\nEnter a string"); String input = keyboard.next(); if (i > 0) { for (int j = 0; j < stringArray.length; j++) { if (stringArray[j].equalsIgnoreCase(input)) { itemExists = true; out.println("Item \"" + input + "\" already exists."); break; } else { continue; // Unhandled exception error. If I don't have "continue" here, the program doesn't work properly after the first number. } } } if (itemExists == false) { stringArray[stringNumber] = input; out.println("\"" + stringArray[stringNumber] + "\"" + " has been stored."); } else { out.println("Try again."); } PrintArray(stringArray); stringNumber++; } } public static void PrintArray(String[] stringArray) { for (int i = 0; i <= 9; i++) { if (stringArray[i] == null) { out.print(" "); } else { out.print("\nYour strings:"); out.print(" " +stringArray[i] + " "); } } } ```
2013/10/24
[ "https://Stackoverflow.com/questions/19570774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915567/" ]
you problem is this `if (stringArray[j].equalsIgnoreCase(input)) {`, you refern to null element as you array do not contain nothing. You can solve this `if (input.equalsIgnoreCase(stringArray[j])) {` Now you compare the value agains the array items that may be null. Check the example code ``` private final static Scanner keyboard = new Scanner(System.in); private final static String[] stringArray = new String[10]; public static void main(String[] args) { int stringNumber = 0; for (int i = 0; i < stringArray.length; i++) { System.out.println("\nEnter a string"); String input = readNextItem(); if(isInputExist(input)) { System.out.println("Item \"" + input + "\" already exists."); System.out.println("Try again."); } else { stringArray[stringNumber++] = input; System.out.println("\"" + input + "\"" + " has been stored."); } printArray(stringArray); } } private static String readNextItem() { return keyboard.next(); } private static boolean isInputExist(String input) { for(String stored : stringArray) { if(input.equalsIgnoreCase(stored)) { return true; } } return false; } ```
The problem is this inner loop: ``` for (int j = 0; j < stringArray.length; j++) { if (stringArray[j].equalsIgnoreCase(input)) { itemExists = true; out.println("Item \"" + input + "\" already exists."); break; } else { continue; // Unhandled exception error. If I don't have "continue" here, the program doesn't work properly after the first number. } } ``` Its not the *continue* statement that causes the problem, its that you invoke ``` stringArray[j].equalsIgnoreCase(input) ``` in the if - stringArray[j] isn't yet filled with a String, it will cause the NullPointerException. You can just reverse the expression: ``` input.equalsIgnoreCase(stringArray[j]) ``` (That is assuming "input" is never NULL)
1,004,699
I have a requirement to document the assembly dependencies in a vb6/dotnet application. What techniques / tools are good for performing this sort of document. I was planning on using Visio for drawing.
2009/06/17
[ "https://Stackoverflow.com/questions/1004699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490/" ]
As a start, try [Dependency Visualizer](http://www.codeplex.com/dependencyvisualizer). I've also used [GraphViz's Dot](http://www.graphviz.org) and some custom code for simple dependency generation. The custom code invoked SysInternal's depends.exe recursively and parsed the output. [.NET Reflector](http://www.red-gate.com/products/reflector/index.htm) with the [Graph](http://reflectoraddins.codeplex.com/Wiki/View.aspx?title=Graph) plugin looks pretty promising, too, though I haven't tried that (yet). What I've always run into was the fact that my graph, unless generated automatically, has to be recreated every time I add to the project and sometimes when I simply change something. So, for me, a manual solution that I became married to for the updates was no solution at all. I just found the [Dependency Structure Matrix Plug-in](http://tcdev.free.fr/) for .NET Reflector.
Well for .NET you could also try VS2010 Beta 1 and the Architecture Explorer [(Arch Explorer screen shots)](http://ajdotnet.wordpress.com/2009/03/29/visual-studio-2010-architecture-edition/). As for VB6, I'd like to have a tool for that also. This tool from Microsoft [Visual Basic 6.0 to Visual Basic .NET Upgrade Assessment Tool](http://www.microsoft.com/downloads/details.aspx?FamilyId=10C491A2-FC67-4509-BC10-60C5C039A272&displaylang=en) creates a call graph in HTML for a single VBP, not sure how useful it would for you. Other than that I have not found may tools for VB6.
1,004,699
I have a requirement to document the assembly dependencies in a vb6/dotnet application. What techniques / tools are good for performing this sort of document. I was planning on using Visio for drawing.
2009/06/17
[ "https://Stackoverflow.com/questions/1004699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490/" ]
Have you had a look at [NDepend](http://www.ndepend.com/)?
You can create dependency graphs of .NET assemblies and application projects in VS 2010 Ultimate. You can generate assembly dependency graphs as one of the standard graphs, or you can use Architecture Explorer to browse your solution, select projects and the relationships that you want to visualize, and then create a dependency graph from your selection. For more info, see the following topics: **How to: Generate Graph Documents from Code**: <http://msdn.microsoft.com/en-us/library/dd409453%28VS.100%29.aspx#SeeSpecificSource> **How to: Find Code Using Architecture Explorer**: <http://msdn.microsoft.com/en-us/library/dd409431%28VS.100%29.aspx> **RC download**: <http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=457bab91-5eb2-4b36-b0f4-d6f34683c62a>. **Visual Studio 2010 Architectural Discovery & Modeling Tools** forum: <http://social.msdn.microsoft.com/Forums/en-US/vsarch/threads>
1,004,699
I have a requirement to document the assembly dependencies in a vb6/dotnet application. What techniques / tools are good for performing this sort of document. I was planning on using Visio for drawing.
2009/06/17
[ "https://Stackoverflow.com/questions/1004699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490/" ]
You can create dependency graphs of .NET assemblies and application projects in VS 2010 Ultimate. You can generate assembly dependency graphs as one of the standard graphs, or you can use Architecture Explorer to browse your solution, select projects and the relationships that you want to visualize, and then create a dependency graph from your selection. For more info, see the following topics: **How to: Generate Graph Documents from Code**: <http://msdn.microsoft.com/en-us/library/dd409453%28VS.100%29.aspx#SeeSpecificSource> **How to: Find Code Using Architecture Explorer**: <http://msdn.microsoft.com/en-us/library/dd409431%28VS.100%29.aspx> **RC download**: <http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=457bab91-5eb2-4b36-b0f4-d6f34683c62a>. **Visual Studio 2010 Architectural Discovery & Modeling Tools** forum: <http://social.msdn.microsoft.com/Forums/en-US/vsarch/threads>
Dependency visualizer is good for small projects. For projects or solutions with many inter dependencies it becomes too clumsy to even trace the dependency graph.
1,004,699
I have a requirement to document the assembly dependencies in a vb6/dotnet application. What techniques / tools are good for performing this sort of document. I was planning on using Visio for drawing.
2009/06/17
[ "https://Stackoverflow.com/questions/1004699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490/" ]
As a start, try [Dependency Visualizer](http://www.codeplex.com/dependencyvisualizer). I've also used [GraphViz's Dot](http://www.graphviz.org) and some custom code for simple dependency generation. The custom code invoked SysInternal's depends.exe recursively and parsed the output. [.NET Reflector](http://www.red-gate.com/products/reflector/index.htm) with the [Graph](http://reflectoraddins.codeplex.com/Wiki/View.aspx?title=Graph) plugin looks pretty promising, too, though I haven't tried that (yet). What I've always run into was the fact that my graph, unless generated automatically, has to be recreated every time I add to the project and sometimes when I simply change something. So, for me, a manual solution that I became married to for the updates was no solution at all. I just found the [Dependency Structure Matrix Plug-in](http://tcdev.free.fr/) for .NET Reflector.
You can create dependency graphs of .NET assemblies and application projects in VS 2010 Ultimate. You can generate assembly dependency graphs as one of the standard graphs, or you can use Architecture Explorer to browse your solution, select projects and the relationships that you want to visualize, and then create a dependency graph from your selection. For more info, see the following topics: **How to: Generate Graph Documents from Code**: <http://msdn.microsoft.com/en-us/library/dd409453%28VS.100%29.aspx#SeeSpecificSource> **How to: Find Code Using Architecture Explorer**: <http://msdn.microsoft.com/en-us/library/dd409431%28VS.100%29.aspx> **RC download**: <http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=457bab91-5eb2-4b36-b0f4-d6f34683c62a>. **Visual Studio 2010 Architectural Discovery & Modeling Tools** forum: <http://social.msdn.microsoft.com/Forums/en-US/vsarch/threads>
1,004,699
I have a requirement to document the assembly dependencies in a vb6/dotnet application. What techniques / tools are good for performing this sort of document. I was planning on using Visio for drawing.
2009/06/17
[ "https://Stackoverflow.com/questions/1004699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490/" ]
Have you had a look at [NDepend](http://www.ndepend.com/)?
Dependency visualizer is good for small projects. For projects or solutions with many inter dependencies it becomes too clumsy to even trace the dependency graph.
1,004,699
I have a requirement to document the assembly dependencies in a vb6/dotnet application. What techniques / tools are good for performing this sort of document. I was planning on using Visio for drawing.
2009/06/17
[ "https://Stackoverflow.com/questions/1004699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490/" ]
As a start, try [Dependency Visualizer](http://www.codeplex.com/dependencyvisualizer). I've also used [GraphViz's Dot](http://www.graphviz.org) and some custom code for simple dependency generation. The custom code invoked SysInternal's depends.exe recursively and parsed the output. [.NET Reflector](http://www.red-gate.com/products/reflector/index.htm) with the [Graph](http://reflectoraddins.codeplex.com/Wiki/View.aspx?title=Graph) plugin looks pretty promising, too, though I haven't tried that (yet). What I've always run into was the fact that my graph, unless generated automatically, has to be recreated every time I add to the project and sometimes when I simply change something. So, for me, a manual solution that I became married to for the updates was no solution at all. I just found the [Dependency Structure Matrix Plug-in](http://tcdev.free.fr/) for .NET Reflector.
Dependency visualizer is good for small projects. For projects or solutions with many inter dependencies it becomes too clumsy to even trace the dependency graph.
1,004,699
I have a requirement to document the assembly dependencies in a vb6/dotnet application. What techniques / tools are good for performing this sort of document. I was planning on using Visio for drawing.
2009/06/17
[ "https://Stackoverflow.com/questions/1004699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490/" ]
Have you had a look at [NDepend](http://www.ndepend.com/)?
To complete the Eric answer, NDepend comes indeed with a [dependency graph](http://www.ndepend.com/Doc_VS_Arch.aspx) coupled with a [dependency matrix](http://www.ndepend.com/Doc_Matrix.aspx). ![NDepend Dependency Graph](https://i.stack.imgur.com/ETJHB.png) ![NDepend Dependency Matrix](https://i.stack.imgur.com/Fpr6t.png) The dependency Graph is easier to understand, but when the number of nodes grow (> 40) often the dependency Matrix will provide a clearer view of the situation. For example, below the Matrix represents the same dependency data than the Graph, but it is obviously clearer. ![Dependency Matrix vs. Dependency Graph](https://i.stack.imgur.com/OWXl8.jpg)
1,004,699
I have a requirement to document the assembly dependencies in a vb6/dotnet application. What techniques / tools are good for performing this sort of document. I was planning on using Visio for drawing.
2009/06/17
[ "https://Stackoverflow.com/questions/1004699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490/" ]
To complete the Eric answer, NDepend comes indeed with a [dependency graph](http://www.ndepend.com/Doc_VS_Arch.aspx) coupled with a [dependency matrix](http://www.ndepend.com/Doc_Matrix.aspx). ![NDepend Dependency Graph](https://i.stack.imgur.com/ETJHB.png) ![NDepend Dependency Matrix](https://i.stack.imgur.com/Fpr6t.png) The dependency Graph is easier to understand, but when the number of nodes grow (> 40) often the dependency Matrix will provide a clearer view of the situation. For example, below the Matrix represents the same dependency data than the Graph, but it is obviously clearer. ![Dependency Matrix vs. Dependency Graph](https://i.stack.imgur.com/OWXl8.jpg)
Dependency visualizer is good for small projects. For projects or solutions with many inter dependencies it becomes too clumsy to even trace the dependency graph.
1,004,699
I have a requirement to document the assembly dependencies in a vb6/dotnet application. What techniques / tools are good for performing this sort of document. I was planning on using Visio for drawing.
2009/06/17
[ "https://Stackoverflow.com/questions/1004699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490/" ]
Well for .NET you could also try VS2010 Beta 1 and the Architecture Explorer [(Arch Explorer screen shots)](http://ajdotnet.wordpress.com/2009/03/29/visual-studio-2010-architecture-edition/). As for VB6, I'd like to have a tool for that also. This tool from Microsoft [Visual Basic 6.0 to Visual Basic .NET Upgrade Assessment Tool](http://www.microsoft.com/downloads/details.aspx?FamilyId=10C491A2-FC67-4509-BC10-60C5C039A272&displaylang=en) creates a call graph in HTML for a single VBP, not sure how useful it would for you. Other than that I have not found may tools for VB6.
You can create dependency graphs of .NET assemblies and application projects in VS 2010 Ultimate. You can generate assembly dependency graphs as one of the standard graphs, or you can use Architecture Explorer to browse your solution, select projects and the relationships that you want to visualize, and then create a dependency graph from your selection. For more info, see the following topics: **How to: Generate Graph Documents from Code**: <http://msdn.microsoft.com/en-us/library/dd409453%28VS.100%29.aspx#SeeSpecificSource> **How to: Find Code Using Architecture Explorer**: <http://msdn.microsoft.com/en-us/library/dd409431%28VS.100%29.aspx> **RC download**: <http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=457bab91-5eb2-4b36-b0f4-d6f34683c62a>. **Visual Studio 2010 Architectural Discovery & Modeling Tools** forum: <http://social.msdn.microsoft.com/Forums/en-US/vsarch/threads>
1,004,699
I have a requirement to document the assembly dependencies in a vb6/dotnet application. What techniques / tools are good for performing this sort of document. I was planning on using Visio for drawing.
2009/06/17
[ "https://Stackoverflow.com/questions/1004699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490/" ]
As a start, try [Dependency Visualizer](http://www.codeplex.com/dependencyvisualizer). I've also used [GraphViz's Dot](http://www.graphviz.org) and some custom code for simple dependency generation. The custom code invoked SysInternal's depends.exe recursively and parsed the output. [.NET Reflector](http://www.red-gate.com/products/reflector/index.htm) with the [Graph](http://reflectoraddins.codeplex.com/Wiki/View.aspx?title=Graph) plugin looks pretty promising, too, though I haven't tried that (yet). What I've always run into was the fact that my graph, unless generated automatically, has to be recreated every time I add to the project and sometimes when I simply change something. So, for me, a manual solution that I became married to for the updates was no solution at all. I just found the [Dependency Structure Matrix Plug-in](http://tcdev.free.fr/) for .NET Reflector.
Have you had a look at [NDepend](http://www.ndepend.com/)?
1,696,791
Assume $|f(z)|\leq 1/|y|$ for all $z\in\mathbb{C}$. Here $f$ is entire and we express $z=x+iy$. Then is $f$ constant ?
2016/03/14
[ "https://math.stackexchange.com/questions/1696791", "https://math.stackexchange.com", "https://math.stackexchange.com/users/74489/" ]
Let $w\in\mathbb R$ and $r > 0$ be arbitrary. Let $C$ be the circle about $w$ with radius $r$. We have $$ \frac 1 {2\pi i}\int\_C\frac{f(z)}{z-w}\,dz = f(w)\quad\text{and}\quad\frac 1 {2\pi i}\int\_C(z-w)f(z)\,dz = 0. $$ Hence, $$ -f(w) = \frac 1 {2\pi i}\int\_C\frac{r^{-2}(z-w)^2 - 1}{z-w}f(z)\,dz = \frac 1 {r^2}\cdot\frac 1 {2\pi i}\int\_C\frac{(z-w)^2 - r^2}{z-w}f(z)\,dz. $$ Now, since $\left|\frac{(z-w)^2 - r^2}{z-w}\right| = 2|\operatorname{Im}z|$ for $z\in C$, we conclude that $$ |f(w)|\,\le\,\frac 1 {2\pi r^2}\cdot 2\pi r\cdot 2 = \frac 2 r. $$ Letting $r\to\infty$ shows $f(w) = 0$. BTW: Here is another answer: [Showing Entire Function is Bounded](https://math.stackexchange.com/questions/1174742/showing-entire-function-is-bounded?rq=1)
A function like this must be zero. Indeed, let $g(z) := f(1/z)$, $z\neq 0$. Then $|g(z)|\le\frac{|z|^2}{|y|}$, i.e., $|g(z)|\le\frac 1 {|\operatorname{Im} z|}$ for $z\in\mathbb D\setminus\{0\}$. From this, it follows that $z=0$ is (at most) a pole of $g$. From here, it should be easy for you to deduce that $f = 0$.
25,055,712
`Dataframe.resample()` works only with timeseries data. I cannot find a way of getting every nth row from non-timeseries data. What is the best method?
2014/07/31
[ "https://Stackoverflow.com/questions/25055712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1014352/" ]
There is an even simpler solution to the accepted answer that involves directly invoking `df.__getitem__`. ``` df = pd.DataFrame('x', index=range(5), columns=list('abc')) df a b c 0 x x x 1 x x x 2 x x x 3 x x x 4 x x x ``` For example, to get every 2 rows, you can do ``` df[::2] a b c 0 x x x 2 x x x 4 x x x ``` --- There's also [`GroupBy.first`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.first.html)/[`GroupBy.head`](https://www.google.com/search?client=safari&rls=en&q=Groupby.head&ie=UTF-8&oe=UTF-8), you group on the index: ``` df.index // 2 # Int64Index([0, 0, 1, 1, 2], dtype='int64') df.groupby(df.index // 2).first() # Alternatively, # df.groupby(df.index // 2).head(1) a b c 0 x x x 1 x x x 2 x x x ``` The index is floor-divved by the stride (2, in this case). If the index is non-numeric, instead do ``` # df.groupby(np.arange(len(df)) // 2).first() df.groupby(pd.RangeIndex(len(df)) // 2).first() a b c 0 x x x 1 x x x 2 x x x ```
I had a similar requirement, but I wanted the n'th item in a particular group. This is how I solved it. ``` groups = data.groupby(['group_key']) selection = groups['index_col'].apply(lambda x: x % 3 == 0) subset = data[selection] ```
25,055,712
`Dataframe.resample()` works only with timeseries data. I cannot find a way of getting every nth row from non-timeseries data. What is the best method?
2014/07/31
[ "https://Stackoverflow.com/questions/25055712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1014352/" ]
I had a similar requirement, but I wanted the n'th item in a particular group. This is how I solved it. ``` groups = data.groupby(['group_key']) selection = groups['index_col'].apply(lambda x: x % 3 == 0) subset = data[selection] ```
``` df.drop(labels=df[df.index % 3 != 0].index, axis=0) # every 3rd row (mod 3) ```
25,055,712
`Dataframe.resample()` works only with timeseries data. I cannot find a way of getting every nth row from non-timeseries data. What is the best method?
2014/07/31
[ "https://Stackoverflow.com/questions/25055712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1014352/" ]
Though @chrisb's accepted answer does answer the question, I would like to add to it the following. A simple method I use to get the `nth` data or drop the `nth` row is the following: ``` df1 = df[df.index % 3 != 0] # Excludes every 3rd row starting from 0 df2 = df[df.index % 3 == 0] # Selects every 3rd raw starting from 0 ``` This arithmetic based sampling has the ability to enable even more complex row-selections. This **assumes**, of course, that you have an `index` column of *ordered, consecutive, integers* starting at 0.
Adding `reset_index()` to [metastableB's answer](https://stackoverflow.com/a/46141173/11816073) allows you to only need to assume that the rows are *ordered and consecutive*. ``` df1 = df[df.reset_index().index % 3 != 0] # Excludes every 3rd row starting from 0 df2 = df[df.reset_index().index % 3 == 0] # Selects every 3rd row starting from 0 ``` `df.reset_index().index` will create an index that starts at 0 and increments by 1, allowing you to use the modulo easily.
25,055,712
`Dataframe.resample()` works only with timeseries data. I cannot find a way of getting every nth row from non-timeseries data. What is the best method?
2014/07/31
[ "https://Stackoverflow.com/questions/25055712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1014352/" ]
Though @chrisb's accepted answer does answer the question, I would like to add to it the following. A simple method I use to get the `nth` data or drop the `nth` row is the following: ``` df1 = df[df.index % 3 != 0] # Excludes every 3rd row starting from 0 df2 = df[df.index % 3 == 0] # Selects every 3rd raw starting from 0 ``` This arithmetic based sampling has the ability to enable even more complex row-selections. This **assumes**, of course, that you have an `index` column of *ordered, consecutive, integers* starting at 0.
There is an even simpler solution to the accepted answer that involves directly invoking `df.__getitem__`. ``` df = pd.DataFrame('x', index=range(5), columns=list('abc')) df a b c 0 x x x 1 x x x 2 x x x 3 x x x 4 x x x ``` For example, to get every 2 rows, you can do ``` df[::2] a b c 0 x x x 2 x x x 4 x x x ``` --- There's also [`GroupBy.first`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.first.html)/[`GroupBy.head`](https://www.google.com/search?client=safari&rls=en&q=Groupby.head&ie=UTF-8&oe=UTF-8), you group on the index: ``` df.index // 2 # Int64Index([0, 0, 1, 1, 2], dtype='int64') df.groupby(df.index // 2).first() # Alternatively, # df.groupby(df.index // 2).head(1) a b c 0 x x x 1 x x x 2 x x x ``` The index is floor-divved by the stride (2, in this case). If the index is non-numeric, instead do ``` # df.groupby(np.arange(len(df)) // 2).first() df.groupby(pd.RangeIndex(len(df)) // 2).first() a b c 0 x x x 1 x x x 2 x x x ```
25,055,712
`Dataframe.resample()` works only with timeseries data. I cannot find a way of getting every nth row from non-timeseries data. What is the best method?
2014/07/31
[ "https://Stackoverflow.com/questions/25055712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1014352/" ]
I'd use `iloc`, which takes a row/column slice, both based on integer position and following normal python syntax. If you want every 5th row: ``` df.iloc[::5, :] ```
I had a similar requirement, but I wanted the n'th item in a particular group. This is how I solved it. ``` groups = data.groupby(['group_key']) selection = groups['index_col'].apply(lambda x: x % 3 == 0) subset = data[selection] ```
25,055,712
`Dataframe.resample()` works only with timeseries data. I cannot find a way of getting every nth row from non-timeseries data. What is the best method?
2014/07/31
[ "https://Stackoverflow.com/questions/25055712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1014352/" ]
I'd use `iloc`, which takes a row/column slice, both based on integer position and following normal python syntax. If you want every 5th row: ``` df.iloc[::5, :] ```
``` df.drop(labels=df[df.index % 3 != 0].index, axis=0) # every 3rd row (mod 3) ```
25,055,712
`Dataframe.resample()` works only with timeseries data. I cannot find a way of getting every nth row from non-timeseries data. What is the best method?
2014/07/31
[ "https://Stackoverflow.com/questions/25055712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1014352/" ]
I had a similar requirement, but I wanted the n'th item in a particular group. This is how I solved it. ``` groups = data.groupby(['group_key']) selection = groups['index_col'].apply(lambda x: x % 3 == 0) subset = data[selection] ```
A solution I came up with when using the index was not viable ( possibly the multi-Gig .csv was too large, or I missed some technique that would allow me to reindex without crashing ). Walk through one row at a time and add the nth row to a new dataframe. ``` import pandas as pd from csv import DictReader def make_downsampled_df(filename, interval): with open(filename, 'r') as read_obj: csv_dict_reader = DictReader(read_obj) column_names = csv_dict_reader.fieldnames df = pd.DataFrame(columns=column_names) for index, row in enumerate(csv_dict_reader): if index % interval == 0: print(str(row)) df = df.append(row, ignore_index=True) return df ```
25,055,712
`Dataframe.resample()` works only with timeseries data. I cannot find a way of getting every nth row from non-timeseries data. What is the best method?
2014/07/31
[ "https://Stackoverflow.com/questions/25055712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1014352/" ]
Adding `reset_index()` to [metastableB's answer](https://stackoverflow.com/a/46141173/11816073) allows you to only need to assume that the rows are *ordered and consecutive*. ``` df1 = df[df.reset_index().index % 3 != 0] # Excludes every 3rd row starting from 0 df2 = df[df.reset_index().index % 3 == 0] # Selects every 3rd row starting from 0 ``` `df.reset_index().index` will create an index that starts at 0 and increments by 1, allowing you to use the modulo easily.
I had a similar requirement, but I wanted the n'th item in a particular group. This is how I solved it. ``` groups = data.groupby(['group_key']) selection = groups['index_col'].apply(lambda x: x % 3 == 0) subset = data[selection] ```
25,055,712
`Dataframe.resample()` works only with timeseries data. I cannot find a way of getting every nth row from non-timeseries data. What is the best method?
2014/07/31
[ "https://Stackoverflow.com/questions/25055712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1014352/" ]
I'd use `iloc`, which takes a row/column slice, both based on integer position and following normal python syntax. If you want every 5th row: ``` df.iloc[::5, :] ```
Adding `reset_index()` to [metastableB's answer](https://stackoverflow.com/a/46141173/11816073) allows you to only need to assume that the rows are *ordered and consecutive*. ``` df1 = df[df.reset_index().index % 3 != 0] # Excludes every 3rd row starting from 0 df2 = df[df.reset_index().index % 3 == 0] # Selects every 3rd row starting from 0 ``` `df.reset_index().index` will create an index that starts at 0 and increments by 1, allowing you to use the modulo easily.