title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Going crazy with python set
7,446,198
2
2011-09-16T14:27:34Z
7,446,253
10
2011-09-16T14:32:12Z
[ "python", "set" ]
Please take a look at the following snippet from ipython: ``` In [122]: len(netean) Out[122]: 150 In [123]: len(nwrongpea) Out[123]: 100 In [124]: len(set.intersection(set(nwrongpea), set(netean))) Out[124]: 8 In [125]: len(set(nwrongpea) - set(netean)) Out[125]: 90 In [126]: len(set(netean) - set(nwrongpea)) Out[...
It looks like one(or two) of this collections have some duplicate elements. So creating sets from them gives you sets with less number of elements.. Try `len(set(natean)) + len(set(nwrongpea))` and you'll see.
how to troubleshoot an "AttributeError: __exit__" in multiproccesing in Python?
7,447,284
40
2011-09-16T15:48:04Z
7,447,369
72
2011-09-16T15:53:31Z
[ "python", "python-3.x", "multiprocessing", "pool" ]
I tried to rewrite some csv-reading code to be able to run it on multiple cores in Python 3.2.2. I tried to use the Pool object of multiprocessing, which I adapted from working examples (and already worked for me for another part of my project). I ran into an error message I found hard to decipher and troubleshoot. Wha...
The problem is in this line: ``` with pattern.findall(row) as f: ``` You are using the with statement. It requires an object with `__enter__` and `__exit__` methods. But `pattern.findall` returns a `list`, `with` tries to store the `__exit__` method, but it can't find it, and raises an error. Just use ``` f = patter...
how to troubleshoot an "AttributeError: __exit__" in multiproccesing in Python?
7,447,284
40
2011-09-16T15:48:04Z
35,991,842
13
2016-03-14T15:37:23Z
[ "python", "python-3.x", "multiprocessing", "pool" ]
I tried to rewrite some csv-reading code to be able to run it on multiple cores in Python 3.2.2. I tried to use the Pool object of multiprocessing, which I adapted from working examples (and already worked for me for another part of my project). I ran into an error message I found hard to decipher and troubleshoot. Wha...
It is not the asker's problem in this instance but **the first** troubleshooting step for a generic "AttributeError: \_\_exit\_\_" should be making sure the brackets are there, e.g. ``` with SomeEnterExitObject() as foo: #works because a new object is referenced... ``` **not** ``` with SomeEnterExitObject as foo...
issue while committing data using SQLAlchemy Session object in a Loop
7,447,309
3
2011-09-16T15:49:39Z
7,450,991
7
2011-09-16T22:25:24Z
[ "python", "sqlalchemy" ]
I am having a database committing problem with SQLalchemy. Here is my scenario I have a list of records to be added into a table. Once a records is added into a table I need to get the inserted records Id and do another insert into a second table. I am doing these operation under single session. The code structure is g...
There's a very good chance that you *don't* need to issue two commits; One of the main reasons for using sqlalchemy sessions is that it understands how objects can interrelate, and will order its inserts in such a way that data gets properly inserted and correctly represents the desired structure. This works principall...
using Python logger class to generate multiple logs for different log levels
7,447,382
3
2011-09-16T15:54:29Z
7,447,596
8
2011-09-16T16:12:16Z
[ "python", "logging", "file-io", "sikuli" ]
I looked through the tutorials for the python logging class here and didnt see anything that would let me make multiple logs of different levels for the same output. In the end I would like to have three logs: `<timestamp>_DEBUG.log` (debug level) `<timestamp>_INFO.log` (info Level) `<timestamp>_ERROR.log` (error l...
Create multiple Handlers, each for one output file (INFO.log, DEBUG.log etc.). Add a filter to each handler that only allows the specific level. For example: ``` import logging # Set up loggers and handlers. # ... class LevelFilter(logging.Filter): def __init__(self, level): self.level = level def...
Trouble converting string to int in Django/Python
7,448,531
4
2011-09-16T17:52:55Z
7,448,669
11
2011-09-16T18:05:59Z
[ "python", "django", "oop", "for-loop", "django-views" ]
I'm trying to convert a string into an int so that I can keep a running total and would like to be able to output in the django template. ``` def stats(request): stats = [] players = Player.objects.all() for player in players: player_stats = PlayerStat.objects.filter(player__id=player.pk) ...
I sometimes use this stupid trick : ``` a = int('0' + someString) ``` Adding a zero in front of a string guaranties me to have at least "0" in the string. Now, to be sure, you may extract all the digits from the "'0'+someString" with a regular expression.
Call python script within java code (runtime.exec)
7,449,395
3
2011-09-16T19:21:46Z
7,449,405
7
2011-09-16T19:24:00Z
[ "java", "python", "windows", "runtime.exec" ]
I'm trying to run a python script in java but I'm having some troubles. I'm using the command bellow to execute the python script which is inside a folder called python in my java project: ``` Runtime r = Runtime.getRuntime(); Process p = r.exec("cmd /c python python\\test.py"); ``` The script should write something ...
Most likely the python executable is not in the path that's given to the child process. Try changing the command line to include the full path to the python executable, as in ``` Process p = r.exec("cmd /c c:\\path\\to\\python python\\test.py"); ```
How do you set the absolute position of figure windows with matplotlib?
7,449,585
14
2011-09-16T19:41:12Z
7,450,808
10
2011-09-16T21:58:20Z
[ "python", "matplotlib" ]
I'm writing a simple Python application that uses matplotlib to display a few figures on screen. The number of figures generated is based on user input and changes throughout the application's life. The user has the ability to issue a "plot" command to generate a new figure window with the selected data series. In orde...
there is not that I know a backend-agnostic way to do this, but definitely it is possible to do it for some common backends, e.g., WX, tkagg etc. ``` import matplotlib matplotlib.use("wx") from pylab import * figure(1) plot([1,2,3,4,5]) thismanager = get_current_fig_manager() thismanager.window.SetPosition((500, 0)) s...
How do you set the absolute position of figure windows with matplotlib?
7,449,585
14
2011-09-16T19:41:12Z
19,943,546
10
2013-11-13T01:30:56Z
[ "python", "matplotlib" ]
I'm writing a simple Python application that uses matplotlib to display a few figures on screen. The number of figures generated is based on user input and changes throughout the application's life. The user has the ability to issue a "plot" command to generate a new figure window with the selected data series. In orde...
FINALLY found the solution for QT backend: ``` import matplotlib.pyplot as plt fig, ax = subplots() mngr = plt.get_current_fig_manager() # to put it into the upper left corner for example: mngr.window.setGeometry(50,100,640, 545) ``` If one doesn't know the x- and y-width one can read them out first, like so: ``` #...
Get input file name in streaming hadoop program
7,449,756
7
2011-09-16T19:59:17Z
7,452,439
7
2011-09-17T04:30:40Z
[ "python", "input", "streaming", "hadoop", "filesplitting" ]
I am able to find the name if the input file in a mapper class using FileSplit when writing the program in Java. Is there a corresponding way to do this when I write a program in Python (using streaming?) I found the following in the hadoop streaming document on apache: > See Configured Parameters. During the execut...
According to the ["Hadoop : The Definitive Guide"](http://shop.oreilly.com/product/0636920010388.do) Hadoop sets job configuration parameters as environment variables for Streaming programs. However, it replaces non-alphanumeric character with underscores to make sure they are valid names. The following Python express...
Calling 'mv' from Python Popen with wildcard
7,450,456
3
2011-09-16T21:14:33Z
7,450,478
8
2011-09-16T21:17:58Z
[ "python", "shell", "unix", "scripting" ]
I can't seem to get the 'mv' command to work from Python `subprocess.Popen` with a wildcard. The code: ``` def moveFilesByType(source, destination, extension): params = [] params.append("mv") params.append(source + "/*." + extension) params.append(destination + "/") print params pip...
Use a string instead of an array: ``` params = "mv /full_path_to_folder_source/*.nib /full_path_to_folder_target/" ``` When you specify arguments via the array form, the argument `'/full_path_to_folder_source/*.nib'` is passed to `mv`. You want to force bash to expand the argument, but `Popen` won't pass each argumen...
How to implement R's p.adjust in Python
7,450,957
9
2011-09-16T22:18:41Z
7,453,313
10
2011-09-17T07:46:37Z
[ "python", "statistics", "rpy2" ]
I have a list of p-values and I would like to calculate the adjust p-values for multiple comparisons for the [FDR](http://en.wikipedia.org/wiki/False_discovery_rate). In R, I can use: ``` pval <- read.csv("my_file.txt",header=F,sep="\t") pval <- pval[,1] FDR <- p.adjust(pval, method= "BH") print(length(pval[FDR<0.1]))...
If you wish to be sure of what you are getting from R, you can also indicate that you wish to use the function in the R package 'stats': ``` from rpy2.robjects.packages import importr from rpy2.robjects.vectors import FloatVector stats = importr('stats') p_adjust = stats.p_adjust(FloatVector(pvalue_list), method = '...
How to implement R's p.adjust in Python
7,450,957
9
2011-09-16T22:18:41Z
13,745,141
10
2012-12-06T13:58:08Z
[ "python", "statistics", "rpy2" ]
I have a list of p-values and I would like to calculate the adjust p-values for multiple comparisons for the [FDR](http://en.wikipedia.org/wiki/False_discovery_rate). In R, I can use: ``` pval <- read.csv("my_file.txt",header=F,sep="\t") pval <- pval[,1] FDR <- p.adjust(pval, method= "BH") print(length(pval[FDR<0.1]))...
This question is a bit old, but there are multiple comparison corrections available in statsmodels for Python. We have <http://statsmodels.sourceforge.net/devel/generated/statsmodels.sandbox.stats.multicomp.multipletests.html#statsmodels.sandbox.stats.multicomp.multipletests>
Is there a JavaScript (ECMAScript) implementation written in Python?
7,451,619
16
2011-09-17T00:25:36Z
7,451,628
9
2011-09-17T00:29:05Z
[ "javascript", "python", "interpreter", "vm-implementation" ]
Are there any JavaScript (ECMAScript) implementations written in **pure** Python? It is okay even if its implementation is very slow.
Doesn't seem to be under active development anymore but you could check out `pynarcissus`, <http://code.google.com/p/pynarcissus/source/browse/trunk/jsparser.py> Seems like a binding to V8 (JavaScript interpreter in Google Chromium) is available also, <http://www.advogato.org/article/985.html>
Django's Double Underscore
7,451,933
7
2011-09-17T01:48:38Z
7,451,959
8
2011-09-17T01:56:17Z
[ "python", "django" ]
In Django, you can make database queries like the following: ``` Model.objects.filter(name__icontains = 'bob') ``` The question is: how is this working 'under the cover'? Is the double underscore a Django thing or a Python thing? Is this just a single variable named `name__icontains`, or is it some sort of attribute-...
It's a Django thing, implemented with some Python things. In Python, you can get a dictionary of the keyword arguments passed to a function or method: ``` >>> def func(*args, **kwargs): ... print(kwargs) >>> func(a=1, b=2) {'a': 1, 'b': 2} ``` From there, it can simply iterate over the dictionary keys and split ...
Best way to retrieve data attributes in Python?
7,454,879
9
2011-09-17T12:52:46Z
7,454,908
12
2011-09-17T12:56:32Z
[ "python", "coding-style" ]
I have a question that is puzzling me recently about which is the best way to retrieve attributes from outside. Let say I have a class: ``` class Thing: def __init__(self, whatever): self.whatever = whatever x = Thing('foo') ``` Now I know that if I want to retrieve `whatever` attribute I can do this: ...
Defining explicit getters and setters is a [bad practice](http://stackoverflow.com/questions/6618002/python-property-versus-getters-and-setters/6618184#6618184) in Python. Instead, use [properties](http://docs.python.org/library/functions.html#property): ``` class Thing(object): # New-style class def __init__(self...
Best way to retrieve data attributes in Python?
7,454,879
9
2011-09-17T12:52:46Z
7,454,953
8
2011-09-17T13:02:53Z
[ "python", "coding-style" ]
I have a question that is puzzling me recently about which is the best way to retrieve attributes from outside. Let say I have a class: ``` class Thing: def __init__(self, whatever): self.whatever = whatever x = Thing('foo') ``` Now I know that if I want to retrieve `whatever` attribute I can do this: ...
@phihag has the right idea, and mentions in their answer, but to be more explicit about it: The first step is simply to use the attribute directly: ``` class Thing(object): def __init__(self, whatever): self.whatever = whatever t = Thing(12) assert t.whatever == 12 ``` Later, if you find you need to mak...
weird behaviour in twisted defer callback
7,456,463
2
2011-09-17T17:10:04Z
7,456,594
8
2011-09-17T17:32:13Z
[ "python", "callback", "twisted" ]
Aim : To try a TCP connection to a list of server and print if the connection was successful and prompted for password or not Problem : It seems as if a statement(`to_check -= 1`) in my callback(named **connected**) and errback(named **failed**) never gets executed, even though the print statements in those functions ...
This is a general issue with your understanding of closures in python; by default, variables are local to the innermost function in which they are assigned. `-=` is an implicit assignment, so `to_check` becomes a local variable to `connected` and `failed`. As such, the `to_check` in the `main` function is never changed...
Python name mangling
7,456,807
43
2011-09-17T18:07:49Z
7,456,865
86
2011-09-17T18:16:54Z
[ "python", "naming-conventions" ]
In other languages, a general guideline that helps produce better code is always make everything as hidden as possible. If in doubt about whether a variable should be private or protected, it's better to go with private. Does the same hold true for Python? Should I use two leading underscores on everything at first, a...
When in doubt, leave it "public" - I mean, do not add anything to obscure the name of your attribute. If you have a class with some internal value, do not bother about it. Instead of writing: ``` class Stack(object): def __init__(self): self.__storage = [] # Too uptight def push(self, value): ...
Python name mangling
7,456,807
43
2011-09-17T18:07:49Z
7,456,912
9
2011-09-17T18:25:22Z
[ "python", "naming-conventions" ]
In other languages, a general guideline that helps produce better code is always make everything as hidden as possible. If in doubt about whether a variable should be private or protected, it's better to go with private. Does the same hold true for Python? Should I use two leading underscores on everything at first, a...
I wouldn't say that practice produces better code. Visibility modifiers only distract you from the task at hand, and as a side effect force your interface to be used as you intended. Generally speaking, enforcing visibility prevents programmers from messing things up if they haven't read the documentation properly. A ...
Best / most pythonic way to get an ordered list of unique items
7,458,689
4
2011-09-18T00:13:12Z
7,458,752
12
2011-09-18T00:30:08Z
[ "python", "list" ]
I have one or more unordered sequences of (immutable, hashable) objects with possible duplicates and I want to get a sorted sequence of all those objects without duplicates. Right now I'm using a set to quickly gather all the elements discarding duplicates, convert it to a list and then sort that: ``` result = set() ...
This should work: ``` sorted(set(itertools.chain.from_iterable(sequences))) ```
Installing MySQL-python
7,459,766
49
2011-09-18T05:57:09Z
7,459,941
7
2011-09-18T06:44:35Z
[ "python", "mysql" ]
I got the below failure while trying to get MySQL-python installed on my Ubuntu/Linux Box.From the below it seem like the issue is `sh: mysql_config: not found` Could someone advice me on what to do? ``` rmicro@ubuntu:~$ pip install MySQL-python Downloading/unpacking MySQL-python Downloading MySQL-python-1.2.3.tar.g...
Reread the error message. It says: > sh: mysql\_config: not found If you are on Ubuntu Natty, `mysql_config` belongs to package [libmysqlclient-dev](http://packages.ubuntu.com/search?searchon=contents&keywords=mysql_config&mode=exactfilename&suite=natty&arch=any)
Installing MySQL-python
7,459,766
49
2011-09-18T05:57:09Z
7,461,662
114
2011-09-18T13:03:57Z
[ "python", "mysql" ]
I got the below failure while trying to get MySQL-python installed on my Ubuntu/Linux Box.From the below it seem like the issue is `sh: mysql_config: not found` Could someone advice me on what to do? ``` rmicro@ubuntu:~$ pip install MySQL-python Downloading/unpacking MySQL-python Downloading MySQL-python-1.2.3.tar.g...
On Ubuntu it is advised to use the distributions repository. So installing python-mysqldb should be straight forward: ``` sudo apt-get install python-mysqldb ``` If you actually want to use pip to install, which is as mentioned before not the suggested path but possible, please have a look at this previously asked qu...
Installing MySQL-python
7,459,766
49
2011-09-18T05:57:09Z
11,522,727
10
2012-07-17T12:44:56Z
[ "python", "mysql" ]
I got the below failure while trying to get MySQL-python installed on my Ubuntu/Linux Box.From the below it seem like the issue is `sh: mysql_config: not found` Could someone advice me on what to do? ``` rmicro@ubuntu:~$ pip install MySQL-python Downloading/unpacking MySQL-python Downloading MySQL-python-1.2.3.tar.g...
You have 2 options, as described bellow: --- Distribution package like Glaslos suggested: ``` # sudo apt-get install python-mysqldb ``` In this case you can't use virtualenv no-site-packages (default option) but must use: ``` # virtualenv --system-site-packages myenv ``` --- Use clean virtualenv and build your o...
Installing MySQL-python
7,459,766
49
2011-09-18T05:57:09Z
18,589,348
9
2013-09-03T09:59:01Z
[ "python", "mysql" ]
I got the below failure while trying to get MySQL-python installed on my Ubuntu/Linux Box.From the below it seem like the issue is `sh: mysql_config: not found` Could someone advice me on what to do? ``` rmicro@ubuntu:~$ pip install MySQL-python Downloading/unpacking MySQL-python Downloading MySQL-python-1.2.3.tar.g...
``` yum install mysql-devel ``` It worked for me.
Get image size without downloading it in Python
7,460,218
11
2011-09-18T07:58:57Z
7,460,263
9
2011-09-18T08:09:06Z
[ "python", "image", "url" ]
How can I get dimensions of image without actually downloading it? Is it even possible? I have a list of urls of images and I want to assign width and size to it. I know there is a way of doing it locally ([How to check dimensions of all images in a directory using python?](http://stackoverflow.com/questions/1507084/h...
If you're willing to download the first 24 bytes of each file, then [this function](http://code.google.com/p/bfg-pages/source/browse/trunk/pages/getimageinfo.py) (mentioned in johnteslade's answer to the question you mention) will work out the dimensions. That's probably the least downloading necessary to do the job y...
Get image size without downloading it in Python
7,460,218
11
2011-09-18T07:58:57Z
9,051,055
14
2012-01-29T04:54:18Z
[ "python", "image", "url" ]
How can I get dimensions of image without actually downloading it? Is it even possible? I have a list of urls of images and I want to assign width and size to it. I know there is a way of doing it locally ([How to check dimensions of all images in a directory using python?](http://stackoverflow.com/questions/1507084/h...
This is based on ed's answer mixed with other things I found on the web. I ran into the same issue as grotos with .read(24). Download getimageinfo.py from [here](https://gist.github.com/bmamouri/55ac6bfa7ba5eee03da2eb9e4f7469d9) and download ReSeekFile.py from [here](http://www.dalkescientific.com/writings/diary/archiv...
Get image size without downloading it in Python
7,460,218
11
2011-09-18T07:58:57Z
16,379,179
8
2013-05-04T21:33:37Z
[ "python", "image", "url" ]
How can I get dimensions of image without actually downloading it? Is it even possible? I have a list of urls of images and I want to assign width and size to it. I know there is a way of doing it locally ([How to check dimensions of all images in a directory using python?](http://stackoverflow.com/questions/1507084/h...
I found the solution on [this site](http://effbot.org/zone/pil-image-size.htm) to work well: ``` import urllib import ImageFile def getsizes(uri): # get file size *and* image size (None if not known) file = urllib.urlopen(uri) size = file.headers.get("content-length") if size: size = int(size) p =...
How to run python script in webpage
7,460,938
22
2011-09-18T10:37:30Z
7,460,987
18
2011-09-18T10:51:00Z
[ "python" ]
I'm very new to python. Just know what is python. I have created the below code (In python IDLE): ``` print "Hi Welcome to Python test page\n"; print "Now it will show a calculation"; print "30+2="; print 30+2; ``` Then I saved this page in my localhost as index.py I run the script using <http://localhost/index.py> ...
In order for your code to show, you need several things: Firstly, there needs to be a server that handles HTTP requests. At the moment you are just opening a file with Firefox on your local hard drive. A server like Apache or something similar is required. Secondly, presuming that you now have a server that serves th...
How to run python script in webpage
7,460,938
22
2011-09-18T10:37:30Z
7,461,804
7
2011-09-18T13:35:14Z
[ "python" ]
I'm very new to python. Just know what is python. I have created the below code (In python IDLE): ``` print "Hi Welcome to Python test page\n"; print "Now it will show a calculation"; print "30+2="; print 30+2; ``` Then I saved this page in my localhost as index.py I run the script using <http://localhost/index.py> ...
As others have pointed out, there are many web frameworks for Python. But, seeing as you are just getting started with Python, a simple CGI script might be more appropriate: 1. Rename your script to `index.cgi`. You also need to execute `chmod +x index.cgi` to give it execution privileges. 2. Add these 2 lines in the...
Matching 2 regular expressions in Python
7,463,233
10
2011-09-18T17:48:03Z
7,533,570
11
2011-09-23T18:55:18Z
[ "python", "regex" ]
Is it possible to match 2 regular expressions in Python? For instance, I have a use-case wherein I need to compare 2 expressions like this: ``` re.match('google\.com\/maps', 'google\.com\/maps2', re.IGNORECASE) ``` I would expect to be returned a RE object. But obviously, Python expects a string as the second param...
Outside of the syntax clarification on `re.match`, I think I am understanding that you are struggling with taking two or more unknown (user input) regex expressions and classifying which is a more 'specific' match against a string. Recall for a moment that a Python regex really is a type of computer program. Most mode...
if, elif, else chain not working correctly?
7,463,256
2
2011-09-18T17:53:09Z
7,463,269
8
2011-09-18T17:54:34Z
[ "python" ]
I'm working through 'Learn Python the Hard Way' and I've hit a roadblock. The book gives a unit test and asks you to write a function to satisfy the tests. But when I import this function to the interactive shell to test it out, any input returns 'direction' and I can't figure out why. Here's my code: ``` def pos(ite...
You should have written this: ``` if item == 'north' or item == 'south' or item == 'east': ``` or, alternatively: ``` if item in ('north', 'south', 'east'): ``` The same applies for the remaining branches. To explain why your original code failed, consider how Python parses the following expression: ``` item == '...
How to deal with Linux/Python dependencies?
7,463,530
12
2011-09-18T18:36:03Z
7,463,938
12
2011-09-18T19:36:37Z
[ "python", "linux", "dependencies", "dependency-management" ]
Due to lack of support for some libraries I want to use, I moved some Python development from Windows to Linux development. I've spent most of the day messing about getting nowhere with dependencies. **The question** Whenever I pick up Linux, I usually run into some kind of dependency issue, usually with development ...
I see two separate problems here: 1. Keeping track of all the python modules you need for your project. 2. Keeping track of all the dynamic libraries you need for the python modules in your project. For the first problem, I have found that [buildout](http://www.buildout.org/%20buildout) is good help, althought it tak...
Don't understand this python For loop
7,463,683
7
2011-09-18T18:58:02Z
7,463,720
8
2011-09-18T19:04:05Z
[ "python" ]
I'm still a python newb, but I'm working through the [Pyneurgen neural network tutorial](http://pyneurgen.sourceforge.net/tutorial_nn.html), and I don't fully understand how the for loop used to create the input data works in this instance: ``` for position, target in population_gen(population): pos = float(positi...
The function population\_gen is returning a list of tuples, which are unpacked automatically into variable names using this syntax. So basically, you're getting something like the following as return value from the function: ``` [("pos1", "target1"), ("pos2", "target2"), ] ``` Given this example, in the the for loop...
Convert loop and if statemnt to a list comprehension
7,464,911
3
2011-09-18T22:35:40Z
7,464,929
9
2011-09-18T22:38:46Z
[ "python", "list" ]
Is it possible to convert the following to a python list comprehension: ``` values = [a,b,c,d,...] converted_values = [] for item in values: if type(item) == datetime.date: converted_values.append(item) else: converted_values.append(item.decode('utf-8')) ```
You can use [Conditional Expressions](http://docs.python.org/reference/expressions.html#conditional-expressions) to make this work. ``` converted_values = [item if type(item) == datetime.data else item.decode('utf-8') for item in values] ``` Python conditionals are fairly reada...
Convert relative URL to fully qualified URL using Python
7,465,379
5
2011-09-19T00:25:13Z
7,465,405
7
2011-09-19T00:32:50Z
[ "python", "string", "http", "url" ]
I'm looking for a way to fully qualify a URL using Python. I have my current page URL, such as: <http://www.foo.com/Stuff/Mike/Doc.html> and I have my href, such as: href="../Bob/Doc.html" What I need to build is: <http://www.foo.com/Stuff/Bob/Doc.html> Does Python have any libraries that can parse paths like thi...
Use the [`urlparse`](http://docs.python.org/library/urlparse.html) library. ``` >>> import urlparse >>> urlparse.urljoin("http://www.foo.com/Stuff/Mike/Doc.html","../Bob/Doc.html") 'http://www.foo.com/Stuff/Bob/Doc.html' ```
How to install python modules without root access?
7,465,445
109
2011-09-19T00:41:50Z
7,465,532
139
2011-09-19T01:04:07Z
[ "python", "numpy", "pip" ]
I'm taking some university classes and have been given an 'instructional account', which is a school account I can ssh into to do work. I want to run my computationally intensive Numpy, matplotlib, scipy code on that machine, but I cannot install these modules because I am not a system administrator. How can I do the ...
In most situations the best solution is to rely on the so-called "user site" location (see the [PEP](http://www.python.org/dev/peps/pep-0370/) for details) by running: ``` pip install --user package_name ``` Below is a more "manual" way from my original answer, you do not need to read it if the above solution works f...
How to install python modules without root access?
7,465,445
109
2011-09-19T00:41:50Z
7,469,781
8
2011-09-19T10:51:45Z
[ "python", "numpy", "pip" ]
I'm taking some university classes and have been given an 'instructional account', which is a school account I can ssh into to do work. I want to run my computationally intensive Numpy, matplotlib, scipy code on that machine, but I cannot install these modules because I am not a system administrator. How can I do the ...
If you have to use a distutils `setup.py` script, there are some commandline options for forcing an installation destination. See <http://docs.python.org/install/index.html#alternate-installation>. If this problem repeats, you can setup a distutils configuration file, see <http://docs.python.org/install/index.html#inst...
How to install python modules without root access?
7,465,445
109
2011-09-19T00:41:50Z
13,958,308
24
2012-12-19T17:59:44Z
[ "python", "numpy", "pip" ]
I'm taking some university classes and have been given an 'instructional account', which is a school account I can ssh into to do work. I want to run my computationally intensive Numpy, matplotlib, scipy code on that machine, but I cannot install these modules because I am not a system administrator. How can I do the ...
An alternative solution is creating a python virtualenv (specially when not having access to easy\_install). Executing 3 commands in the shell will be enough: ``` $ curl -O https://raw.github.com/pypa/virtualenv/master/virtualenv.py $ python virtualenv.py my_new_env $ . my_new_env/bin/activate (my_new_env)$ pip instal...
NameError: name 're' is not defined
7,465,590
7
2011-09-19T01:17:00Z
7,465,610
14
2011-09-19T01:20:10Z
[ "python" ]
I am very new to python. Very new. I copied the following from a tutorial ``` #!/usr/bin/python import re from urllib import urlopen from BeautifulSoup import BeautifulSoup webpage = urlopen('http://feeds.huffingtonpost.com/huffingtonpost/LatestNews').read patFinderTitle = re.compile('<title>(.*)</title>') patFinde...
You need to import [regular expression module](http://docs.python.org/library/re.html) in your code ``` import re re.compile('<title>(.*)</title>') ```
perl to python...how do I?
7,465,695
4
2011-09-19T01:38:07Z
7,465,724
7
2011-09-19T01:45:01Z
[ "python", "perl" ]
I am trying to learn python but don't quite understand the syntax. What is the equivalent of: ``` my $string='this one this that this here '; while($string=~/this\s+(.*?)\s+/g){ print $1."\n"; } ``` prints: ``` one that here ```
Try the `re` module. I think this is equivalent, modulo some of the side-effects on `string`: ``` import re string = "this one this that this here " for match in re.finditer(r"this\s+(.*?)\s+", string): print match.group(1) ```
django set DateTimeField to server's current time
7,465,796
26
2011-09-19T01:58:16Z
7,466,038
37
2011-09-19T02:57:03Z
[ "python", "database", "django" ]
How do I do the equivalent of this SQL in django? ``` UPDATE table SET timestamp=NOW() WHERE ... ``` Particularly I want to set the datetime field using server's builtin function to get the system time from the server that the database was running on and not the time on the client machine. I know you can execute the...
As j0ker said, if you want automatic update of the timestamp, use the `auto_now` option. E.g. `date_modified = models.DateTimeField(auto_now=True)`. Or if you want to do it manually, isn't it a simple assignment with python `datetime.now()`? ``` from datetime import datetime obj.date_modified = datetime.now() ```
Trouble iterating in python
7,465,824
2
2011-09-19T02:04:59Z
7,465,861
7
2011-09-19T02:12:16Z
[ "python", "floating-point", "iteration" ]
Working in Python 2.7. I would like to be able to input a number, and return all the sets of values for x and y that complete the equation win\_percentage = observed. ``` def Rlog5(observed): z = float(observed)/1000 for x in range(350, 650, 1): y = 1000 - x win_percentage = (float(x)-(float(x...
As others have noted, you have `=` where you should have `==`, but I assume that's a typo here, since you would get a syntax error. But you are testing floats for equality, and floats are almost never equal because of their imprecision. Generally, you test to see if two floats are within a small difference of each othe...
cx_Oracle and Exception Handling - Good practices?
7,465,889
13
2011-09-19T02:19:40Z
9,853,319
24
2012-03-24T16:23:41Z
[ "python", "oracle", "cx-oracle" ]
I'm trying to use cx\_Oracle to connect to an Oracle instance and execute some DDL statements: ``` db = None try: db = cx_Oracle.connect('username', 'password', 'hostname:port/SERVICENAME') #print(db.version) except cx_Oracle.DatabaseError as e: error, = e.args if error.code == 1017: print('Please ...
> However, if it can't connect, then `db` won't exist further down - > which is why I set `db = None` above. However, is that good practice? No, setting `db = None` is not best practice. There are two possibilities, either connecting to the database will work or it won't. * Connecting to the database doesn't work: ...
Installing python ldap module under cygwin
7,466,959
2
2011-09-19T05:56:32Z
7,479,796
8
2011-09-20T03:31:17Z
[ "python", "cygwin" ]
I am trying to install the basic ldap python module under cygwin. The following is failing: ``` %easy_install ldap Searching for ldap... .. No local packages or download links found for ldap ``` I am using cherrypy for an app which is running fine in Ubuntu, and planning to port it to cygwin so I can run the app unde...
Another stackoverflow page came to rescue: [python-ldap OS X 10.6 and Python 2.6](http://stackoverflow.com/questions/6475118/python-ldap-os-x-10-6-and-python-2-6) The final solution: ``` pip install python-ldap==2.3.13 ``` Noting it here so people facing this in cygwin can use this post.
Python subprocess readlines()?
7,468,668
9
2011-09-19T09:12:57Z
7,468,725
19
2011-09-19T09:17:40Z
[ "python", "subprocess" ]
So I'm trying to move away from os.popen to subprocess.popen as recommended by the user guide. The only trouble I'm having is I can't seem to find a way of making readlines() work. So I used to be able to do ``` list = os.popen('ls -l').readlines() ``` But I can't do ``` list = subprocess.Popen(['ls','-l']).readlin...
With `subprocess.Popen`, use `communicate` to read and write data: ``` out, err = subprocess.Popen(['ls','-l'], stdout=subprocess.PIPE).communicate() ``` Then you can always split the string from the processes' `stdout` with `splitlines()`. ``` out = out.splitlines() ```
Python subprocess readlines()?
7,468,668
9
2011-09-19T09:12:57Z
7,468,726
17
2011-09-19T09:17:40Z
[ "python", "subprocess" ]
So I'm trying to move away from os.popen to subprocess.popen as recommended by the user guide. The only trouble I'm having is I can't seem to find a way of making readlines() work. So I used to be able to do ``` list = os.popen('ls -l').readlines() ``` But I can't do ``` list = subprocess.Popen(['ls','-l']).readlin...
``` ls = subprocess.Popen(['ls','-l'], stdout=subprocess.PIPE) out = ls.stdout.readlines() ``` or, if you want to read line-by-line (maybe the other process is more intensive than `ls`): ``` for ln in ls.stdout: # whatever ```
Python subprocess readlines()?
7,468,668
9
2011-09-19T09:12:57Z
7,469,070
8
2011-09-19T09:49:00Z
[ "python", "subprocess" ]
So I'm trying to move away from os.popen to subprocess.popen as recommended by the user guide. The only trouble I'm having is I can't seem to find a way of making readlines() work. So I used to be able to do ``` list = os.popen('ls -l').readlines() ``` But I can't do ``` list = subprocess.Popen(['ls','-l']).readlin...
[Making a system call that returns the stdout output as a string](http://stackoverflow.com/questions/236737/making-a-system-call-that-returns-the-stdout-output-as-a-string/236909#236909): ``` lines = subprocess.check_output(['ls', '-l']).splitlines() ```
what's the difference between two Python imports
7,468,774
4
2011-09-19T09:22:51Z
7,468,805
11
2011-09-19T09:26:29Z
[ "python", "import" ]
Python [has](http://docs.python.org/reference/simple_stmts.html#the-import-statement) two ways to import something from a module: ``` from mymodule import ClassOne, ClassTwo, ClassThree ``` and ``` from mymodule import (ClassOne, ClassTwo, ClassThree) ``` I cannot find any note (probably, I'm just not trying hard e...
If you put the items to import between brackets, you can use more than one line for everything you want to import, without escaping newlines.
pip on Windows giving the error - Unknown or unsupported command 'install'
7,469,361
48
2011-09-19T10:17:07Z
7,470,225
123
2011-09-19T11:29:47Z
[ "python", "selenium", "pip" ]
I installed pip on Windows by downloading <http://pypi.python.org/packages/source/p/pip/pip-1.0.2.tar.gz#md5=47ec6ff3f6d962696fe08d4c8264ad49> and running `python setup.py install` Installation went fine with no errors. But when I tried installing selenium package with it, it gives me the following error - ``` pip i...
Do you happen to have the Perl pip lying around somewhere? Sounds like the problem described here: <https://github.com/mike-perdide/gitbuster/issues/62> To check, in Windows command prompt execute: ``` C:\>where pip ``` This will potentially output the following: ``` C:\strawberry\perl\bin\pip C:\strawberry\perl\...
pip on Windows giving the error - Unknown or unsupported command 'install'
7,469,361
48
2011-09-19T10:17:07Z
8,634,923
12
2011-12-26T10:36:39Z
[ "python", "selenium", "pip" ]
I installed pip on Windows by downloading <http://pypi.python.org/packages/source/p/pip/pip-1.0.2.tar.gz#md5=47ec6ff3f6d962696fe08d4c8264ad49> and running `python setup.py install` Installation went fine with no errors. But when I tried installing selenium package with it, it gives me the following error - ``` pip i...
Had the same problem under Ubuntu and did: ``` $ sudo apt-get remove pip $ sudo apt-get install python-pip ```
pip on Windows giving the error - Unknown or unsupported command 'install'
7,469,361
48
2011-09-19T10:17:07Z
28,998,747
9
2015-03-11T22:40:02Z
[ "python", "selenium", "pip" ]
I installed pip on Windows by downloading <http://pypi.python.org/packages/source/p/pip/pip-1.0.2.tar.gz#md5=47ec6ff3f6d962696fe08d4c8264ad49> and running `python setup.py install` Installation went fine with no errors. But when I tried installing selenium package with it, it gives me the following error - ``` pip i...
This error is because the system is finding pip.bat before it finds pip.exe. You do NOT need to uninstall Strawberry Perl or type the whole path. What I do is to simply type pip.exe (same number of keystrokes as apt-get) when I want to use the Python utility. This method seems to work find for me on Win7 with Python(...
Renaming file names containing spaces
7,469,374
5
2011-09-19T10:18:20Z
7,469,461
8
2011-09-19T10:26:02Z
[ "python", "file", "operating-system", "rename" ]
I am writing a simple Python script to rename all files in a directory to replace all spaces in the file name with hyphens. I have the following which is crashing on os.rename ``` import os path = os.getcwd() filenames = os.listdir(path) for filename in filenames: os.rename(os.path.join(path + filename), os.pat...
If you are already in the directory which contains the files you want to rename, you don't need to give absolute path: ``` for filename in filenames: os.rename(filename, filename.replace(" ", "-")) ```
Renaming file names containing spaces
7,469,374
5
2011-09-19T10:18:20Z
7,469,492
15
2011-09-19T10:29:00Z
[ "python", "file", "operating-system", "rename" ]
I am writing a simple Python script to rename all files in a directory to replace all spaces in the file name with hyphens. I have the following which is crashing on os.rename ``` import os path = os.getcwd() filenames = os.listdir(path) for filename in filenames: os.rename(os.path.join(path + filename), os.pat...
I think it's just because you have the syntax wrong in your call to os.path.join, the items you're joining should be supplied as two distinct arguments, separated by a comma. This works fine for me: ``` Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credit...
How to construct relative url, given two absolute urls in Python
7,469,573
12
2011-09-19T10:35:10Z
7,469,728
8
2011-09-19T10:48:00Z
[ "python", "urlparse" ]
Is there a builtin function to get url like this: `../images.html` given a base url like this: `http://www.example.com/faq/index.html` and a target url such as `http://www.example.com/images.html` I checked urlparse module. What I want is counterpart of the urljoin() function.
You could use [urlparse.urlparse](http://docs.python.org/library/urlparse.html#urlparse.urlparse) to find the paths, and the posixpath version of [os.path.relname](http://docs.python.org/library/os.path.html#os.path.relpath) to find the relative path. (Warning: This works for Linux, but may not for Windows): ``` impo...
matplotlib.pcolor very slow. alternatives?
7,470,288
8
2011-09-19T11:35:55Z
7,474,721
9
2011-09-19T17:15:57Z
[ "python", "numpy", "matplotlib" ]
I want to plot a 2D array (roughly 1000x1000) with the values corresponding to a color scale. So I used matplotlib.pcolor, which did just that but for some reason it is super slow when it gets to those dimensions (like 2 minutes or so just to plot). What is the reason for that? Would converting the float values to int1...
**`imshow`** will be much faster. `pcolor` returns a PolyCollection, which is going to be fairly slow with a million elements, whereas imshow is just an image. Note that the indexing in pcolor is slightly different than imshow, though you may not need to worry about it depending on how you used pcolor. Also, often whe...
matplotlib.pcolor very slow. alternatives?
7,470,288
8
2011-09-19T11:35:55Z
32,048,253
8
2015-08-17T10:37:55Z
[ "python", "numpy", "matplotlib" ]
I want to plot a 2D array (roughly 1000x1000) with the values corresponding to a color scale. So I used matplotlib.pcolor, which did just that but for some reason it is super slow when it gets to those dimensions (like 2 minutes or so just to plot). What is the reason for that? Would converting the float values to int1...
As a note for future googlers, there is also [`pcolormesh`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.pcolormesh) and [`pcolorfast`](http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.pcolorfast). The documentation for `pcolormesh` states that: > pcolormesh is similar to pcolor(), but uses...
remove certain attributes from HTML tags
7,470,333
6
2011-09-19T11:38:35Z
7,472,003
8
2011-09-19T13:48:58Z
[ "python", "html-parsing", "beautifulsoup", "lxml" ]
How can I remove certain attributes such as id, style, class, etc. from HTML code? I thought I could use the [lxml.html.clean module](http://lxml.de/lxmlhtml.html#cleaning-up-html), but as it turned out I can only remove style attributes with `Clean(style=True).clean_html(code)`. I'd prefer not to use regular expressi...
`cleaner.Cleaner.__call__` has a `safe_attrs_only` parameter. When set to `True`, only attributes in `clean.defs.safe_attrs` are preserved. You can remove any or all attributes by changing `clean.defs.safe_attrs`. Just be sure to change it back when you are done. ``` import lxml.html.clean as clean code = '<tr id="ct...
python's super and __new__ confused me
7,471,255
21
2011-09-19T12:54:25Z
7,471,469
28
2011-09-19T13:09:47Z
[ "python", "class-method" ]
As what I just learned, I can use super this way: super(class, obj\_of\_class-or-\_subclass\_of\_class) Code goes below: ``` #Case 1 class A(object): def __init__(self): print "A init" class B(A): def __init__(self): print "B init" super(B, self).__init__() #ok, I can invoke A's __in...
From the [Python release notes](http://www.python.org/download/releases/2.2/descrintro/#__new__) on overriding the `__new__` method: > `__new__` is a **static method**, not a class method. I initially thought it > would have to be a class method, and that's why I added the > classmethod primitive. Unfortunately, with ...
What is the difference between session.commit() and session.flush()?
7,471,495
7
2011-09-19T13:12:01Z
7,471,557
7
2011-09-19T13:17:16Z
[ "python", "sqlalchemy", "pylons" ]
Does anybody know what the main difference between `session.commit()` and `session.flush()` in SQLAlchemy is?
Here are some relevant quotes from the [documentation](http://www.sqlalchemy.org/docs/orm/session.html#flushing). **flush**: > When the `Session` is used with its default configuration, the flush > step is nearly always done transparently. Specifically, **the flush > occurs before any individual Query is issued, as w...
How to convert Python dictionary object to numpy array
7,471,872
3
2011-09-19T13:39:44Z
7,472,034
8
2011-09-19T13:50:32Z
[ "python", "numpy" ]
I have python dict object with key as datetime.date object and values as tuple objects: ``` >>> data_dict {datetime.date(2006, 1, 1): (5, 3), datetime.date(2006, 1, 2): (8, 8), datetime.date(2006, 1, 3): (8, 5), datetime.date(2006, 1, 4): (3, 3), datetime.date(2006, 1, 5): (3, 3), datetime.date(2006, 1, 6): (4, 3...
The following will do it: ``` arr = np.array([(k,)+v for k,v in data_dict.iteritems()], \ dtype=[('date', '|O4'), ('high', '<f8'), ('low', '<f8')]) ``` If you then wish to use `arr` as a [`recarray`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.recarray.html), you could use: ``` arr = arr.view(...
Why cannot pass print function to dir() in python?
7,472,218
9
2011-09-19T14:06:02Z
7,472,283
15
2011-09-19T14:10:07Z
[ "python" ]
Is print a built-in function? If it is, why I cannot run `dir(print)`? `dir` is a built-in function and `dir(dir)` works well. So it looks very strange to me that `dir(print)` could not work.
In python 2 print is a statement and not a function and you can't put a statement as a function argument, in the other hand in python3 [print is a function](http://docs.python.org/release/3.0.1/whatsnew/3.0.html#print-is-a-function) so you can do `dir(print)`.
Continue after exception raising in iterator/generator in python
7,472,786
3
2011-09-19T14:49:02Z
7,472,850
7
2011-09-19T14:53:39Z
[ "python", "exception" ]
Is there any way in Python to continue iterating after exception throwed by iterator/generator? Like in code below, is there any way to skip ZeroDivisionError and continue looping through `gener()` without modyfying `run()` function? ``` def gener(): a = [1,2,3,4,0, 5, 6,7, 8, 0, 9] for i in a: yield 2...
The logical place for the `try/except` would be the place where the offending calculation takes place: ``` def gener(): a = [1,2,3,4,0, 5, 6,7, 8, 0, 9] for i in a: try: yield 2/i except ZeroDivisionError: pass ```
Python readline() from a string?
7,472,839
19
2011-09-19T14:52:25Z
7,472,878
43
2011-09-19T14:55:25Z
[ "python" ]
In python, is there a built-in way to do a readline() on string? I have a large chunk of data and want to strip off just the first couple lines w/o doing split() on the whole string. Hypothetical example: ``` def handleMessage(msg): headerTo = msg.readline() headerFrom= msg.readline() sendMessage(headerTo,h...
## Python 2 You can use [StringIO](http://docs.python.org/library/stringio.html): ``` >>> msg = "Bob Smith\nJane Doe\nJane,\nPlease order more widgets\nThanks,\nBob\n" >>> msg 'Bob Smith\nJane Doe\nJane,\nPlease order more widgets\nThanks,\nBob\n' >>> import StringIO >>> buf = StringIO.StringIO(msg) >>> buf.readline(...
Python readline() from a string?
7,472,839
19
2011-09-19T14:52:25Z
7,472,921
12
2011-09-19T14:58:28Z
[ "python" ]
In python, is there a built-in way to do a readline() on string? I have a large chunk of data and want to strip off just the first couple lines w/o doing split() on the whole string. Hypothetical example: ``` def handleMessage(msg): headerTo = msg.readline() headerFrom= msg.readline() sendMessage(headerTo,h...
Why not just only do as many splits as you need? Since you're using all of the resulting parts (including the rest of the string), loading it into some other buffer object and then reading it back out again is probably going to be slower, not faster (plus the overhead of function calls). If you want the first `N` line...
PyDev unittesting: How to capture text logged to a logging.Logger in "Captured Output"
7,472,863
21
2011-09-19T14:54:18Z
7,483,862
19
2011-09-20T10:43:22Z
[ "python", "unit-testing", "logging", "pydev" ]
I am using PyDev for development and unit-testing of my Python application. As for unit-testing, everything works great behalf the fact that content logged to any logging. Logger is not captured by the "Captured output" of PyDev. I already forward everything logged to the standard output like this: ``` import sys log...
The issue is that the `unittest` runner replaces `sys.stdout`/`sys.stderr` before the testing starts, and the `StreamHandler` is still writing to the original `sys.stdout`. If you assign the 'current' `sys.stdout` to the handler, it should work (see the code below). ``` import sys import unittest import logging logg...
PyDev unittesting: How to capture text logged to a logging.Logger in "Captured Output"
7,472,863
21
2011-09-19T14:54:18Z
15,969,985
10
2013-04-12T11:17:51Z
[ "python", "unit-testing", "logging", "pydev" ]
I am using PyDev for development and unit-testing of my Python application. As for unit-testing, everything works great behalf the fact that content logged to any logging. Logger is not captured by the "Captured output" of PyDev. I already forward everything logged to the standard output like this: ``` import sys log...
I grew tired of having to manually add [Fabio's great code](http://stackoverflow.com/a/7483862/321973) to all `setUp`s, so I subclassed `unittest.TestCase` with some `__metaclass__`ing: ``` class LoggedTestCase(unittest.TestCase): __metaclass__ = LogThisTestCase logger = logging.getLogger("unittestLogger") ...
Unittest's assertEqual and iterables - only check the contents
7,473,071
39
2011-09-19T15:08:52Z
7,473,137
64
2011-09-19T15:13:09Z
[ "python", "unit-testing", "assert", "iterable" ]
Is there a 'decent' way in unittest to check the equality of the contents of two iterable objects? I am using a lot of tuples, lists and numpy arrays and I usually only want to test for the contents and not for the type. Currently I am simply casting the type: ``` self.assertEqual (tuple (self.numpy_data), tuple (self...
In python >= 2.7 : * if you don't care of the order of the content, you have the [assertItemsEqual(actual\_iterable, expected\_iterable)](http://docs.python.org/library/unittest.html?highlight=assertequal#unittest.TestCase.assertItemsEqual) method * if you care about the order of the content, you have the [assertSeque...
Unittest's assertEqual and iterables - only check the contents
7,473,071
39
2011-09-19T15:08:52Z
7,473,187
9
2011-09-19T15:16:02Z
[ "python", "unit-testing", "assert", "iterable" ]
Is there a 'decent' way in unittest to check the equality of the contents of two iterable objects? I am using a lot of tuples, lists and numpy arrays and I usually only want to test for the contents and not for the type. Currently I am simply casting the type: ``` self.assertEqual (tuple (self.numpy_data), tuple (self...
You can always add your own assertion methods to your TestCase class: ``` def assertSequenceEqual(self, it1, it2): self.assertEqual(tuple(it1), tuple(it2)) ``` or take a look at how 2.7 defined it: <http://hg.python.org/cpython/file/14cafb8d1480/Lib/unittest/case.py#l621>
A* Algorithm does not find shortest path
7,473,441
4
2011-09-19T15:35:33Z
7,473,899
7
2011-09-19T16:04:10Z
[ "python", "algorithm", "a-star" ]
I am trying to implement the A\* algorithm in python but have hit a problem when trying to find the path of this map: ``` X X X X X X X S = Start 0 0 0 X 0 0 0 E = End 0 S 0 X 0 E 0 X = Wall 0 0 0 X 0 0 0 0 0 0 0 0 0 0 ``` I am using the Manhattan method. My implementation does find a path, but not the sh...
You seem to be constructing a new open list for each node, which contains only that node's neighbors. This essentially makes your search a form of a depth-first search, while A\* should be a best-first search. You need to use one open list which will be updated with each node's neighbors as you visit that node. The ol...
Celery tasks profiling
7,473,537
5
2011-09-19T15:41:58Z
7,473,901
12
2011-09-19T16:04:26Z
[ "python", "profiling", "celery", "django-celery" ]
As I can see in `top` utility `celery` procecess consume a lot of CPU time. So I want to profile it. I can do it manually on developer machine like so: ``` python -m cProfile -o test-`date +%Y-%m-%d-%T`.prof ./manage.py celeryd -B ``` But to have accurate timings I need to profile it on production machine. On that m...
I think you're confusing two separate issues. You could be processing too many individual tasks or an individual task could be inefficient. You may know which of these is the problem, but it's not clear from your question which it is. To track how many tasks are being processed I suggest you look at [celerymon](https...
How to get Inserted or selected row id in postgres using python
7,474,176
9
2011-09-19T16:26:53Z
7,475,376
10
2011-09-19T18:12:28Z
[ "python", "postgresql", "upsert" ]
My postgres query is: ``` query = """INSERT INTO statustable(value) SELECT '%s' WHERE NOT EXISTS (SELECT id, value FROM statustable WHERE value = '%s') RETURNING id""" % (status, status) cursor_postgres.execute(query) conn_postgres.commit() statusId = cursor_postgres.fetch...
I can't say I fully understand your motivation for insisting on a single query. I think your best bet is to have two simple queries: 1. `SELECT id FROM statustable WHERE value = '%s'`. This gives you the id if the entry exists, in which case skip step 2; 2. `INSERT INTO statustable(value) VALUES('%s') RETURNING id`. T...
Display tick and cross icons for a property in the Django administration console
7,474,212
6
2011-09-19T16:29:31Z
7,474,429
14
2011-09-19T16:48:41Z
[ "python", "django", "django-admin" ]
In the Django admin if the field is a BooleanField or NullBooleanField, Django will display a pretty "on" or "off" icon instead of True or False. Now, I don't really have a BooleanField in my model by I do have a property fior which I'd like to display the icons but when I try doing so, Django screams that `'SomeAdmin...
You don't want to use `list_filter`. The property you're looking for is [`list_display`](https://docs.djangoproject.com/en/1.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display). The documentation offers an example of how you can create a column that behaves like a boolean in the display. In short, you do...
pyinstaller, NameError: global name 'quit' is not defined
7,474,291
3
2011-09-19T16:36:29Z
7,474,346
10
2011-09-19T16:41:59Z
[ "python", "pyinstaller" ]
Gents, I have a python script which runs just fine, but after running pyinstaller, I get the following on any quit() or exit() commands... Makespec file: ``` # -*- mode: python -*- a = Analysis([os.path.join(HOMEPATH,'support/_mountzlib.py'), os.path.join(HOMEPATH,'support/useUnicode.py'), 'icinga.py'], ...
That is because there is no `quit` command. You are looking for [`sys.exit`](http://docs.python.org/library/sys.html#sys.exit).
Why is large integer division faster than slicing (numeric) strings, for accessing individual digits?
7,474,628
5
2011-09-19T17:06:12Z
7,474,684
10
2011-09-19T17:12:38Z
[ "python", "computer-science" ]
I am doing a (typical) assignment of finding primes. I thought I'd be clever and, for large numbers, skip the division process with this trick: ``` def div5(candidate): return str(candidate)[-1] == "5" ``` Adding 5 to itself a few thousand times seems like a waste (I only need the last member), but I wanted to be...
``` % python -mtimeit "str(2147483645)" 1000000 loops, best of 3: 0.321 usec per loop % python -mtimeit "2147483645 % 5" 10000000 loops, best of 3: 0.0351 usec per loop % python -mtimeit "'2147483645'[-1]" 10000000 loops, best of 3: 0.0349 usec per loop ``` I'd say the bottleneck is converting to a string.
How to zip two lists of lists in Python?
7,474,717
16
2011-09-19T17:15:43Z
7,474,755
10
2011-09-19T17:18:38Z
[ "python", "list", "merge", "zip", "nested" ]
I have two lists of lists that have equivalent numbers of items. The two lists look like this: ``` L1 = [[1, 2], [3, 4], [5, 6]] L2 =[[a, b], [c, d], [e, f]] ``` I am looking to create one list that looks like this: ``` Lmerge = [[1, 2, a, b], [3, 4, c, d], [5, 6, e, f]] ``` I was attempting to use `zip()` somethi...
``` >>> L1 = [[1, 2], [3, 4], [5, 6]] >>> L2 =[["a", "b"], ["c", "d"], ["e", "f"]] >>> [x + y for x,y in zip(L1,L2)] [[1, 2, 'a', 'b'], [3, 4, 'c', 'd'], [5, 6, 'e', 'f']] ``` Or, ``` >>> [sum(x,[]) for x in zip(L1,L2)] [[1, 2, 'a', 'b'], [3, 4, 'c', 'd'], [5, 6, 'e', 'f']] ``` or, ``` >>> import itertools >>> [lis...
How to zip two lists of lists in Python?
7,474,717
16
2011-09-19T17:15:43Z
7,474,813
17
2011-09-19T17:23:34Z
[ "python", "list", "merge", "zip", "nested" ]
I have two lists of lists that have equivalent numbers of items. The two lists look like this: ``` L1 = [[1, 2], [3, 4], [5, 6]] L2 =[[a, b], [c, d], [e, f]] ``` I am looking to create one list that looks like this: ``` Lmerge = [[1, 2, a, b], [3, 4, c, d], [5, 6, e, f]] ``` I was attempting to use `zip()` somethi...
``` >>> map(list.__add__, L1, L2) [[1, 2, 'a', 'b'], [3, 4, 'c', 'd'], [5, 6, 'e', 'f']] ```
What migration order does South follow across different apps?
7,474,745
8
2011-09-19T17:18:01Z
7,474,845
12
2011-09-19T17:27:31Z
[ "python", "django", "django-south" ]
I've recently begun using South for migrations in my Django project. All was going well until recently when I ran into a peculiar issue. I have two apps in my project, say, App-A and App-B. A model in App-A has a foreign key to a model in App-B. When I've been trying to build my system, I ran `syndb` which created all...
South migrates apps in the order they appear in the `INSTALLED_APPS` tuple in settings.py. So just make sure App-B comes before App-A in your settings.py, and it should work :)
What migration order does South follow across different apps?
7,474,745
8
2011-09-19T17:18:01Z
7,480,386
16
2011-09-20T05:05:57Z
[ "python", "django", "django-south" ]
I've recently begun using South for migrations in my Django project. All was going well until recently when I ran into a peculiar issue. I have two apps in my project, say, App-A and App-B. A model in App-A has a foreign key to a model in App-B. When I've been trying to build my system, I ran `syndb` which created all...
This explained it <https://south.readthedocs.io/en/latest/dependencies.html>. > Migrations for apps are nice ‘n all, but when you start writing a > large project, with a lot of apps, you realise you have foreign key > relationships between apps and working out what order migrations would > need to be applied in for ...
python lxml append element after another element
7,474,972
7
2011-09-19T17:38:34Z
7,475,897
18
2011-09-19T18:57:02Z
[ "python", "html", "append", "lxml" ]
I have the following HTML markup ``` <div id="contents"> <div id="content_nav"> something goes here </div> <p> some contents </p> </div> ``` To fix some CSS issue, I want to append a div tag `<div style="clear:both"></div>` after the `content_nav` div like this ``` <div id="content...
Instead of appending to `contentnav`, go up to the parent (`contentdiv`) and `insert` the new `div` at a particular index. To find that index, use `contentdiv.index(contentnav)`, which gives the index of `contentnav` within `contentdiv`. Adding one to that gives the desired index. ``` import lxml.etree as ET content=...
mysql_config not found when installing mysqldb python interface
7,475,223
200
2011-09-19T18:00:25Z
7,475,296
276
2011-09-19T18:06:23Z
[ "python", "linux", "ssh", "mysql-python" ]
I am trying to get a Python script to run on the linux server I'm connected to via ssh. The script uses mysqldb. I have all the other components I need, but when I try to install mySQLdb via setuptools like so:, ``` python setup.py install ``` I get the following error report related to the `mysql_config` command. `...
mySQLdb is a python interface for mysql, but it is not mysql itself. And apparently mySQLdb needs the command 'mysql\_config', so you need to install that first. Can you confirm that you did or did not install mysql itself, by running "mysql" from the shell? That should give you a response other than "mysql: command n...
mysql_config not found when installing mysqldb python interface
7,475,223
200
2011-09-19T18:00:25Z
11,805,493
12
2012-08-04T02:41:14Z
[ "python", "linux", "ssh", "mysql-python" ]
I am trying to get a Python script to run on the linux server I'm connected to via ssh. The script uses mysqldb. I have all the other components I need, but when I try to install mySQLdb via setuptools like so:, ``` python setup.py install ``` I get the following error report related to the `mysql_config` command. `...
The commands (mysql too) mPATH might be missing. `export PATH=$PATH:/usr/local/mysql/bin/`
mysql_config not found when installing mysqldb python interface
7,475,223
200
2011-09-19T18:00:25Z
12,708,157
15
2012-10-03T12:06:52Z
[ "python", "linux", "ssh", "mysql-python" ]
I am trying to get a Python script to run on the linux server I'm connected to via ssh. The script uses mysqldb. I have all the other components I need, but when I try to install mySQLdb via setuptools like so:, ``` python setup.py install ``` I get the following error report related to the `mysql_config` command. `...
I got the same error while trying to install `mysql-python`. This is how I fixed it. ``` sudo PATH=/usr/local/mysql/bin/:$PATH pip install mysql-python ``` The problem was that the installer could not find the mysql\_config in the default path. Now it can ..and it worked.. ``` 15 warnings generated. clang -bun...
mysql_config not found when installing mysqldb python interface
7,475,223
200
2011-09-19T18:00:25Z
12,814,672
119
2012-10-10T08:01:47Z
[ "python", "linux", "ssh", "mysql-python" ]
I am trying to get a Python script to run on the linux server I'm connected to via ssh. The script uses mysqldb. I have all the other components I need, but when I try to install mySQLdb via setuptools like so:, ``` python setup.py install ``` I get the following error report related to the `mysql_config` command. `...
I was installing `python-mysql` on Ubuntu 12.04 using ``` pip install mysql-python ``` First I had the same problem: ``` Not Found "mysql_config" ``` This worked for me ``` $ sudo apt-get install libmysqlclient-dev ``` Then I had this problem: ``` ... _mysql.c:29:20: error fatal: Python.h: No existe el archivo o...
mysql_config not found when installing mysqldb python interface
7,475,223
200
2011-09-19T18:00:25Z
13,196,984
14
2012-11-02T14:17:06Z
[ "python", "linux", "ssh", "mysql-python" ]
I am trying to get a Python script to run on the linux server I'm connected to via ssh. The script uses mysqldb. I have all the other components I need, but when I try to install mySQLdb via setuptools like so:, ``` python setup.py install ``` I get the following error report related to the `mysql_config` command. `...
I fixed this problem with the following steps: ``` sudo apt-get install libmysqlclient-dev sudo apt-get install python-dev sudo python setup.py install ```
mysql_config not found when installing mysqldb python interface
7,475,223
200
2011-09-19T18:00:25Z
18,174,157
20
2013-08-11T16:31:00Z
[ "python", "linux", "ssh", "mysql-python" ]
I am trying to get a Python script to run on the linux server I'm connected to via ssh. The script uses mysqldb. I have all the other components I need, but when I try to install mySQLdb via setuptools like so:, ``` python setup.py install ``` I get the following error report related to the `mysql_config` command. `...
The below worked for me on Ubuntu 12.04 LTS: ``` apt-get install libmysqlclient-dev python-dev ``` All though it worked, i still went ahead to do the below: ``` export PATH=$PATH:/usr/local/mysql/bin/ ```
mysql_config not found when installing mysqldb python interface
7,475,223
200
2011-09-19T18:00:25Z
28,414,414
8
2015-02-09T16:24:09Z
[ "python", "linux", "ssh", "mysql-python" ]
I am trying to get a Python script to run on the linux server I'm connected to via ssh. The script uses mysqldb. I have all the other components I need, but when I try to install mySQLdb via setuptools like so:, ``` python setup.py install ``` I get the following error report related to the `mysql_config` command. `...
On Red Hat I had to do ``` sudo yum install mysql-devel gcc gcc-devel python-devel sudo easy_install mysql-python ``` Then it worked.
Learning Python the Hard Way: Ex16 Extra Credit
7,477,041
10
2011-09-19T20:40:37Z
7,477,070
15
2011-09-19T20:43:39Z
[ "python" ]
I'm stumped when it comes to the 3rd question on the extra credit. The code in question is this: ``` target.write(line1) target.write("\n") target.write(line2) target.write("\n") target.write(line3) target.write("\n") ``` The question asks you to "use strings, formats, and escapes to print out line1, line2, and line3...
How about this? ``` target.write("%s\n%s\n%s\n" % (line1, line2, line3)) ```
Inheriting from decorated classes
7,477,311
3
2011-09-19T21:08:23Z
7,479,189
7
2011-09-20T01:43:52Z
[ "python", "inheritance", "decorator" ]
I'm trying to decorate a class with another class. I also want to inherit from the decorated class, but I get some errors. Here's my code: ``` class Decorator: def __init__(self, decorated): pass @Decorator class Foo: pass class Goo(Foo): pass ``` The error I get when I try to subclass from `Foo...
I'll try to answer the "what are those parameters" question. This code: ``` @Decorator class Foo: pass ``` is equivalent to: ``` class Foo: pass Foo = Decorator(Foo) ``` This means that `Foo` ends up being an **instance** of the `Decorator` class instead of being a class. When you try to use this instance ...
Matrix multiplication for sparse matrices in Python
7,477,733
4
2011-09-19T21:51:42Z
7,478,393
9
2011-09-19T23:14:55Z
[ "python", "multidimensional-array", "matrix", "numpy" ]
I want to multiply a sparse matrix A, with a matrix B which has 0, -1, or 1 as elements. To reduce the complexity of the matrix multiplication, I can ignore items if they are 0, or go ahead and add the column without multiplication if the item is 1, or subs. if it's -1. The discussion about this is here: [Random proje...
Have you looked at `scipy.sparse`? There's no point in re-inventing the wheel, here. Sparse matricies are a fairly standard thing. (In the example, I'm using a `300000x4` matrix for easier printing after the multiplication. A `300000x1000` matrix shouldn't be any problem, though. This will be much faster than multiply...
Import a module in Python only if it doesn't already exist
7,478,075
7
2011-09-19T22:31:19Z
7,478,115
14
2011-09-19T22:35:41Z
[ "python", "module" ]
I want to use a module, e.g. BeautifulSoup, in my Python code, so I usually add this to the top of the file: ``` from BeautifulSoup import BeautifulSoup ``` However, when I distribute the module I'm writing, others may not have BeautifulSoup, so I'll just include it in my directory structure like so: ``` Mode ...
Usually the following pattern is used to handle this situation in Python. First rename your BeautifulSoup module something else, e.g. MyBeautifulSoup Then: ``` try: import BeautifulSoup # Standard except ImportError: import MyBeautifulSoup as BeautifulSoup # internal distribution ```
Create dynamic URLs in Flask with url_for()
7,478,366
60
2011-09-19T23:11:03Z
7,478,705
96
2011-09-20T00:02:51Z
[ "python", "flask" ]
Half of my Flask routes requires a variable say, `/<variable>/add` or `/<variable>/remove`. How do I create links to those locations? `url_for()` takes one argument for the function to route to but I can't add arguments?
It takes keyword arguments for the variables: ``` url_for('add', variable=foo) ```
Create dynamic URLs in Flask with url_for()
7,478,366
60
2011-09-19T23:11:03Z
7,488,983
19
2011-09-20T17:10:39Z
[ "python", "flask" ]
Half of my Flask routes requires a variable say, `/<variable>/add` or `/<variable>/remove`. How do I create links to those locations? `url_for()` takes one argument for the function to route to but I can't add arguments?
Refer to [the Flask API document for `flask.url_for()`](http://flask.pocoo.org/docs/api/#flask.url_for) Other sample snippets of usage for linking js or css to your template are below. ``` <script src="{{ url_for('static', filename='jquery.min.js') }}"></script> <link rel=stylesheet type=text/css href="{{ url_for('s...
SQLAlchemy classes across files
7,478,403
29
2011-09-19T23:16:06Z
7,479,122
38
2011-09-20T01:28:58Z
[ "python", "sqlalchemy" ]
I'm trying to figure out how to have SQLAlchemy classes spread across several files, and I can for my life not figure out how to do it. I am pretty new to SQLAlchemy so forgive me if this question is trivial.. Consider these 3 classes in *each their own file*: **A.py:** ``` from sqlalchemy import * from main import ...
The simplest solution to your problem will be to take `Base` out of the module that imports `A`, `B` and `C`; Break the cyclic import. ## base.py ``` from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() ``` ## a.py ``` from sqlalchemy import * from base import Base from sqlalchemy.orm i...
High quality, simple random password generator
7,479,442
55
2011-09-20T02:34:16Z
7,479,473
28
2011-09-20T02:38:47Z
[ "python", "security", "random", "passwords" ]
I'm interested in creating a very simple, high (cryptographic) quality random password generator. Is there a better way to do this? ``` import os, random, string length = 13 chars = string.ascii_letters + string.digits + '!@#$%^&*()' random.seed = (os.urandom(1024)) print ''.join(random.choice(chars) for i in range(...
[XKCD](http://xkcd.com/936/) has a great explanation of why **what you think** are strong passwords **aren't**. ![http://xkcd.com/936/](http://imgs.xkcd.com/comics/password_strength.png) > To anyone who understands information theory and security and is in an > infuriating argument with someone who does not (possibly...
High quality, simple random password generator
7,479,442
55
2011-09-20T02:34:16Z
7,479,754
12
2011-09-20T03:23:58Z
[ "python", "security", "random", "passwords" ]
I'm interested in creating a very simple, high (cryptographic) quality random password generator. Is there a better way to do this? ``` import os, random, string length = 13 chars = string.ascii_letters + string.digits + '!@#$%^&*()' random.seed = (os.urandom(1024)) print ''.join(random.choice(chars) for i in range(...
Just two days ago, Kragen Javier Sitaker posted a program to do this at <http://lists.canonical.org/pipermail/kragen-hacks/2011-September/000527.html> (gone now - try <https://github.com/jesterpm/bin/blob/master/mkpasswd>) Generate a random, memorizable password: <http://xkcd.com/936/> Example run: kragen at inexora...
High quality, simple random password generator
7,479,442
55
2011-09-20T02:34:16Z
7,480,271
39
2011-09-20T04:48:49Z
[ "python", "security", "random", "passwords" ]
I'm interested in creating a very simple, high (cryptographic) quality random password generator. Is there a better way to do this? ``` import os, random, string length = 13 chars = string.ascii_letters + string.digits + '!@#$%^&*()' random.seed = (os.urandom(1024)) print ''.join(random.choice(chars) for i in range(...
The difficult thing with passwords is to make them strong enough and still be able to remember them. If the password is not meant to be remembered by a human being, then it is not really a password. You use Python's `os.urandom()`: that's good. For any practical purpose (even cryptography), the output of `os.urandom()...
High quality, simple random password generator
7,479,442
55
2011-09-20T02:34:16Z
9,368,832
7
2012-02-20T21:41:25Z
[ "python", "security", "random", "passwords" ]
I'm interested in creating a very simple, high (cryptographic) quality random password generator. Is there a better way to do this? ``` import os, random, string length = 13 chars = string.ascii_letters + string.digits + '!@#$%^&*()' random.seed = (os.urandom(1024)) print ''.join(random.choice(chars) for i in range(...
Another implemention of the XKCD method: ``` #!/usr/bin/env python import random import re # apt-get install wbritish def randomWords(num, dictionary="/usr/share/dict/british-english"): r = random.SystemRandom() # i.e. preferably not pseudo-random f = open(dictionary, "r") count = 0 chosen = [] for i in ran...
High quality, simple random password generator
7,479,442
55
2011-09-20T02:34:16Z
13,901,912
7
2012-12-16T13:47:49Z
[ "python", "security", "random", "passwords" ]
I'm interested in creating a very simple, high (cryptographic) quality random password generator. Is there a better way to do this? ``` import os, random, string length = 13 chars = string.ascii_letters + string.digits + '!@#$%^&*()' random.seed = (os.urandom(1024)) print ''.join(random.choice(chars) for i in range(...
implementing @Thomas Pornin solution ``` import M2Crypto import string def random_password(length=10): chars = string.ascii_uppercase + string.digits + string.ascii_lowercase password = '' for i in range(length): password += chars[ord(M2Crypto.m2.rand_bytes(1)) % len(chars)] return password ``...
DJANGO_SETTINGS_MODULE is undefined
7,479,493
5
2011-09-20T02:41:05Z
14,872,658
8
2013-02-14T10:26:17Z
[ "python", "django", "python-idle" ]
when i input `from django.db import models` into IDLE,the result throw a exception named `Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.` why does this exception occur and how i can fix it
You can use **python manage.py shell** instead of using **IDLE**. **manage.py** reads and uses django settings including `DJANGO_SETTINGS_MODULE`.