content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Is there a matplotlib equivalent of MATLAB's datacursormode?
In MATLAB, one can use datacursormode to add annotation to a graph when user mouses over. Is there such thing in matplotlib? Or I need to write my own event using matplotlib.text.Annotation?
A:
Late Edit / Shameless Plug: This is now available (with mu... | Is there a matplotlib equivalent of MATLAB's datacursormode? | In MATLAB, one can use datacursormode to add annotation to a graph when user mouses over. Is there such thing in matplotlib? Or I need to write my own event using matplotlib.text.Annotation?
| [
"Late Edit / Shameless Plug: This is now available (with much more functionality) as mpldatacursor. Calling mpldatacursor.datacursor() will enable it for all matplotlib artists (including basic support for z-values in images, etc).\n\nAs far as I know, there isn't one already implemented, but it's not too hard to w... | [
64
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0004652439_matplotlib_python.txt |
Q:
Encoding and decoding in Python with MD5( )
Running this code on Ubuntu 10.10 in Python 3.1.1
I am getting the following error:
UnicodeDecodeError: 'utf8' codec can't decode byte 0xd3 in position 0: invalid continuation byte
And the position of the error changes depending on when I run the following code:
(not the... | Encoding and decoding in Python with MD5( ) | Running this code on Ubuntu 10.10 in Python 3.1.1
I am getting the following error:
UnicodeDecodeError: 'utf8' codec can't decode byte 0xd3 in position 0: invalid continuation byte
And the position of the error changes depending on when I run the following code:
(not the real keys or secret)
sandboxAPIKey = "wed23hf5yx... | [
"When you try to decode a bytearray into a string it tries to match sequentially the bytes to valid characters of an encoding set(by default, utf-8), the exception is being raised because it can't match a sequence of bytes to a valid character in the utf-8 alphabet.\nThe same will happen if you try to decode it usi... | [
4
] | [] | [] | [
"character_encoding",
"encoding",
"python"
] | stackoverflow_0004674465_character_encoding_encoding_python.txt |
Q:
RuntimeError: maximum recursion depth exceeded
I have the following code which extracts two strings from text by matching different patterns
def urlChange(self, event):
text = self.txtUrl.GetValue()
matches = re.findall('GET (\S+).*Host: (\S+).*Cookie: (.+\S)\s*', text, re.DOTALL or re.MULTILINE)
if matches... | RuntimeError: maximum recursion depth exceeded | I have the following code which extracts two strings from text by matching different patterns
def urlChange(self, event):
text = self.txtUrl.GetValue()
matches = re.findall('GET (\S+).*Host: (\S+).*Cookie: (.+\S)\s*', text, re.DOTALL or re.MULTILINE)
if matches:
groups = matches[0]
self.txtUrl.SetValue(gro... | [
"This looks like GUI code?\nIf so I assume that urlChange is called whenever self.txtUrl changes. Therefore when you call self.txtUrl.SetValue(matches[0]) it triggers another call to urlChange, which then repeats and htis the recursion limit.\nJust a guess - would need more context to be sure, but that's the only ... | [
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004668535_python_regex.txt |
Q:
Sorting a list of tuples by date
I would like to sort and return a section of a tuple with it sorted by date.
I'd only like to sort the first to the 4th record (tuple[:3]) and print it.
tuple = [('Dec 1, 2010', '7.41', '7.60', '7.37'),
('Dec 4, 2010', '7.41', '7.60', '7.37'),
('Dec 2, 2010', '... | Sorting a list of tuples by date | I would like to sort and return a section of a tuple with it sorted by date.
I'd only like to sort the first to the 4th record (tuple[:3]) and print it.
tuple = [('Dec 1, 2010', '7.41', '7.60', '7.37'),
('Dec 4, 2010', '7.41', '7.60', '7.37'),
('Dec 2, 2010', '7.41', '7.60', '7.37'),
('De... | [
"Why are you getting by date? isn't the first element of the tuple what you are looking for? \nsorted(records[:3], key=operator.itemgetter(0), reverse=True)\n\nBy the way, you should transform the string to an actual date before you compare them. Maybe:\nfrom datetime import datetime\ndef get_date(record):\n re... | [
8,
1,
0,
0
] | [] | [] | [
"date",
"python",
"sorting",
"tuples"
] | stackoverflow_0004672852_date_python_sorting_tuples.txt |
Q:
Python function parameter count
Possible Duplicate:
How to find out the arity of a method in Python
Given a python function, how do I programmatically determine the number of parameters it takes?
A:
inspect is your friend in this case
>>> def testFunc(arg1, arg2, arg3, additional='test'):
... print arg1
..... | Python function parameter count |
Possible Duplicate:
How to find out the arity of a method in Python
Given a python function, how do I programmatically determine the number of parameters it takes?
| [
"inspect is your friend in this case\n>>> def testFunc(arg1, arg2, arg3, additional='test'):\n... print arg1\n... \n>>> import inspect\n>>> inspect.getargspec(testFunc)\nArgSpec(args=['arg1', 'arg2', 'arg3', 'additional'], varargs=None, keywords=None, defaults=('test',))\n>>> \n\n",
"From outside the function... | [
11,
4,
2
] | [] | [] | [
"metaprogramming",
"python"
] | stackoverflow_0004674875_metaprogramming_python.txt |
Q:
Django memory usage going up with every request
I moved my first Django project from DjangoEurope to Webfaction, and that started an issue looking like a memory leak. With every single request memory usage of the server process goes up about 500kb. It never goes down. This goes on until Webfaction kills it for usi... | Django memory usage going up with every request | I moved my first Django project from DjangoEurope to Webfaction, and that started an issue looking like a memory leak. With every single request memory usage of the server process goes up about 500kb. It never goes down. This goes on until Webfaction kills it for using too much memory.
I can clearly see this when I ref... | [
"I'm afraid I haven't got any definite answers. Graham Dumpleton's tips were most helpfull, but unfortunately he didn't make an answer (just comments), so there is no way to accept his response.\nAlthough I still haven't fully resolved the issue, here are some basic tips for other people having similar problems:\n\... | [
14,
2,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"django",
"memory_leaks",
"mod_wsgi",
"python"
] | stackoverflow_0002293333_django_memory_leaks_mod_wsgi_python.txt |
Q:
Multiple Versions of Python on my Windows machine: Which is the "right" one?
In continuing to research a solution for this question on ServerFault:
https://serverfault.com/questions/221203/mercurial-hook-fails-on-windows
I discovered an interesting and somewhat disturbing thing: I have seem three different versio... | Multiple Versions of Python on my Windows machine: Which is the "right" one? | In continuing to research a solution for this question on ServerFault:
https://serverfault.com/questions/221203/mercurial-hook-fails-on-windows
I discovered an interesting and somewhat disturbing thing: I have seem three different versions of Python on my machine (four if you count the "official" version which doesn't... | [
"For the problem that you mentioned earlier, the mercurial package got installed within python under mercurial home but you are executing scripts under C:\\python26. So you need to install and execute your script under mercurial python \nAs seth mentioned earlier it is perfectly ok to multiple python homes in the s... | [
2,
1,
1,
0,
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0004675159_python_windows.txt |
Q:
How to use non valid identifiers as django form field names
I am not sure if I should post this question here or in serverfault since it involves both django and nginx configuration files.
I have a django view that receives POST data from a form that contains file fields.
The request goes through an nginx module (... | How to use non valid identifiers as django form field names | I am not sure if I should post this question here or in serverfault since it involves both django and nginx configuration files.
I have a django view that receives POST data from a form that contains file fields.
The request goes through an nginx module (upload module) that takes file upload fields, stores them to a di... | [
"Ok, I think I found a way to answer my own question and I hope it helps someone.\nThe form I would use to handle the submitted POST with a field called \"uploadedFile.name\" would look something like this: \nfrom django.forms import Form, fields\ndef UploadForm(Form):\n someField = fields.CharField()\n uploadedFil... | [
7
] | [] | [] | [
"django",
"forms",
"nginx",
"python",
"upload"
] | stackoverflow_0004675103_django_forms_nginx_python_upload.txt |
Q:
Model set fields in Django
I have a Django model that needs to represent a set of data. What is the canonical way to implement this? I don't see a models.SetField() in the documentation. I could use a text field and pickling.
I recognize that this isn't the fastest way to do it, but this part of the code doesn't n... | Model set fields in Django | I have a Django model that needs to represent a set of data. What is the canonical way to implement this? I don't see a models.SetField() in the documentation. I could use a text field and pickling.
I recognize that this isn't the fastest way to do it, but this part of the code doesn't need to be super fast - simplicit... | [
"I'm not exactly sure what you are trying to achieve, but it seems to me your looking for some getter/setter functionality that automatically pickles the values:\nimport cPickle\nclass MyModel(models.Model):\n cpickled_values = models.TextField()\n\n def get_values(self):\n return cPickle.loads(str(sel... | [
1
] | [] | [] | [
"database",
"django",
"python"
] | stackoverflow_0004675539_database_django_python.txt |
Q:
Starting, Stopping, and Continuing the Google App Engine BulkLoader
I have quite of bit of data that I will be uploading into Google App Engine. I want to use the bulkloader to help get it in there. However, I have so much data that I generally use up my CPU quota before it's done. Also, any other problem such a b... | Starting, Stopping, and Continuing the Google App Engine BulkLoader | I have quite of bit of data that I will be uploading into Google App Engine. I want to use the bulkloader to help get it in there. However, I have so much data that I generally use up my CPU quota before it's done. Also, any other problem such a bad internet connection or random computer issue can stop the process.
Is ... | [
"Well, it is in the docs:\n\nIf the transfer is interrupted, you\n can resume the transfer from where it\n left off using the --db_filename=...\n argument. The value is the name of the\n progress file created by the tool,\n which is either a name you provided\n with the --db_filename argument when\n you star... | [
4
] | [] | [] | [
"bulkloader",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004675593_bulkloader_google_app_engine_google_cloud_datastore_python.txt |
Q:
Python - removing double quotation marks " so that script runs
I am using Python scripts to edit the table of many shape files. The following script runs fine, but if there are any " marks in the SIT_FULL_S field, the script errors and shuts down.
gp.CalculateField_management(fc + "\\Parcels.shp","SIT_FULL_S", "!... | Python - removing double quotation marks " so that script runs | I am using Python scripts to edit the table of many shape files. The following script runs fine, but if there are any " marks in the SIT_FULL_S field, the script errors and shuts down.
gp.CalculateField_management(fc + "\\Parcels.shp","SIT_FULL_S", "!SIT_FULL_S!.lstrip('0')", "PYTHON")
arcgisscripting.ExecuteError: ER... | [
"Escape it:\n\"string \\\"inner string\\\"\"\n\nor don't mix quotations:\n'string \"inner string\"'\n\n"
] | [
3
] | [] | [] | [
"arcmap",
"python"
] | stackoverflow_0004675695_arcmap_python.txt |
Q:
Class objects are irregular when assigning functions
Let's say I have a function like this:
def id(x):
return x
I expect to be able to bind it to any object (let's say x),
x.f = id
and be able to do
x.f(1)
=> 1
However, classes are not regular objects because it does not work :
class X(object):
pass
X.... | Class objects are irregular when assigning functions | Let's say I have a function like this:
def id(x):
return x
I expect to be able to bind it to any object (let's say x),
x.f = id
and be able to do
x.f(1)
=> 1
However, classes are not regular objects because it does not work :
class X(object):
pass
X.f = id
x.f(1)
=> unbound method f() must be called with X ... | [
"import inspect\nif inspect.isclass(X):\n X.f = staticmethod(f)\nelse:\n X.f = f\n\nThe issue isn't the assignment; that works fine. It is that functions on classes take self as their first parameter, and your function doesn't. You can get the actual function back with \nX.__dict__['f']\n<function f at 0x023A52... | [
3,
1,
1
] | [] | [] | [
"function",
"functional_programming",
"python"
] | stackoverflow_0004675564_function_functional_programming_python.txt |
Q:
How do you create a transaction that spans multiple statements in Python with MySQLdb?
I know that with an InnoDB table, transactions are autocommit, however I understand that to mean for a single statement? For example, I want to check if a user exists in a table, and then if it doesn't, create it. However there ... | How do you create a transaction that spans multiple statements in Python with MySQLdb? | I know that with an InnoDB table, transactions are autocommit, however I understand that to mean for a single statement? For example, I want to check if a user exists in a table, and then if it doesn't, create it. However there lies a race condition. I believe using a transaction prior to doing the select, will ensure ... | [
"There exists a SELECT ... FOR UPDATE that allows you to lock the rows from being read by another transaction but I believe the records have to exist in the first place. Then you can do as you say, and unlock it once you commit. \nIn your case I think the best approach is to simply set a unique constraint on the us... | [
4,
2
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0004637886_mysql_python.txt |
Q:
How come my python code doesn't work?
def getSize(f):
print StringIO(f)
im = Image.open(StringIO(f))
size = im.size[0], im.size[1]
return size
def download(source_url, g = False, correct_url = True):
try:
socket.setdefaulttimeout(10)
agents = ['Mozilla/4.0 (compatible; MSIE 5.5... | How come my python code doesn't work? | def getSize(f):
print StringIO(f)
im = Image.open(StringIO(f))
size = im.size[0], im.size[1]
return size
def download(source_url, g = False, correct_url = True):
try:
socket.setdefaulttimeout(10)
agents = ['Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)','Mozilla/4.0 (compatible... | [
"The problem is that your Accept-Encoding states gzip so you're probably getting a gzipped image. \nI just tried your code with your gzip decompression on and it works without any problems.\n pic = download(\"http://media2.ct.yelpcdn.com/photo/2MdauidaMUazuew2h0pdgQ/l\", g=True)\n s = getSize(pic)\n\nSo does ... | [
3
] | [] | [] | [
"http",
"python",
"python_imaging_library"
] | stackoverflow_0004675853_http_python_python_imaging_library.txt |
Q:
default model field attribute in Django
I have a Django model:
@staticmethod
def getdefault():
print "getdefault called"
return cPickle.dumps(set())
_applies_to = models.TextField(db_index=True, default=getdefault)
For some reason, getdefault() is never called, even as I construct ins... | default model field attribute in Django | I have a Django model:
@staticmethod
def getdefault():
print "getdefault called"
return cPickle.dumps(set())
_applies_to = models.TextField(db_index=True, default=getdefault)
For some reason, getdefault() is never called, even as I construct instances of this model and save them to the dat... | [
"Remove the staticmethod decorator and it will work :\ndef getdefault():\n print \"getdefault called\"\n return cPickle.dumps(set())\n\n_applies_to = models.TextField(db_index=True, default=getdefault)\n\nEdit : From your Update i think the easiest way in this case is to simply do:\nmodels.TextField(db_index=... | [
1
] | [] | [] | [
"django",
"models",
"python"
] | stackoverflow_0004675957_django_models_python.txt |
Q:
Python: add the key to each list item, and then convert to dictionary
lst = [1,2,3,4]
I have hard coded keys ['one','two','three','four','five']
and I want the dictionary like
{'one':1, 'two':2, 'three':3, 'four':4, 'five':None}
Keys are always more than the number of items in list.
A:
import itertools
lst = ... | Python: add the key to each list item, and then convert to dictionary | lst = [1,2,3,4]
I have hard coded keys ['one','two','three','four','five']
and I want the dictionary like
{'one':1, 'two':2, 'three':3, 'four':4, 'five':None}
Keys are always more than the number of items in list.
| [
"import itertools\n\nlst = [1,2,3,4]\nlst2 = ['one','two','three','four','five']\n\nprint dict(itertools.izip_longest(lst2, lst, fillvalue=None))\n# {'five': None, 'four': 4, 'one': 1, 'three': 3, 'two': 2}\n\n",
"Here are a couple of ways to do it\n>>> K=['one','two','three','four','five']\n>>> V=[1,2,3,4]\n>>> ... | [
10,
2,
1
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0004675895_dictionary_list_python.txt |
Q:
most efficient way to go about identifying sub-strings in a string in python?
i need to search a fairly lengthy string for CPV (common procurement vocab) codes.
at the moment i'm doing this with a simple for loop and str.find()
the problem is, if the CPV code has been listed in a slightly different format, this al... | most efficient way to go about identifying sub-strings in a string in python? | i need to search a fairly lengthy string for CPV (common procurement vocab) codes.
at the moment i'm doing this with a simple for loop and str.find()
the problem is, if the CPV code has been listed in a slightly different format, this algorithm won't find it.
what's the most efficient way of searching for all the diffe... | [
"Try a regular expression:\n>>> cpv = re.compile(r'([0-9]+[-\\. ]?[0-9])')\n>>> print cpv.findall('foo 30124120-1 bar 21966823.1 baz')\n['30124120-1', '21966823.1']\n\n(Modify until it matches the CPVs in your data closely.)\n",
"Try using any of the functions in re (regular expressions for Python). See the docs ... | [
4,
1,
1
] | [] | [] | [
"fuzzy_search",
"python",
"string"
] | stackoverflow_0004672868_fuzzy_search_python_string.txt |
Q:
How do I modify this download function in Python?
Right now, it's iffy. Gzip, images, sometimes it doesn't work.
How do I modify this download function so that it can work with anything? (Regardless of gzip or any header?)
How do I automatically "Detect" if it's gzip? I don't want to always pass True/False, like... | How do I modify this download function in Python? | Right now, it's iffy. Gzip, images, sometimes it doesn't work.
How do I modify this download function so that it can work with anything? (Regardless of gzip or any header?)
How do I automatically "Detect" if it's gzip? I don't want to always pass True/False, like I do right now.
def download(source_url, g = False, co... | [
"Check the Content-Encoding header:\nimport urllib2\nimport socket\nimport random\nimport StringIO\nimport gzip\n\ndef download(source_url):\n try:\n socket.setdefaulttimeout(10)\n agents = ['Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)','Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1)','... | [
4,
1,
1
] | [] | [] | [
"http",
"python",
"url",
"urllib"
] | stackoverflow_0004676163_http_python_url_urllib.txt |
Q:
What are the first 32 bits of the fractional part of this float?
I am looking at the following SHA256 pseudocode on wikipedia.
Specifically, I am looking at the following section.
//Initialize variables
//(first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
h0 := 0x6a09e667
I a... | What are the first 32 bits of the fractional part of this float? | I am looking at the following SHA256 pseudocode on wikipedia.
Specifically, I am looking at the following section.
//Initialize variables
//(first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
h0 := 0x6a09e667
I am trying to figure out how h0 was generated. I know from the comment t... | [
"\nUse your calculator on Windows to calculate sqrt(2) (1.4142135623730950488016887242097)\nTake the decimal part (0.4142135623730950488016887242097)\nMultiply by 2^32 (1779033703.9520993849027770600526)\nExpress the whole part in hex (6A09E667)\n\nVoila. (Apologies to OP for not doing a Python answer but I hope t... | [
18,
13,
6
] | [] | [] | [
"bit_manipulation",
"hash",
"python"
] | stackoverflow_0004674956_bit_manipulation_hash_python.txt |
Q:
Add fields to Django ModelForm that aren't in the model
I have a model that looks like:
class MySchedule(models.Model):
start_datetime=models.DateTimeField()
name=models.CharField('Name',max_length=75)
With it comes its ModelForm:
class MyScheduleForm(forms.ModelForm):
startdate=forms.DateField()
starthou... | Add fields to Django ModelForm that aren't in the model | I have a model that looks like:
class MySchedule(models.Model):
start_datetime=models.DateTimeField()
name=models.CharField('Name',max_length=75)
With it comes its ModelForm:
class MyScheduleForm(forms.ModelForm):
startdate=forms.DateField()
starthour=forms.ChoiceField(choices=((6,"6am"),(7,"7am"),(8,"8am"),(9... | [
"\nIf I were you, I would have used the customised Django-admin date/time widget(s) for entering date/time entries.\nRegarding form validation, make sure you pass the form associated with the request for it to show up form-based errors. (Sample code below)\nAs for using inheritance, it would be a overkill for this ... | [
1,
1,
0,
0
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0004665719_django_django_forms_python.txt |
Q:
Is it faster to union sets or check the whole list for a duplicate?
Sorry for the poorly worded title but I asked a question earlier about getting a unique list of items from two lists. People told me to make the list -> sets and then union.
So now I'm wondering if it's faster to:
While adding one item to a list,... | Is it faster to union sets or check the whole list for a duplicate? | Sorry for the poorly worded title but I asked a question earlier about getting a unique list of items from two lists. People told me to make the list -> sets and then union.
So now I'm wondering if it's faster to:
While adding one item to a list, scan the whole list for duplicates.
Make that one item a set and then un... | [
"as you can see extending one list by another end then remove duplicates by making set\nis the fastest way(at least in python;))\n>>> def foo():\n... \"\"\"\n... extending one list by another end then remove duplicates by making set\n... \"\"\"\n... l1 = range(200)\n... l2 = range(150, 250)\n...... | [
22,
12,
1,
1
] | [] | [] | [
"python",
"set"
] | stackoverflow_0004674208_python_set.txt |
Q:
How to rewrite this using 2 FOR loops?
Here is the snippet. How can I re-write this to do away with the first WHILE loop?
start = 1
end = 4
currentcount = 0
while start < end:
file = open('C:\Users\Owner\Desktop\\test' + str(start) + '.txt')
for line in file:
f = o.open('http://www.test.com/?... | How to rewrite this using 2 FOR loops? | Here is the snippet. How can I re-write this to do away with the first WHILE loop?
start = 1
end = 4
currentcount = 0
while start < end:
file = open('C:\Users\Owner\Desktop\\test' + str(start) + '.txt')
for line in file:
f = o.open('http://www.test.com/?userid=' + line.strip())
f.close()
... | [
"Change your while loop to this:\nfor i in range(start, end):\n\nThen use i in the method body. Other points:\n\nUsing start as a counter is potentially confusing. If you change the value of start it is no longer the start.\nUse a raw string for the path:\nr'C:\\Users\\Owner\\Desktop\\test'\nConsider using str.form... | [
2,
1,
0,
0,
0
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0004675128_loops_python.txt |
Q:
Python: Inverse Replace Function
I have no idea about how I explain this, but here goes...
>>> x = 'qwertyHelloWorldasdfg'
>>> x = inversereplace(x, 'HelloWorld', 'a')
>>> print x
aaaaaaHelloWorldaaaaaa
>>> y = 'qwertyHelloWorld'
>>> y = inversereplace(y, 'qwerty', '')
>>> print y
qwerty
In the function abov... | Python: Inverse Replace Function |
I have no idea about how I explain this, but here goes...
>>> x = 'qwertyHelloWorldasdfg'
>>> x = inversereplace(x, 'HelloWorld', 'a')
>>> print x
aaaaaaHelloWorldaaaaaa
>>> y = 'qwertyHelloWorld'
>>> y = inversereplace(y, 'qwerty', '')
>>> print y
qwerty
In the function above, it replaces everything in x that i... | [
"This should work:\ndef inversereplace(text, word, repl):\n parts = text.split(word)\n return word.join(repl*len(x) for x in parts)\n\n",
"def inversereplace(s, p, q):\n s = s.split(p)\n s = map(lambda x: q * len(x), s)\n return p.join(s)\n\n"
] | [
4,
1
] | [] | [] | [
"python",
"replace"
] | stackoverflow_0004676700_python_replace.txt |
Q:
Can this loop be sped up in pure Python?
I was trying out an experiment with Python, trying to find out how many times it could add one to an integer in one minute's time. Assuming two computers are the same except for the speed of the CPUs, this should give an estimate of how fast some CPU operations may take for... | Can this loop be sped up in pure Python? | I was trying out an experiment with Python, trying to find out how many times it could add one to an integer in one minute's time. Assuming two computers are the same except for the speed of the CPUs, this should give an estimate of how fast some CPU operations may take for the computer in question.
The code below is a... | [
"I see almost the same but consistently better (~2%) results than the @Amber's one on my machine on Python 3.1.2 for the code:\nimport signal\n\nclass Alarm(Exception):\n pass\n\ndef alarm_handler(signum, frame):\n raise Alarm\n\ndef jfs_signal(seconds):\n # set signal handler\n signal.signal(signal.SIG... | [
3,
2,
0
] | [] | [] | [
"performance",
"python",
"testing",
"timing"
] | stackoverflow_0004676544_performance_python_testing_timing.txt |
Q:
using django-jython
I have read from the django-jython wiki that 1.1.1 is not compatible with django 1.2, and that jython does not works with the default django backend.
Does this means I'm unable to use django 1.2 with jython at the moment?
A:
I was able to get django 1.2 working just fine in jython 2.5. You... | using django-jython | I have read from the django-jython wiki that 1.1.1 is not compatible with django 1.2, and that jython does not works with the default django backend.
Does this means I'm unable to use django 1.2 with jython at the moment?
| [
"I was able to get django 1.2 working just fine in jython 2.5. You will have to use the SVN build of django-jython. \nI would recommend that you use Java 6 I was able to get it running in Java 5 but I had to rebuild the ruby file system jar and remove the Java 6 database drivers from the packaged war. So you wont e... | [
0
] | [] | [] | [
"django",
"jython",
"python"
] | stackoverflow_0003995088_django_jython_python.txt |
Q:
How do I transfer a Python virtual environment to another user?
Currently, I created a virutal environment in my
/home/myuser/my_virtual_env/
How do I copy this entire thing to another user? (and perhaps rename it to thatuser_virtual_env)
? I have to copy all the python packages, and eveyrthing.
A:
The 'offic... | How do I transfer a Python virtual environment to another user? | Currently, I created a virutal environment in my
/home/myuser/my_virtual_env/
How do I copy this entire thing to another user? (and perhaps rename it to thatuser_virtual_env)
? I have to copy all the python packages, and eveyrthing.
| [
"The 'official' method is to create virtualenv this way: virtualenv --relocatable ENV.\nCheck the 'Making Environments Relocatable' section here: http://pypi.python.org/pypi/virtualenv\nBut I think the way to go is not to copy the environment (that's quite error prone) but to script the environment creation.\nYou c... | [
6
] | [] | [] | [
"linux",
"python",
"unix"
] | stackoverflow_0004677013_linux_python_unix.txt |
Q:
When should you check for errors using "if" , and when should you use exceptions?
When do you use each? I find that I'm using if's a lot more than exceptions. It seems like I'm catching the exceptions using my "ifs", before I even get them. There are ifs all over my code.
A:
EAFP: Easier to ask for forgiveness ... | When should you check for errors using "if" , and when should you use exceptions? | When do you use each? I find that I'm using if's a lot more than exceptions. It seems like I'm catching the exceptions using my "ifs", before I even get them. There are ifs all over my code.
| [
"EAFP: Easier to ask for forgiveness than permission.\nIt is common Python coding style to assume the existence of valid keys or attributes and catch exceptions if the assumption proves false. \nThis contrasts with the LBYL (Look before you leap) style common to many other languages such as C.\nUpdate 1\nOf course,... | [
4,
2,
2,
1
] | [] | [] | [
"conditional",
"error_handling",
"exception",
"python"
] | stackoverflow_0004676957_conditional_error_handling_exception_python.txt |
Q:
python global variable trouble
I am having troubles using global variables in python...
In my program, i have declared 2 global variables,
global SYNC_DATA and
global SYNC_TOTAL_SIZE
Now in one of my functions, I am able to use the global variable SYNC_DATA without declaring it as global again in the function; how... | python global variable trouble | I am having troubles using global variables in python...
In my program, i have declared 2 global variables,
global SYNC_DATA and
global SYNC_TOTAL_SIZE
Now in one of my functions, I am able to use the global variable SYNC_DATA without declaring it as global again in the function; however , I am not able to use the othe... | [
"Assuming SYNC_TOTAL_SIZE is not declared as local variable. It depends on what operations you are performing on global variables, for just reading the global variable there is no need to declare it as global, but if you are modifying the value of global variable you have to declare it with global.\n",
"Because S... | [
6,
0
] | [] | [] | [
"global_variables",
"python"
] | stackoverflow_0004677185_global_variables_python.txt |
Q:
Would porting parts of a PHP application to Python help it scale?
I appreciate there are perhaps better ways of making a PHP application scale than the above, however I'm wondering more on principle. From what I've heard, Python is faster than PHP and I'm trying to decide which language to learn next, as a PHP dev... | Would porting parts of a PHP application to Python help it scale? | I appreciate there are perhaps better ways of making a PHP application scale than the above, however I'm wondering more on principle. From what I've heard, Python is faster than PHP and I'm trying to decide which language to learn next, as a PHP developer.
| [
"Python's a very good language to learn for a number of reasons, including its clear syntax, its excellent standard library, its multi-paradigm support, and the helpful community that surrounds it. \nHowever, scalability has more to do with your system's overall architecture than with the programming language you c... | [
3,
2,
0,
0
] | [] | [] | [
"php",
"python"
] | stackoverflow_0004675504_php_python.txt |
Q:
python and regex
#!/usr/bin/python
import re
str = raw_input("String containing email...\t")
match = re.search(r'[\w.-]+@[\w.-]+', str)
if match:
print match.group()
it's not the most complicated code, and i'm looking for a way to get ALL of the matches, if it's possible.
A:
It sounds like you want re.finda... | python and regex |
#!/usr/bin/python
import re
str = raw_input("String containing email...\t")
match = re.search(r'[\w.-]+@[\w.-]+', str)
if match:
print match.group()
it's not the most complicated code, and i'm looking for a way to get ALL of the matches, if it's possible.
| [
"It sounds like you want re.findall():\nfindall(pattern, string, flags=0)\n Return a list of all non-overlapping matches in the string.\n\n If one or more groups are present in the pattern, return a\n list of groups; this will be a list of tuples if the pattern\n has more than one group.\n\n Empty ma... | [
5,
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004677396_python_regex.txt |
Q:
Login hook on Google Appengine
Every time a user logs in to the application, I want to perform a certain task, say, record the time of login. So I wanted to know if a hook is fired on login by default? If yes, how can I make my module respond to it.
Edit - Assume there are multiple entry points in the application ... | Login hook on Google Appengine | Every time a user logs in to the application, I want to perform a certain task, say, record the time of login. So I wanted to know if a hook is fired on login by default? If yes, how can I make my module respond to it.
Edit - Assume there are multiple entry points in the application to login.
| [
"While there may well be multiple points of entry, it's crucial that your auth/session code conform to the DRY principle.\nOnce/if you're down to a single code path for logging in, you should be able to find an appropriate place in that code path to do something as simple as this:\nuser.last_login = time\nuser.num_... | [
1,
0
] | [] | [] | [
"authentication",
"events",
"google_app_engine",
"hook",
"python"
] | stackoverflow_0004656923_authentication_events_google_app_engine_hook_python.txt |
Q:
In Python, how do I check the size of a StringIO object?
And get the bytes of that StringIO object?
A:
StringIO objects implement the file API, so you can get their size in exactly the same way as you can with a file object: seek to the end and see where it goes.
from StringIO import StringIO
import os
s = Strin... | In Python, how do I check the size of a StringIO object? | And get the bytes of that StringIO object?
| [
"StringIO objects implement the file API, so you can get their size in exactly the same way as you can with a file object: seek to the end and see where it goes.\nfrom StringIO import StringIO\nimport os\ns = StringIO()\ns.write(\"abc\")\npos = s.tell()\ns.seek(0, os.SEEK_END)\nprint s.tell()\ns.seek(pos)\n\nAs Kim... | [
80,
21
] | [] | [] | [
"python"
] | stackoverflow_0004677433_python.txt |
Q:
Chart of mutable versus immutable types
Is there a table or a chart somewhere online which shows what types (inbuilt) are mutable and immutable in python?
A:
I am not sure of a chart, but basically:
Mutable:
list, dictionary, bytearray
Note: bytearray is not a sequence though.
Immutable:
tuple, str
You can chec... | Chart of mutable versus immutable types | Is there a table or a chart somewhere online which shows what types (inbuilt) are mutable and immutable in python?
| [
"I am not sure of a chart, but basically:\nMutable:\nlist, dictionary, bytearray \nNote: bytearray is not a sequence though.\nImmutable:\ntuple, str\nYou can check for mutability with:\n>>> import collections\n>>> l = range(10)\n>>> s = \"Hello World\"\n>>> isinstance(l, collections.MutableSequence)\nTrue\n>>> isin... | [
12
] | [] | [] | [
"immutability",
"mutable",
"python",
"types"
] | stackoverflow_0004677529_immutability_mutable_python_types.txt |
Q:
Suppose I have a StringIO file. How can I use python-magic to check its file type?
import StringIO
import magic
m = magic.Magic()
thefile = StringIO.StringIO(request.raw_post_data) # I got this from Django. ajax file uploader.
what now?
A:
...should be as easy as:
>>> m.from_buffer(thefile.read(1024))
'PDF d... | Suppose I have a StringIO file. How can I use python-magic to check its file type? | import StringIO
import magic
m = magic.Magic()
thefile = StringIO.StringIO(request.raw_post_data) # I got this from Django. ajax file uploader.
what now?
| [
"...should be as easy as:\n >>> m.from_buffer(thefile.read(1024))\n'PDF document, version 1.2'\n\n",
"It looks like you need to use the from_buffer method.\nm.from_buffer(theFile)\n\n"
] | [
2,
1
] | [] | [] | [
"file",
"mime_types",
"python",
"string",
"stringio"
] | stackoverflow_0004677575_file_mime_types_python_string_stringio.txt |
Q:
Regex for multiple lines checking
I'm trying out regex (import re) to extract the info I want from a log file.
UPDATE: Added the C:\WINDOWS\security folder permissions which broke all of the sample codes.
Say the format of the log is:
C:\:
BUILTIN\Administrators Allowed: Full Control
NT AUTHORITY\SYSTE... | Regex for multiple lines checking | I'm trying out regex (import re) to extract the info I want from a log file.
UPDATE: Added the C:\WINDOWS\security folder permissions which broke all of the sample codes.
Say the format of the log is:
C:\:
BUILTIN\Administrators Allowed: Full Control
NT AUTHORITY\SYSTEM Allowed: Full Control
BUILTIN\... | [
"# I would replace this with reading lines from a file,\n# rather than splitting a big string containing the file.\n\nsection = None\ninspecialperm = False\nwith open(\"testdata.txt\") as w:\n for line in w:\n if not line.startswith(\" \"):\n inspecialperm = False\n\n if secti... | [
2,
1,
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004659201_python_regex.txt |
Q:
problem with jinja2 autoescape in google app engine webapp
I decided to install jinja2 to use with my webapp application in order to support the autoescape functionality. So I installed jinja2 into python 2.5 and created a symlink within my project to point to that directory. It's mostly working fine.
EXCEPT, when... | problem with jinja2 autoescape in google app engine webapp | I decided to install jinja2 to use with my webapp application in order to support the autoescape functionality. So I installed jinja2 into python 2.5 and created a symlink within my project to point to that directory. It's mostly working fine.
EXCEPT, when I actually try to use the {% autoescape true %} tag, I get the ... | [
"The {% autoescape %} tag needs Jinja 2.4 or higher and the jinja2.ext.autoescape extension loaded.\nenv = Environment(autoescape=True, extensions=['jinja2.ext.autoescape'],\n loader=...)\n\n"
] | [
8
] | [] | [] | [
"google_app_engine",
"jinja2",
"python"
] | stackoverflow_0004674366_google_app_engine_jinja2_python.txt |
Q:
Multiple inheritance problem in Python!
Why does c.print_a() output 'B'?
class A(object):
def __init__(self):
self.some_name = 'A'
def print_a(self):
print self.some_name
class B(object):
def __init__(self):
self.some_name = 'B'
def print_b(self):
print self.some_... | Multiple inheritance problem in Python! | Why does c.print_a() output 'B'?
class A(object):
def __init__(self):
self.some_name = 'A'
def print_a(self):
print self.some_name
class B(object):
def __init__(self):
self.some_name = 'B'
def print_b(self):
print self.some_name
class C(A, B):
def __init__(self):
... | [
"You only have a single object here; the some_name property is shared between methods from all inherited classes. You call A.__init__, which sets it to A, then B.__init__, which changes it to B.\nAlso note that you're calling base methods incorrectly; use super:\nclass A(object):\n def __init__(self):\n ... | [
5,
1,
1
] | [] | [] | [
"multiple_inheritance",
"python"
] | stackoverflow_0004677755_multiple_inheritance_python.txt |
Q:
How do I use python-magic to get the file type of a file over the Internet?
Usually I would download it to StringIO object, then run this:
m = magic.Magic()
m.from_buffer(thefile.read(1024))
But this time , I can't download the file, because the image might be 20 Megabytes. I want to use Python magic to find the ... | How do I use python-magic to get the file type of a file over the Internet? | Usually I would download it to StringIO object, then run this:
m = magic.Magic()
m.from_buffer(thefile.read(1024))
But this time , I can't download the file, because the image might be 20 Megabytes. I want to use Python magic to find the file type without downloading the entire file.
If python-magic can't do it...is t... | [
"You can call read(1024) without downloading the whole file:\nthefile = urllib2.urlopen(someURL)\n\nThen, just use your existing code. urlopen returns a file-like object, so this works naturally.\n",
"If it is one of the common image formats like png of jpg, and you see the server is a reliable one, then you can... | [
7,
2
] | [] | [] | [
"file",
"http",
"image",
"python",
"string"
] | stackoverflow_0004677883_file_http_image_python_string.txt |
Q:
Correcting the XML encoding
I have a xml with encoding tag set to 'utf-8'. But, it is actually iso-8859-1.
Programatically, how do I detect this in perl and python? and how do I decode with a different coding?
In perl, I tried
$xml = decode('iso-8859-1',$file)
but, this does not work.
A:
Miscoding is notoriou... | Correcting the XML encoding | I have a xml with encoding tag set to 'utf-8'. But, it is actually iso-8859-1.
Programatically, how do I detect this in perl and python? and how do I decode with a different coding?
In perl, I tried
$xml = decode('iso-8859-1',$file)
but, this does not work.
| [
"Miscoding is notoriously tricky to detect, as random binary data often represents valid strings in many many encodings.\nIn Perl, the easiest thing you could try would be to attempt to decode it as utf-8 and check for failures. (it only works this way round; a utf-8 encoded western-language document is almost alw... | [
4,
1,
1
] | [] | [] | [
"encoding",
"perl",
"python",
"xml"
] | stackoverflow_0004674835_encoding_perl_python_xml.txt |
Q:
Problem with char * in python
I've just wrapped a header (.h) file and created .so to use it as a module in python. The function Encrypt takes char* bb, then fill it using memcpy(). If I want to call this function from a c code I have to do (char* bb = (char*) new char[200]; Encrypt (...,...,..., bb);). How to cal... | Problem with char * in python | I've just wrapped a header (.h) file and created .so to use it as a module in python. The function Encrypt takes char* bb, then fill it using memcpy(). If I want to call this function from a c code I have to do (char* bb = (char*) new char[200]; Encrypt (...,...,..., bb);). How to call it from python? How is the equiva... | [
"IMHO you can not call C functions directly from python, but it is easy to write a python module, see http://docs.python.org/extending/extending.html\nEDIT\nctype module allows you to call plain C functions directly.\nCheck this URL for an answer: http://docs.python.org/library/ctypes.html#passing-pointers-or-passi... | [
2,
0
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0004678371_c++_python.txt |
Q:
Is having a unit test that is mostly mock verification a smell?
I have a class that connects three other services, specifically designed to make implementing the other services more modular, but the bulk of my unit test logic is in mock verification. Is there a way to redesign to avoid this?
Python example:
class ... | Is having a unit test that is mostly mock verification a smell? | I have a class that connects three other services, specifically designed to make implementing the other services more modular, but the bulk of my unit test logic is in mock verification. Is there a way to redesign to avoid this?
Python example:
class Input(object): pass
class Output(object): pass
class Finder(object)... | [
"There's no reason to only use unit test - Maybe integration tests would be more useful for this case. Initialize all the objects properly, use the main class a bit, and assert on the (possibly complex) results. That way you'll test interfaces, output predictability, and other things which are important further up ... | [
2,
2,
0
] | [] | [] | [
"language_agnostic",
"python",
"tdd",
"unit_testing"
] | stackoverflow_0004676706_language_agnostic_python_tdd_unit_testing.txt |
Q:
Finding the outer borders from the list of random coordinates
I've a huge list (60 000+) of coordinates and I haven't found a way for recognizing the outer borders.
The list of coordinates are quite random, but they're defining some really specific area.
I should be able to draw an area by using that list by using... | Finding the outer borders from the list of random coordinates | I've a huge list (60 000+) of coordinates and I haven't found a way for recognizing the outer borders.
The list of coordinates are quite random, but they're defining some really specific area.
I should be able to draw an area by using that list by using OpenLayers, so they also should in order.
This seemed to be relati... | [
"Are you looking for a convex hull?\n",
"If you just want the bounding box, it's easy enough:\nmin_x = MAX_INT;\nmin_y = MAX_INT;\nmax_x = MIN_INT;\nmax_y = MIN_INT;\n\nfor p in points:\n if p.x < min_x then min_x = p.x;\n if p.y < min_y then min_y = p.y;\n if p.x > max_x then max_x = p.x;\n if p.y > max_y th... | [
4,
1,
1
] | [] | [] | [
"coordinates",
"geometry",
"math",
"openlayers",
"python"
] | stackoverflow_0004678648_coordinates_geometry_math_openlayers_python.txt |
Q:
how to dynamically create SQLAlchemy columns
I have a csv file with first line as fields and remaining lines as data. With this file I would like to create a table. Since the fields are quite long and may vary, I want to dynamically create it.
After several tries and searches, I figured I could maybe generate a... | how to dynamically create SQLAlchemy columns | I have a csv file with first line as fields and remaining lines as data. With this file I would like to create a table. Since the fields are quite long and may vary, I want to dynamically create it.
After several tries and searches, I figured I could maybe generate a Class from factory and then assign the attributes... | [
"I'm the author of the related answer:\nsqlalchemy dynamic mapping\nI have this answer to another question, which I think is even more related - it could even be a duplicate:\nDatabase on the fly with scripting languages\nAs you can see, to make it you need to create a table object and map it against your class. Al... | [
13
] | [] | [] | [
"dynamic_data",
"python",
"sqlalchemy"
] | stackoverflow_0004678115_dynamic_data_python_sqlalchemy.txt |
Q:
Recommendations for choosing a programming language
Days ago I created a program in Python to download stuff from the Internet, doing HTTP POST and GET and parsing JSON objects. I noticed some slow performance and I was thinking about writing it from scratch using another language, so I started to write it in C++ ... | Recommendations for choosing a programming language | Days ago I created a program in Python to download stuff from the Internet, doing HTTP POST and GET and parsing JSON objects. I noticed some slow performance and I was thinking about writing it from scratch using another language, so I started to write it in C++ to make it faster. Finally I give up, C++ wasn't made for... | [
"Rewriting an IO bound application in a different language is unlikely to make any difference in its execution speed.\n",
"If you need it to be cross-platform: (i.e. you just write it once and it can run anywhere) Then Java or Python are your only options. This is because any C variant will need compiling specifi... | [
7,
2,
2,
0,
0,
0
] | [
"I'd go with the good, old PHP! It has proven time and time again, that it is more than capable of doing this, and is quite easy to learn. \nSo my advice: Go with PHP!\n"
] | [
-1
] | [
"c#",
"c++",
"httpwebrequest",
"java",
"python"
] | stackoverflow_0004678831_c#_c++_httpwebrequest_java_python.txt |
Q:
numpy array mapping and take average
I have three arrays
import numpy as np
value = np.array ([1, 3, 3, 5, 5, 7, 3])
index = np.array ([1, 1, 3, 3, 6, 6, 6])
data = np.array ([1, 2, 3, 4, 5, 6])
Arrays "index" & "value" have same size and I want to group the items in "value" by taking average. For example: For t... | numpy array mapping and take average | I have three arrays
import numpy as np
value = np.array ([1, 3, 3, 5, 5, 7, 3])
index = np.array ([1, 1, 3, 3, 6, 6, 6])
data = np.array ([1, 2, 3, 4, 5, 6])
Arrays "index" & "value" have same size and I want to group the items in "value" by taking average. For example: For the first two items [1, 3, ... in "value", ... | [
">>> [value[index==i].mean() for i in data]\n[2.0, nan, 4.0, nan, nan, 5.0]\n\n",
"Maybe you would like to use numpy.bincount()?\nvalue = np.array([1, 3, 3, 5, 5, 7, 3])\nindex = np.array([1, 1, 3, 3, 6, 6, 6])\nnp.bincount(index, value) / np.bincount(index)\n# array([ NaN, 2., NaN, 4., NaN, NaN, 5.])\n\... | [
3,
3,
0,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0004676029_numpy_python.txt |
Q:
Python / google app engine self request domain
I know that the google app engine come with the self.request for url and the path in the python platform.
What I wanted to know is that did it come with anything to return only the domain name?
This is because sometime in the localhost, mywebapps.appspot.com and www.m... | Python / google app engine self request domain | I know that the google app engine come with the self.request for url and the path in the python platform.
What I wanted to know is that did it come with anything to return only the domain name?
This is because sometime in the localhost, mywebapps.appspot.com and www.mywebapps.com will have different kind of behavior.
O... | [
"Google app engine uses the CGI standard, you can use Host header in request from within the application code and respond accordingly.\nHow to access Host will depend on the web framework e.g webapp and django may differ in details, but as it is CGI you can just access os.environ from anywhere e.g.\nimport os\nlo... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003078537_python.txt |
Q:
Python strings references
Possible Duplicate:
Python '==' vs 'is' comparing strings, 'is' fails sometimes, why?
Hi. I have a question about how Python works when it comes how and when references are used.
I have an example here that I understand.
a = "cat"
b = a
a is b
True
This makes sense. But here comes s... | Python strings references |
Possible Duplicate:
Python '==' vs 'is' comparing strings, 'is' fails sometimes, why?
Hi. I have a question about how Python works when it comes how and when references are used.
I have an example here that I understand.
a = "cat"
b = a
a is b
True
This makes sense. But here comes something I don't understand.
a... | [
"a = \"cat\"\nb = \"cat\"\na is b\n True\nc = 1.2\nd = 1.2\nc is d\n False\n\n\nWhy does a is b return True and not c is d?\n\nWell, the correct question would be \"why does c is d return False and not a is b?\" since the logical expected behavior would be to return False - they are separate objects, created i... | [
7
] | [] | [] | [
"immutability",
"python",
"reference",
"string"
] | stackoverflow_0004679323_immutability_python_reference_string.txt |
Q:
Increasing speed of python code
I have some python code that has many classes. I used cProfile to find that the total time to run the program is 68 seconds. I found that the following function in a class called Buyers takes about 60 seconds of those 68 seconds. I have to run the program about 100 times, so any inc... | Increasing speed of python code | I have some python code that has many classes. I used cProfile to find that the total time to run the program is 68 seconds. I found that the following function in a class called Buyers takes about 60 seconds of those 68 seconds. I have to run the program about 100 times, so any increase in speed will help. Can you sug... | [
"There are many things you can try after optimizing your Python code for speed. If this program doesn't need C extensions, you can run it under PyPy to benefit from its JIT compiler. You can try making a C extension for possibly huge speedups. Shed Skin will even allow you to convert your Python program to a standa... | [
6,
5,
2,
2,
2,
1,
1,
1
] | [] | [] | [
"performance",
"python"
] | stackoverflow_0004653715_performance_python.txt |
Q:
How to find instance of a bound method in Python?
>>> class A(object):
... def some(self):
... pass
...
>>> a=A()
>>> a.some
<bound method A.some of <__main__.A object at 0x7f0d6fb9c090>>
IOW, I need to get access to "a" after being handed over only "a.some".
A:
Starting pyth... | How to find instance of a bound method in Python? | >>> class A(object):
... def some(self):
... pass
...
>>> a=A()
>>> a.some
<bound method A.some of <__main__.A object at 0x7f0d6fb9c090>>
IOW, I need to get access to "a" after being handed over only "a.some".
| [
"Starting python 2.6 you can use special attribute __self__:\n>>> a.some.__self__ is a\nTrue\n\nim_self is phased out in py3k.\nFor details, see the inspect module in the Python Standard Library.\n",
">>> class A(object):\n... def some(self):\n... pass\n...\n>>> a = A()\n>>> a\n<__main__.A object at 0x7fa9b... | [
60,
7,
3,
3
] | [] | [] | [
"class",
"methods",
"python"
] | stackoverflow_0004679592_class_methods_python.txt |
Q:
Splitting 25mb .txt file into smaller files using text delimiter
Regards, SO
I am new to python and Perl. I have been trying to solve a simple problem and getting tied in knots with syntax. I hope someone has the time and patience to help.
I have a 25mb file in ".txt" format which contains news-wire articles goin... | Splitting 25mb .txt file into smaller files using text delimiter | Regards, SO
I am new to python and Perl. I have been trying to solve a simple problem and getting tied in knots with syntax. I hope someone has the time and patience to help.
I have a 25mb file in ".txt" format which contains news-wire articles going back to 1970. Each news story is concatenated to the next, with only... | [
"Something like that:\nfilenumber = 0\noutfile = None\nwith open('source_file.txt') as f:\n for line in f:\n if line.strip() == 'DOCUMENTS':\n filenumber += 1\n outfile = open('result%03d.txt' % filenumber, 'w')\n elif line.strip().startswith('Copyright') and outfile:\n ... | [
1,
1
] | [] | [] | [
"file",
"python",
"string"
] | stackoverflow_0004679668_file_python_string.txt |
Q:
python setup.py bdist_egg Not Setting Up Requirements for Package
I have a Pylons app that I am ready to deploy for the first time to production. It has a simple set of requirements listed in setup.py:
install_requires=[
"Pylons>=1.0",
"Jinja2",
"couchdb",
"python-openid",
],
When I run "python se... | python setup.py bdist_egg Not Setting Up Requirements for Package | I have a Pylons app that I am ready to deploy for the first time to production. It has a simple set of requirements listed in setup.py:
install_requires=[
"Pylons>=1.0",
"Jinja2",
"couchdb",
"python-openid",
],
When I run "python setup.py bdist_egg" it seems to create the egg file properly. When I copy... | [
"After some digging and searching, it seems that something was wrong with the .egg-info directory that was in place, though I don't know what nor how it got that way. Deleting that directory and then regenerating it with the egg_info command fixed things right up.\n",
"In my case, the problem turned out to be wro... | [
2,
0
] | [] | [] | [
"egg",
"pylons",
"python",
"setuptools"
] | stackoverflow_0003553297_egg_pylons_python_setuptools.txt |
Q:
working with dictionary in python
I have this dictionary
goodDay= {'Class':[1,1,0,0,0,1,0,1,0,1], 'grade':[1,0,0,1,0,1,0,1,0,1]}
I want to traverse the values of first key and also of second and put this condition to check:
If value of K2 is 1 how many times is K1 is 1 and K1 is 0
and if K2 is 0 how many times ... | working with dictionary in python | I have this dictionary
goodDay= {'Class':[1,1,0,0,0,1,0,1,0,1], 'grade':[1,0,0,1,0,1,0,1,0,1]}
I want to traverse the values of first key and also of second and put this condition to check:
If value of K2 is 1 how many times is K1 is 1 and K1 is 0
and if K2 is 0 how many times is K1 is 0 and K1 is 1.
| [
"c = [[0,0],[0,0]]\nfor first, second in zip(goodDay['class'], goodDay['grade']):\n c[second][first] += 1\n\n\nYou compare the two lists in the dictionary pairwise, since each of the lists has only two values (0 and 1), this means that together(cartesian product) we can have 4 different options (00, 01, 10, 11). S... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003719987_python.txt |
Q:
How can i invoke gdb using python to run a module
I have a requirement to run a 'C'-module in gdb but this gdb should be involked by python script.
A:
I think the best way to do this is to use subprocess:
subprocess.Popen(['gdb', 'arg1', 'arg2', 'etc'])
If you are using Python 2.x and you only want to record th... | How can i invoke gdb using python to run a module | I have a requirement to run a 'C'-module in gdb but this gdb should be involked by python script.
| [
"I think the best way to do this is to use subprocess:\nsubprocess.Popen(['gdb', 'arg1', 'arg2', 'etc'])\n\nIf you are using Python 2.x and you only want to record the output, you can use commands, but it is deprecated since 2.6.\nYou might want to check Invoke and control GDB from Python\n",
"Hacky solution as a... | [
2,
0
] | [] | [] | [
"gdb",
"python"
] | stackoverflow_0004679889_gdb_python.txt |
Q:
trying to WHOIS a site within IRC
if data.find('!whois') != -1:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("com.whois-servers.net", 43))
s.send('www.msn.com' + "\r\n")
response = ''
while True:
d = s.recv(4096)
respon... | trying to WHOIS a site within IRC | if data.find('!whois') != -1:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("com.whois-servers.net", 43))
s.send('www.msn.com' + "\r\n")
response = ''
while True:
d = s.recv(4096)
response += d
if d == '':
... | [
"This snippet works in python3.1 with the whois site you mentioned.\n#!/usr/bin/env python3\n\nimport socket\n\ndomain = \"msn\"\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((\"com.whois-servers.net\", 43))\ns.send((\"%s\\r\\n\" % domain).encode())\nresponse = \"\"\n\nwhile True:\n r = s.rec... | [
0
] | [] | [] | [
"irc",
"python",
"sockets",
"whois"
] | stackoverflow_0004680709_irc_python_sockets_whois.txt |
Q:
Django workflow engine using signals and Celery-django
I'm working to implement a workflow engine into my project and the main purpose of my attempt is to create a portable app. Something, I would be able to place into any other project in the future and then attach workflows to different models in my projects and... | Django workflow engine using signals and Celery-django | I'm working to implement a workflow engine into my project and the main purpose of my attempt is to create a portable app. Something, I would be able to place into any other project in the future and then attach workflows to different models in my projects and get it to work.
I tried to think of an approach but it doe... | [
"For example you can have a look for zope.wfmc (http://pypi.python.org/pypi/zope.wfmc) : this is an implementation of a Workflow-Management Coalition\nWorkflow that can be defined on XPDL.\n"
] | [
2
] | [] | [] | [
"django",
"python",
"workflow"
] | stackoverflow_0004624247_django_python_workflow.txt |
Q:
Testing authentication UI in selenium
I am using selenium with pylons to test user interactions. Everything was fine until I added testing for an authentication UI -- a login screen with user name and password. It appears that Chrome (the browser I am using under selenium) is popping up a dialog to request whether... | Testing authentication UI in selenium | I am using selenium with pylons to test user interactions. Everything was fine until I added testing for an authentication UI -- a login screen with user name and password. It appears that Chrome (the browser I am using under selenium) is popping up a dialog to request whether to store the credentials. All the tests fa... | [
"Ideally you should use a profile for your tests and in this profile you should specify to never ask for saving the credentials. Unfortunately it is impossible to specify a customized Chrome profile with Selenium 1, but it is possible to do for Firefox in Selenium 1 or move to Selenium 2 (WebDriver) - see this thre... | [
1
] | [] | [] | [
"authentication",
"pylons",
"python",
"selenium"
] | stackoverflow_0004671813_authentication_pylons_python_selenium.txt |
Q:
another switch case with functions
Diving deeper in the interesting python language, so there is no switch in the language as a construct. So using dictionaries is the first place choice by reading learning python first edition. So I tried sth like,
cases = { 2 : readt3(e,t,off, partElems, partsNodes), # to read ... | another switch case with functions | Diving deeper in the interesting python language, so there is no switch in the language as a construct. So using dictionaries is the first place choice by reading learning python first edition. So I tried sth like,
cases = { 2 : readt3(e,t,off, partElems, partsNodes), # to read the triangular elements
3 : r... | [
"when you are doing something like this: \n...\n 2 : readt3(e,t,off, partElems, partsNodes)\n...\n\nactually you are evaluating (calling) the function readt3 with the arguments e,t,off, partElems, partsNodes what i think you want to do is something like this (to emulate switch case statement ) :\ndef readt3( e, t, ... | [
9,
2,
1,
0
] | [] | [] | [
"case",
"function",
"python",
"switch_statement"
] | stackoverflow_0004681556_case_function_python_switch_statement.txt |
Q:
Call Perl script from Python
I've got a Perl script that I want to invoke from a Python script. I've been looking all over, and haven't been successful. I'm basically trying to call the Perl script sending 1 variable to it, but don't need the output of the Perl script, as it is a self contained program.
What I... | Call Perl script from Python | I've got a Perl script that I want to invoke from a Python script. I've been looking all over, and haven't been successful. I'm basically trying to call the Perl script sending 1 variable to it, but don't need the output of the Perl script, as it is a self contained program.
What I've come up with so far is:
var = ... | [
"Just do:\nvar = \"/some/file/path/\"\npipe = subprocess.Popen([\"perl\", \"uireplace.pl\", var])\n\n",
"If you just want to open a pipe to a perl interpreter, you're on the right track. The only thing I think you're missing is that the perl script itself is not an executable. So you need to do this:\nvar = \"/so... | [
17,
16,
3,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0004682088_python.txt |
Q:
OSError's filename attribute unavailable?
I have the following code:
except(OSError) as (errno, strerror, filename):
print "OSError [%d]: %s at %s" % (errno, strerror, filename)
It runs great unless it meets OSError num. 123 (The file name, directory name, or volume label syntax is incorrect). then I get the foll... | OSError's filename attribute unavailable? | I have the following code:
except(OSError) as (errno, strerror, filename):
print "OSError [%d]: %s at %s" % (errno, strerror, filename)
It runs great unless it meets OSError num. 123 (The file name, directory name, or volume label syntax is incorrect). then I get the following error at the except code line:
ValueError... | [
"I have not seen this kind of Exception handling where you are passing the Exception object's attributes to the as clause.\nNormally you handle except ExceptionObject as e and handle the attributes as one would normally handle the attributes of an object.\nOSError contains a errno attribute is a numeric error code ... | [
32
] | [] | [] | [
"errno",
"exception_handling",
"python"
] | stackoverflow_0004681603_errno_exception_handling_python.txt |
Q:
What Python Module Should I Use For Updating?
Alright I've been using the time module for time.sleep(x) function for awhile... but I need something that won't pause the shell and so the user can continue using the program while it's counting.
To be more "specific" let's suppose I had a program that needed to wait... | What Python Module Should I Use For Updating? | Alright I've been using the time module for time.sleep(x) function for awhile... but I need something that won't pause the shell and so the user can continue using the program while it's counting.
To be more "specific" let's suppose I had a program that needed to wait 5 seconds before executing a function. In this tim... | [
"threading ? You should handle piece of your work in one worker and another separate worker where you would count or sleep with time.sleep\nHere is an example that might help you understand and use threading with time.sleep\nimport threading\nimport time\n\ndef sleeper():\n print 'Starting to sleep'\n time.sl... | [
4
] | [] | [] | [
"module",
"python"
] | stackoverflow_0004682478_module_python.txt |
Q:
Vim Regexes to match classes, methods or functions
I am currently developing/updating a VIM plugin that uses a lot of VIM Regexes to match a class/method/function in Python
My starting point was to re-use what I could find, in this case this is what I have been using:
Matches a Class
"^\\s.*class\\s\\+[a-zA-Z0... | Vim Regexes to match classes, methods or functions | I am currently developing/updating a VIM plugin that uses a lot of VIM Regexes to match a class/method/function in Python
My starting point was to re-use what I could find, in this case this is what I have been using:
Matches a Class
"^\\s.*class\\s\\+[a-zA-Z0-9_]\\+"
"\ . "\\s*\\((\\([a-zA-Z0-9_,. \\t\\n]\\)*)... | [
"Something like this might help, i'm not a python nor VIM expert.\n\\v^\\s*def\\s+(\\w+)\\s*\\(\\s*(self[^)]*)\\)\\s*:\n\\v # very magic\n^ # start of line\n \\s* # 0 or more whitespace\n def # 'def'\n \\s+ # 1 or more whitespace\n ( # start capture group 1\n ... | [
4
] | [] | [] | [
"python",
"regex",
"vim"
] | stackoverflow_0004682002_python_regex_vim.txt |
Q:
Define a Custom Form for use in Django's ModelAdmin Add View
I'm trying to expose a Django model in admin using the ModelAdmin class. ModelAdmin seems to assume you use the same form for add and change. I'd like the add_view to use a simplified form that only lists a handful of required fields. After submission, i... | Define a Custom Form for use in Django's ModelAdmin Add View | I'm trying to expose a Django model in admin using the ModelAdmin class. ModelAdmin seems to assume you use the same form for add and change. I'd like the add_view to use a simplified form that only lists a handful of required fields. After submission, it'll redirect to the change_view and use ModelForm's default form ... | [
"get_form() is passed an obj parameter when called during change_view. Simply detect that return the new form/tweak parameters as needed.\nFor example:\n\nclass MyModelAdmin(admin.ModelAdmin):\n def get_form(self, request, obj=None, **kwargs):\n # hide every other field apart from url\n # if we ar... | [
7
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0004682665_django_django_admin_python.txt |
Q:
Command is getting hanged on execution via fabric
When i am running the below command on one of the remote machine via fabric it is getting hanged.
def execute_lmo_scripts():
print "preparing to execute lmo scripts................"
output = run("sudo suwww ; ") # or this command sudo("suwww",shell=Fa... | Command is getting hanged on execution via fabric | When i am running the below command on one of the remote machine via fabric it is getting hanged.
def execute_lmo_scripts():
print "preparing to execute lmo scripts................"
output = run("sudo suwww ; ") # or this command sudo("suwww",shell=False)
If i manually run the command on the remote serve... | [
"Probably that you're using run(\"sudo ..\") and not sudo() and the sudo command is asking for input that isn't being received, so it's waiting, forever.\n"
] | [
2
] | [] | [] | [
"fabric",
"python"
] | stackoverflow_0003100014_fabric_python.txt |
Q:
Django: avoiding multiple evaluations of the same expression in a template?
When passing an object called widget as part of the context to rendering a django template, I may have a method which is a bit expensive, but I want to display the result of it more than once.
Python:
class Widget:
def work(self):
... | Django: avoiding multiple evaluations of the same expression in a template? | When passing an object called widget as part of the context to rendering a django template, I may have a method which is a bit expensive, but I want to display the result of it more than once.
Python:
class Widget:
def work(self):
# Do something expensive
Template
This is a widget, the result of whose work i... | [
"{% with %}\n",
"{% with work_result=widget.work %}\n\nLook Django docs for more information\n"
] | [
4,
3
] | [] | [] | [
"django",
"python",
"templates",
"variables"
] | stackoverflow_0004682754_django_python_templates_variables.txt |
Q:
how to break lines when I concatenate strings in django
hy guys, I needed again of the help of you. Now i want to make a break line when i concatenate strings, i tried to do of this way:
r['placa_desc'] = PessoaFrota(request,dbcur).get_placa_choices(r.get('placa'))
if r.get('placa_desc'):
r['placa'... | how to break lines when I concatenate strings in django | hy guys, I needed again of the help of you. Now i want to make a break line when i concatenate strings, i tried to do of this way:
r['placa_desc'] = PessoaFrota(request,dbcur).get_placa_choices(r.get('placa'))
if r.get('placa_desc'):
r['placa'] = \n + r.get('placa_desc')[0]
but when i try to make thi... | [
"You need to quote your \\n:\nr['placa'] = \\n + r.get('placa_desc')[0]\n\nr['placa'] = \"\\n\" + r.get('placa_desc')[0]\n\nor python thinks the \\ is a continuation character. Try that.\n",
"you missed '', it should be: \n r['placa_desc'] = PessoaFrota(request,dbcur).get_placa_choices(r.get('placa'))\n i... | [
3,
2
] | [] | [] | [
"django",
"line_breaks",
"programming_languages",
"python",
"string_concatenation"
] | stackoverflow_0004683304_django_line_breaks_programming_languages_python_string_concatenation.txt |
Q:
Simplifying for-if messes with better structure?
Please, move this question to Code Review -area. It is better suited there because I know the code below is junk and I want critical feedback to complete rewrite. I am pretty much reinventing the wheel.
# Description: you are given a bitwise pattern and a string
# y... | Simplifying for-if messes with better structure? | Please, move this question to Code Review -area. It is better suited there because I know the code below is junk and I want critical feedback to complete rewrite. I am pretty much reinventing the wheel.
# Description: you are given a bitwise pattern and a string
# you need to find the number of times the pattern matche... | [
"def matchIt(yourString, yourPattern):\n \"\"\"find the number of times yourPattern occurs in yourString\"\"\"\n\nAre you allowed to use the following?\nyourString.count(yourPattern)\n\nIn your case you could create myString as a real string of 10000 characters and the pattern also as a string and then count... | [
2,
1,
0
] | [] | [] | [
"markov_chains",
"python"
] | stackoverflow_0004670873_markov_chains_python.txt |
Q:
Why does a Python script work from the CLI, but not when called from a cron job?
I have created a Python script that I want to run daily via a cronjob on an Ubuntu server.
This is how this script would be run from the Command Line:
python /home/username/public_html/IDM_app/manage.py cleanUpPosts
When called fr... | Why does a Python script work from the CLI, but not when called from a cron job? | I have created a Python script that I want to run daily via a cronjob on an Ubuntu server.
This is how this script would be run from the Command Line:
python /home/username/public_html/IDM_app/manage.py cleanUpPosts
When called from the CLI, the script works fine.
However, when I attempt to run the script via cronj... | [
"The crontab probably cannot find the python executable although it can on the CLI, so you need to write down the complete path to python. The same you get from \nwhich python\n\nCrontab supplies an environment for the scripts, which is not the same as the normal user environment.\n",
"3 17 * * * /bin/sh python /... | [
5,
2
] | [] | [] | [
"cron",
"django",
"environment_variables",
"python"
] | stackoverflow_0004683437_cron_django_environment_variables_python.txt |
Q:
Python code translation to JVM
Is there such a thing as a "translator" (for lack of a better word in my mind now) that translates Python code directly to JVM / Dalvik bytecode?
Would be great for writing Android applications in Python!
NOTE: I know about the scripting capabilities of the Android platform but I am ... | Python code translation to JVM | Is there such a thing as a "translator" (for lack of a better word in my mind now) that translates Python code directly to JVM / Dalvik bytecode?
Would be great for writing Android applications in Python!
NOTE: I know about the scripting capabilities of the Android platform but I am looking for something that would gen... | [
"Yes you can go to Java bytecode using jythonc. Though I'm not sure how well that would work with the Dalvik format's subtle differences.\nedit: apparently there was a jythonroid project which aims to do exactly what you want, but they abandoned it in favor of SL4A\n",
"try jython - python implementatjon for the... | [
6,
3,
3,
2
] | [] | [] | [
"android",
"dalvik",
"java",
"jvm",
"python"
] | stackoverflow_0004683777_android_dalvik_java_jvm_python.txt |
Q:
webpy: how to override content of basic template?
I'm using webpy with a basic template
render = web.template.render(basedir + 'templates/', base='layout', globals=globals_vars_custom)
in layout.html I have something like:
$def with (content)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://w... | webpy: how to override content of basic template? | I'm using webpy with a basic template
render = web.template.render(basedir + 'templates/', base='layout', globals=globals_vars_custom)
in layout.html I have something like:
$def with (content)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
... | [
"It was easier than I tought:\nYou can create a variable in a template:\nin page.html you can define a variable\n$var title = 'specific title'\n\nin the base template layout.html you can call the varable:\n$def with (content)\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/RE... | [
5
] | [] | [] | [
"overriding",
"python",
"templates",
"web.py"
] | stackoverflow_0004596298_overriding_python_templates_web.py.txt |
Q:
Wordpress & Django -- One domain, two servers. Possible?
My question is about hosting Django and Wordpress under one domain, but two physical machines (actually, they are VMs but same diff).
Let's say I have a Django webapp at example.com. I'd like to start a Wordpress blog about my webapp, so any blog page rank ... | Wordpress & Django -- One domain, two servers. Possible? | My question is about hosting Django and Wordpress under one domain, but two physical machines (actually, they are VMs but same diff).
Let's say I have a Django webapp at example.com. I'd like to start a Wordpress blog about my webapp, so any blog page rank mojo flows back to my webapp, I'd like the blog address t be e... | [
"You can do this with haproxy -- a robust software load balancer:\nglobal\n user haproxy\n group haproxy\n# chroot /usr/share/haproxy\n pidfile /var/run/haproxy.pid\n daemon\n log 127.0.0.1 local0 info\n\ndefaults\n log global\n mode http\n option httplog\n option dontlognull\n option redispatch\n optio... | [
5
] | [] | [] | [
"apache",
"django",
"python"
] | stackoverflow_0004683286_apache_django_python.txt |
Q:
Django complex queries
I need to craft a filter for an object that checks date ranges. Right now I'm performing a very inefficient loop which checks all the objects. I would like to simplify this to a database call.
The logic is you have a start and an end date objects. I need to check if the start OR the end is w... | Django complex queries | I need to craft a filter for an object that checks date ranges. Right now I'm performing a very inefficient loop which checks all the objects. I would like to simplify this to a database call.
The logic is you have a start and an end date objects. I need to check if the start OR the end is within the range of an appoin... | [
"You need Q objects for & and OR operators and the range field lookup type\nQ Object: http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects\nrange: http://docs.djangoproject.com/en/dev/ref/models/querysets/#range\nEntry.objects.filter(Q(start__range=(appointment.start, appointment.e... | [
4
] | [] | [] | [
"date",
"django",
"model",
"python",
"sql"
] | stackoverflow_0004683883_date_django_model_python_sql.txt |
Q:
module compiled with swig not found by python
I've a problem with SWIG and python. I've a c-class that compiles correctly, but the python script says it can't find the module.
I compile with:
swig -c++ -python codes/codes.i
g++ -c -Wall -O4 -fPIC -pedantic codes/*.cc
g++ -I/usr/include/python2.6 -shared codes/code... | module compiled with swig not found by python | I've a problem with SWIG and python. I've a c-class that compiles correctly, but the python script says it can't find the module.
I compile with:
swig -c++ -python codes/codes.i
g++ -c -Wall -O4 -fPIC -pedantic codes/*.cc
g++ -I/usr/include/python2.6 -shared codes/codes_wrap.cxx *.o -o _codes.so
This gives me a _codes... | [
"Rename your _codes.so to _codes.pyd if its a release build. Rename to _codes_d.pyd for debug builds.\nHTH\n",
"Last time I used SWIG, it generated two files. In your case it should be codes.py and _codes.so\nYou should check why codes.py is not present.\n",
"if you are executing these commands from the same pl... | [
1,
0,
0
] | [] | [] | [
"c++",
"module",
"python",
"swig"
] | stackoverflow_0002751434_c++_module_python_swig.txt |
Q:
Call a program written in python in a program written in Ocaml
I wanted to ask if you could call in a program written in Ocaml a program written in python , and if the answer is yes how do I do?
A:
What exactly are you intending to do? Do you want to run it and forget about it? Then do a fork/exec. Do you wan... | Call a program written in python in a program written in Ocaml | I wanted to ask if you could call in a program written in Ocaml a program written in python , and if the answer is yes how do I do?
| [
"What exactly are you intending to do? Do you want to run it and forget about it? Then do a fork/exec. Do you want run it and wait until it's finished but otherwise do nothing? Then use Sys.command. Do you want to read/write to it? Then uses Unix.open_process* (or Unix.create_process*).\nFor example, if I wan... | [
5,
2,
2,
2,
1
] | [
"It depends on your exact requirements, but you can use pythons os.system() to execute an program in the same way you would call it from the command line. That should be a good starting point.\n"
] | [
-1
] | [
"ocaml",
"python"
] | stackoverflow_0004683639_ocaml_python.txt |
Q:
Reducing Django Memory Usage. Low hanging fruit?
My memory usage increases over time and restarting Django is not kind to users.
I am unsure how to go about profiling the memory usage but some tips on how to start measuring would be useful.
I have a feeling that there are some simple steps that could produce big g... | Reducing Django Memory Usage. Low hanging fruit? | My memory usage increases over time and restarting Django is not kind to users.
I am unsure how to go about profiling the memory usage but some tips on how to start measuring would be useful.
I have a feeling that there are some simple steps that could produce big gains. Ensuring 'debug' is set to 'False' is an obvious... | [
"Make sure you are not keeping global references to data. That prevents the python garbage collector from releasing the memory.\nDon't use mod_python. It loads an interpreter inside apache. If you need to use apache, use mod_wsgi instead. It is not tricky to switch. It is very easy. mod_wsgi is way easier to config... | [
51,
28,
15,
5,
4,
4,
3,
3,
1,
1
] | [] | [] | [
"django",
"memory_management",
"mod_python",
"profiling",
"python"
] | stackoverflow_0000487224_django_memory_management_mod_python_profiling_python.txt |
Q:
The use of getters and setters for different programming languages
So I know there are a lot of questions on getters and setters in general, but I couldn't find something exactly like my question. I was wondering if people change the use of get/set depending on different languages. I started learning with C++ an... | The use of getters and setters for different programming languages | So I know there are a lot of questions on getters and setters in general, but I couldn't find something exactly like my question. I was wondering if people change the use of get/set depending on different languages. I started learning with C++ and was taught to use getters and setters. This is what I understand:
In ... | [
"Actually, getters and setters (as well as public properties hiding these) are very little improvement over public variables, and a pretty good indicator for quasi classes. \n",
"It's OK to have all public variables in any language. Yes, I know it's the opposite of what you learned.\nOO theory says that there sho... | [
6,
3,
2,
2,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"c++",
"getter",
"matlab",
"python",
"setter"
] | stackoverflow_0004683937_c++_getter_matlab_python_setter.txt |
Q:
Order of command line arguments in a Python script
Let's say I have the following script.
This script finds the largest file under /home and emails the output with the 10 largest files.
./myscript.py -d /home -e joe@email.com -p 10
Let's say I don't want it to email me, I remove "-e joe@email.com" The script fai... | Order of command line arguments in a Python script | Let's say I have the following script.
This script finds the largest file under /home and emails the output with the 10 largest files.
./myscript.py -d /home -e joe@email.com -p 10
Let's say I don't want it to email me, I remove "-e joe@email.com" The script fails because it's expecting "-e" to be present. I'm assig... | [
"Use argparse or optparse modules to parse your arguments, instead of parsing them yourself. It allows for optional arguments and you can specify a default value.\nHere's a quick example using optparse:\nimport optparse\n\nparser = optparse.OptionParser()\n\nparser.add_option(\"-d\", \"--directory\", metavar=\"DIR\... | [
4,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0004684621_python.txt |
Q:
Is there a way to disable urlencoding of anchor attributes in lxml
I am using lxml 2.2.8 and trying to transform some existing html files into django templates.
the only problem that i am having is that lxml urlencodes the anchor name and href attributes.
for example:
<xsl:template match="a">
<!-- anchor attribute... | Is there a way to disable urlencoding of anchor attributes in lxml | I am using lxml 2.2.8 and trying to transform some existing html files into django templates.
the only problem that i am having is that lxml urlencodes the anchor name and href attributes.
for example:
<xsl:template match="a">
<!-- anchor attribute href is urlencoded but the title is escaped -->
<a href="{{{{item.get_a... | [
"Maybe you can use the XML instead of the HTML serializer.\n>>> from lxml import etree, html\n>>> \n>>> t = etree.XML('<a href=\"{{x}}\" />')\n>>> \n>>> etree.tostring(t)\n'<a href=\"{{x}}\"/>'\n>>> html.tostring(t)\n'<a href=\"%7B%7Bx%7D%7D\"></a>'\n\n",
"It looks like that should be the proper output for html s... | [
4,
3
] | [] | [] | [
"lxml",
"python",
"urlencode",
"xslt"
] | stackoverflow_0004684614_lxml_python_urlencode_xslt.txt |
Q:
Check if Rhythmbox is running via Python
I am trying to extract information from Rhythmbox via dbus, but I only want to do so, if Rhythmbox is running. Is there a way to check if Rhythmbox is running via Python without starting it if it is not running?
Whenever I invoke the dbus code like this:
bus = dbus.Bus()
ob... | Check if Rhythmbox is running via Python | I am trying to extract information from Rhythmbox via dbus, but I only want to do so, if Rhythmbox is running. Is there a way to check if Rhythmbox is running via Python without starting it if it is not running?
Whenever I invoke the dbus code like this:
bus = dbus.Bus()
obj = bus.get_object("org.gnome.Rhythmbox", "/or... | [
"This is similar to Rosh Oxymoron's answer, but arguably neater (albeit untested):\nbus = dbus.SessionBus()\nif bus.name_has_owner('org.gnome.Rhythmbox'):\n # ...\n\nIf you want to be notified when Rhythmbox starts or stops, you can use:\ndef rhythmbox_owner_changed(new_owner):\n if new_owner == '':\n ... | [
5,
1
] | [] | [] | [
"dbus",
"python",
"rhythmbox"
] | stackoverflow_0004635462_dbus_python_rhythmbox.txt |
Q:
File/module structure in Python
So I'm just getting started with Python, and currently working my way through http://diveintopython3.ep.io/. The code examples are nice, but the vast majority of them are little four-line snippets, and I want to see a little more of the big picture.
As I understand it--and correct ... | File/module structure in Python | So I'm just getting started with Python, and currently working my way through http://diveintopython3.ep.io/. The code examples are nice, but the vast majority of them are little four-line snippets, and I want to see a little more of the big picture.
As I understand it--and correct me if I'm wrong--each '.py' file beco... | [
"\nWhat is it if I don't have a\n __init__.py file?\n\nIt's just a folder.\n\nDo I generally define only one class\n in the file?\n\nIt depends. Not necessarily.\n\nDoes anything else go in that file\n besides the class definition and maybe\n a handful of import commands?\n\nYou can put anything you want. Anyth... | [
5,
1,
0
] | [] | [] | [
"module",
"package",
"python"
] | stackoverflow_0004683955_module_package_python.txt |
Q:
The best way to search string in BeatifulSoup.findAll('a')
Guys please help me with next problem.
I need to find links with some key (string) and I used next code:
import urllib2, re
from BeautifulSoup import BeautifulSoup
url = 'http://5pd.ru'
page = urllib2.urlopen(url)
soup = BeautifulSoup(page)
print soup.f... | The best way to search string in BeatifulSoup.findAll('a') | Guys please help me with next problem.
I need to find links with some key (string) and I used next code:
import urllib2, re
from BeautifulSoup import BeautifulSoup
url = 'http://5pd.ru'
page = urllib2.urlopen(url)
soup = BeautifulSoup(page)
print soup.findAll('a')
for link in soup.findAll('a'):
if '5' in link:
... | [
"link is not string. use link['href'] instead of link inside for loop or force conversion to string with str(link)\n",
"findAll() with regular expression:\nfor link in soup.findAll('a', href=re.compile('5')):\n print link['href']\n\n"
] | [
2,
2
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0004684922_beautifulsoup_python.txt |
Q:
Generic reverse of list items in Python
>>> b=[('spam',0), ('eggs',1)]
>>> [reversed(x) for x in b]
[<reversed object at 0x7fbf07de7090>, <reversed object at 0x7fbf07de70d0>]
Bummer. I expected to get a list of reversed tuples!
Sure I can do:
>>> [tuple(reversed(x)) for x in b]
[(0, 'spam'), (1, 'eggs')]
But I h... | Generic reverse of list items in Python | >>> b=[('spam',0), ('eggs',1)]
>>> [reversed(x) for x in b]
[<reversed object at 0x7fbf07de7090>, <reversed object at 0x7fbf07de70d0>]
Bummer. I expected to get a list of reversed tuples!
Sure I can do:
>>> [tuple(reversed(x)) for x in b]
[(0, 'spam'), (1, 'eggs')]
But I hoped for something generic? Smth that when be... | [
"Extended slicing.\n[x[::-1] for x in b]\n\n",
"If you only need depth of one, try [x[::-1] for x in mylist]. Otherwise just make a recursive function like\nimport collections\ndef recursive_reversed(seq):\n if isinstance(seq, collections.Sequence):\n return [recursive_reversed(x) for x in reversed(seq)... | [
8,
0
] | [] | [] | [
"python",
"sequences"
] | stackoverflow_0004685571_python_sequences.txt |
Q:
Several threads connecting to a Postfix server?
I'm writing a program which is sending files through SMTP, thanks to my (local) Postfix server, on port 25.
Is it possible to use several threads (thus several sockets) to inject emails faster ?
A:
Depends entirely on where the bottleneck is. If it's on the SMTP s... | Several threads connecting to a Postfix server? | I'm writing a program which is sending files through SMTP, thanks to my (local) Postfix server, on port 25.
Is it possible to use several threads (thus several sockets) to inject emails faster ?
| [
"Depends entirely on where the bottleneck is. If it's on the SMTP server or the network, the answer is no. If it's in your python code, probably yes.\n"
] | [
0
] | [] | [] | [
"python",
"smtp",
"smtplib",
"sockets"
] | stackoverflow_0004685634_python_smtp_smtplib_sockets.txt |
Q:
How to implement live updates on page using AJAX?
I'm using Google App Engine, Python and JQuery. My application is similar to Twitter in that it allows users to publish messages/status updates. I want the home page to display live updates (just like Twitter's homepage) so that if a new message is posted, it app... | How to implement live updates on page using AJAX? | I'm using Google App Engine, Python and JQuery. My application is similar to Twitter in that it allows users to publish messages/status updates. I want the home page to display live updates (just like Twitter's homepage) so that if a new message is posted, it appears top on the list of my home page.
I'm looking for a... | [
"Have you seen the new channel api on GAE? it will basically abstract away the polling - allowing you to push bi-directionally. Oh, and i've linked to the code sample (in Python + JS).\nHope this helps\n",
"On Google App Engine, you probably want to use the new Channel API. It allows you to declare a channel on ... | [
4,
1,
0
] | [] | [] | [
"ajax",
"google_app_engine",
"jquery",
"python"
] | stackoverflow_0004685708_ajax_google_app_engine_jquery_python.txt |
Q:
Importing file with unknown encoding from Python into MongoDB
Working on importing a tab-delimited file over HTTP in Python.
Before inserting a row's data into MongoDB, I'm removing slashes, ticks and quotes from the string.
Whatever the encoding of the data is, MongoDB is throwing me the exception:
bson.errors.In... | Importing file with unknown encoding from Python into MongoDB | Working on importing a tab-delimited file over HTTP in Python.
Before inserting a row's data into MongoDB, I'm removing slashes, ticks and quotes from the string.
Whatever the encoding of the data is, MongoDB is throwing me the exception:
bson.errors.InvalidStringData: strings in documents must be valid UTF-8
So in an... | [
"Try these in order:\n(0) Check that your removal of the slashes/ticks/etc is not butchering the data. What's a tick? Please show your code. Please show a sample of the raw data ... use print repr(sample_raw data) and copy/paste the output into an edit of your question.\n(1) There's an old maxim: \"If the encoding ... | [
7
] | [] | [] | [
"character_encoding",
"mongodb",
"python"
] | stackoverflow_0004685568_character_encoding_mongodb_python.txt |
Q:
Equivalent of a python generator in C++ for buffered reads
Guido Van Rossum demonstrates the simplicity of Python in this article and makes use of this function for buffered reads of a file of unknown length:
def intsfromfile(f):
while True:
a = array.array('i')
a.fromstring(f.read(4000))
... | Equivalent of a python generator in C++ for buffered reads | Guido Van Rossum demonstrates the simplicity of Python in this article and makes use of this function for buffered reads of a file of unknown length:
def intsfromfile(f):
while True:
a = array.array('i')
a.fromstring(f.read(4000))
if not a:
break
for x in a:
y... | [
"In order to disguise an ifstream (or really, any input stream) in a form that acts like an iterator, you want to use the istream_iterator or the istreambuf_iterator template class. The former is useful for files where the formatting is of concern. For example, a file full of whitespace-delimited integers can be re... | [
7
] | [] | [] | [
"algorithm",
"c++",
"file",
"io",
"python"
] | stackoverflow_0004685862_algorithm_c++_file_io_python.txt |
Q:
reverse a regexp substitution
Given a string transformation expressed as a regexp substitution, is there a convenient way to reverse that transformation, preferably in python?
For example, given the transformation
def f(x): return re.sub('foo((:?bar)?)', r'\1', x)
which transforms 'foobar' to 'bar' and 'foo' to t... | reverse a regexp substitution | Given a string transformation expressed as a regexp substitution, is there a convenient way to reverse that transformation, preferably in python?
For example, given the transformation
def f(x): return re.sub('foo((:?bar)?)', r'\1', x)
which transforms 'foobar' to 'bar' and 'foo' to the empty string, I would like to ob... | [
"Your example doesn't work; ('(bar)?', 'foo$1') is not the reverse of ('foo(bar)?', '$1').\nIf you try it (dropping the group substitution for the moment): \nimport re\nre.sub(r'(bar)?', 'foo', 'xyz')\n\nyou get fooxfooyfoozfoo.\nThat's because (bar)? matches the null string, and the null string exists at every pos... | [
2,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004685485_python_regex.txt |
Q:
How to prepare and aftercare data for AWS MapReduce
I am working with Amazons MapReduce Web Service for an university project. In order to use the data for MapReduce, I need to dump them from a relational database (AWS RDS) into S3. After MapReduce finishes I need to split the output file and load chunks of it int... | How to prepare and aftercare data for AWS MapReduce | I am working with Amazons MapReduce Web Service for an university project. In order to use the data for MapReduce, I need to dump them from a relational database (AWS RDS) into S3. After MapReduce finishes I need to split the output file and load chunks of it into their own S3 buckets.
What is a good way to do this wit... | [
"If you take a look at the Amazon Elastic MapReduce Developer Guide you need to specify the location of input data, output data, mapper script and reducer script in S3 in order to create a MapReduce job flow.\nIf you need to do some pre-processing (such as dumping the MapReduce input file from a database) or post-p... | [
2
] | [] | [] | [
"amazon_rds",
"amazon_s3",
"amazon_web_services",
"mapreduce",
"python"
] | stackoverflow_0004669947_amazon_rds_amazon_s3_amazon_web_services_mapreduce_python.txt |
Q:
Python: Why can't I use `super` on a class?
Why can't I use super to get a method of a class's superclass?
Example:
Python 3.1.3
>>> class A(object):
... def my_method(self): pass
>>> class B(A):
... def my_method(self): pass
>>> super(B).my_method
Traceback (most recent call last):
File "<pyshell#2>", l... | Python: Why can't I use `super` on a class? | Why can't I use super to get a method of a class's superclass?
Example:
Python 3.1.3
>>> class A(object):
... def my_method(self): pass
>>> class B(A):
... def my_method(self): pass
>>> super(B).my_method
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
super(B).my_method
Attribu... | [
"It looks as though you need an instance of B to pass in as the second argument.\nhttp://www.artima.com/weblogs/viewpost.jsp?thread=236275\n",
"According to this it seems like I just need to call super(B, B).my_method:\n>>> super(B, B).my_method\n<function my_method at 0x00D51738>\n>>> super(B, B).my_method is A.... | [
8,
6
] | [] | [] | [
"class",
"python",
"python_3.x",
"super"
] | stackoverflow_0004686241_class_python_python_3.x_super.txt |
Q:
Two ways to make python based webpages?
I wanted to try out python to create webpages instead of using php. However I came across that you need either mod_python or mod_wsgi installed to apache to make it play with python. If you now use pure, i'm not sure if it should be said pure, python code, not using any web ... | Two ways to make python based webpages? | I wanted to try out python to create webpages instead of using php. However I came across that you need either mod_python or mod_wsgi installed to apache to make it play with python. If you now use pure, i'm not sure if it should be said pure, python code, not using any web frameworks like django. I found out that maki... | [
"Yes, making a webpage with python without using a web framework is harder than it is in php. This is by design, since it gives you a great deal more control over how your page interacts with the server, allowing you to build sites that scale well, among other benefits. WSGI is the modern way to interact with a ser... | [
3,
1,
1,
0,
0
] | [] | [] | [
"php",
"python"
] | stackoverflow_0004685880_php_python.txt |
Q:
Clear all data from Django?
I have a Django project that uses postgresql_psycopg2 as a database. I would like to clear all data. Is there a simple way to do this?
A:
django-admin.py flush
| Clear all data from Django? | I have a Django project that uses postgresql_psycopg2 as a database. I would like to clear all data. Is there a simple way to do this?
| [
"django-admin.py flush\n"
] | [
3
] | [] | [] | [
"database",
"django",
"python"
] | stackoverflow_0004686736_database_django_python.txt |
Q:
save an image with selenium & firefox
i'm trying to save an image from a website using selenium server & python client.
i know the image's URL, but i can't find the code to save it, either when it's the the document itself, or when it's embedded in the current browser session.
the workaround i found so far is to ... | save an image with selenium & firefox | i'm trying to save an image from a website using selenium server & python client.
i know the image's URL, but i can't find the code to save it, either when it's the the document itself, or when it's embedded in the current browser session.
the workaround i found so far is to save the page's screenshot (there are 2 sel... | [
"I found code that puts an image in to a canvas, then converts it to data - which could then be base64 encoded for example. My thought was to call this using the eval command in selenium, however in my testing the toDataURL is throwing a security error 1000. Seems like it is so close to a solution if not for tha... | [
5,
3,
2,
0
] | [
"How about going to the image URL and then taking a screenshot of the page? Firefox displays the image in full screen. Hope this helps..\n"
] | [
-1
] | [
"python",
"selenium"
] | stackoverflow_0000816704_python_selenium.txt |
Q:
Convert to a urllib.request to an integer
Am I able to convert the value us_price into an integer after the following:
import urllib.request
page = urllib.request.urlopen ("http://au.finance.yahoo.com/q?s=AUDUSD=X")
text = page.read().decode("utf8")
where1 = text.find('yfs_l10_audusd=x">')
start_of_us_price = w... | Convert to a urllib.request to an integer | Am I able to convert the value us_price into an integer after the following:
import urllib.request
page = urllib.request.urlopen ("http://au.finance.yahoo.com/q?s=AUDUSD=X")
text = page.read().decode("utf8")
where1 = text.find('yfs_l10_audusd=x">')
start_of_us_price = where1 + 18
end_of_us_price = start_of_us_price ... | [
"You probably should use float(us_price), but if you want int then int(float(us_price)).\n"
] | [
1
] | [] | [] | [
"int",
"python",
"urllib"
] | stackoverflow_0004686715_int_python_urllib.txt |
Q:
python NameError: name '' is not defined (but it is!)
Note: Solved. It turned out that I was importing a previous version of the same module.
It is easy to find similar topics on StackOverflow, where someone ran into a NameError. But most of the questions deal with specific modules and the solution is often to upd... | python NameError: name '' is not defined (but it is!) | Note: Solved. It turned out that I was importing a previous version of the same module.
It is easy to find similar topics on StackOverflow, where someone ran into a NameError. But most of the questions deal with specific modules and the solution is often to update the module.
In my case, I am trying to import a functio... | [
"This could happen if the module has __all__ defined\nAlternatively there could be another version of the module in your path that is getting imported instead of the one you are expecting\nIs the NameError about listToText or is it something inside the function causing the exception?\n",
"In addition the __all__ ... | [
4,
3
] | [] | [] | [
"nameerror",
"python"
] | stackoverflow_0004686525_nameerror_python.txt |
Q:
SqlAlchemy and Multiprocessing
I use SqlAlchemy to connect to my database backend and make heavy use of multiprocessing in my Python application. I came to a situation which requires to pass an object reference, which is the result of a database query, from one process to another.
This is a problem, because when a... | SqlAlchemy and Multiprocessing | I use SqlAlchemy to connect to my database backend and make heavy use of multiprocessing in my Python application. I came to a situation which requires to pass an object reference, which is the result of a database query, from one process to another.
This is a problem, because when accessing an attribute of the object,... | [
"This is a bad idea (tm). \nYou shouldn't share a stateful object between processes like this (I know it's tempting) because all kinds of bad things can happen since lock primitives are not intended to work across multiple python runtimes. \nI suggest taking the attributes you need out of that object, jamming them ... | [
15
] | [] | [] | [
"multiprocessing",
"orm",
"python",
"sqlalchemy"
] | stackoverflow_0004680332_multiprocessing_orm_python_sqlalchemy.txt |
Q:
Where can I find the Python bindings for GIO's GSocket?
Where are the Python bindings, or what is the current status of the Python bindings for GIO's GSocket and other lowlevel network support?
A:
The Gnome documentation is known to be somewhat not up to date. One may endlessly say words like community, manpower... | Where can I find the Python bindings for GIO's GSocket? | Where are the Python bindings, or what is the current status of the Python bindings for GIO's GSocket and other lowlevel network support?
| [
"The Gnome documentation is known to be somewhat not up to date. One may endlessly say words like community, manpower, time, effort, et cetera.\nThe fact is that when you do\n>>> import gio\n>>> help(gio.Socket)\n\nyou will see that the class is there (and others too). That is just the doc missing its description.\... | [
2,
1
] | [] | [] | [
"binding",
"c",
"gio",
"python",
"sockets"
] | stackoverflow_0004677807_binding_c_gio_python_sockets.txt |
Q:
How to STDIN and STDOUT with PHP and Python to use html2text and get a markdown formated text?
I am sending an HTML text from PHP to Python via STDIN. My objctive is to use Aaron Swartz's script "html2text.py" and to print the result to PHP via STDOUT.
Camarade Jan gave me the word and put me in the right directi... | How to STDIN and STDOUT with PHP and Python to use html2text and get a markdown formated text? | I am sending an HTML text from PHP to Python via STDIN. My objctive is to use Aaron Swartz's script "html2text.py" and to print the result to PHP via STDOUT.
Camarade Jan gave me the word and put me in the right direction. Here's my test:
PHP code:
$t='<p><b>Hello</b><i>world!</i></p>';
$scaped=preg_quote($t,"/")."\n"... | [
"You're just passing the last line to html2text , and you are not using html2text correctly do this instead :\nimport html2text\nimport sys\n\nprint html2text.html2text(sys.stdin.read())\n\n"
] | [
2
] | [] | [] | [
"html",
"markdown",
"php",
"python",
"text_files"
] | stackoverflow_0004686842_html_markdown_php_python_text_files.txt |
Q:
Python process fail after ctypes CreateProcessWithLogonW execution
I'm trying to execute a python script (through a python process) under another user. I found part of this code on the web and works pretty well; except one thing.
When the process terminate, python fails.
So to be clear, the second python process ... | Python process fail after ctypes CreateProcessWithLogonW execution | I'm trying to execute a python script (through a python process) under another user. I found part of this code on the web and works pretty well; except one thing.
When the process terminate, python fails.
So to be clear, the second python process under the different user execute well with CreateProcessWithLogonW, but ... | [
"Check your arguments for lpApplicationName and lpCommandLine; one way to fix it is to pass NULL for the former and the complete command line for the latter:\np = CreateProcessWithLogonW('user',\n 'domain',\n 'password',\n 0,\n ... | [
0,
0
] | [] | [] | [
"ctypes",
"python",
"windows"
] | stackoverflow_0004686846_ctypes_python_windows.txt |
Q:
Load python module not from a file
I've got some python code in a library that attempts to load a simple value from a module that will exist for the applications that use this library
from somemodule import simplevalue
Normally, the application that uses the library will have the module file and everything works ... | Load python module not from a file | I've got some python code in a library that attempts to load a simple value from a module that will exist for the applications that use this library
from somemodule import simplevalue
Normally, the application that uses the library will have the module file and everything works fine. However, in the unit tests for thi... | [
"It is. Use types.ModuleType to create a new module object, then add it to sys.modules:\nsys.modules[\"somename\"] = types.ModuleType(\"somename\")\n\nYou can then do import somename. If you need to add classes or functions to it, import it before calling your test script, and just add functions to it:\ndef myfunc(... | [
7,
5,
1
] | [] | [] | [
"import",
"module",
"python",
"unit_testing"
] | stackoverflow_0004686893_import_module_python_unit_testing.txt |
Q:
Establish SSH Connection Between Two Isolated Machines Using a 3rd System
I'd like to do the following with Python:
Computer 1 starts SSH server (probably using twisted or paramiko)
Computer 1 connects to Server 1 (idle connection)
Computer 2 connects to Server 1
Server 1 forwards Computer 2's connection to Compu... | Establish SSH Connection Between Two Isolated Machines Using a 3rd System | I'd like to do the following with Python:
Computer 1 starts SSH server (probably using twisted or paramiko)
Computer 1 connects to Server 1 (idle connection)
Computer 2 connects to Server 1
Server 1 forwards Computer 2's connection to Computer 1 (connection no longer idle)
Computer 1 forwards Server 1's connection to ... | [
"I'd use ssh to create a remote tunnel (-R) from the server to the local system. If you're insistent on doing this with Python then there's the subprocess module.\n",
"I found out how to do it, using an example from twisted's (hard to find) example of conch @ http://twistedmatrix.com/trac/browser/trunk/twisted/co... | [
1,
0
] | [] | [] | [
"networking",
"portforwarding",
"python",
"ssh"
] | stackoverflow_0004686104_networking_portforwarding_python_ssh.txt |
Q:
django app using amazon aws s3 storage in stead of DB?
I'm looking at django for a rapid prototype to a photo sharing app with an amazon aws s3 storage back end.
However, as far as I can tell, Django is tailored toward the typical database MVC type of pattern. is there a way to for example provide a custom Django ... | django app using amazon aws s3 storage in stead of DB? | I'm looking at django for a rapid prototype to a photo sharing app with an amazon aws s3 storage back end.
However, as far as I can tell, Django is tailored toward the typical database MVC type of pattern. is there a way to for example provide a custom Django model implementation that talks to s3 in stead of a DB? a cu... | [
"S3 is best used for storing binaries, and databases are best for storing text (although, of course, exceptions exist). My recommendation is to store the filenames and version numbers in DB records, and keep the binaries in S3.\nTo answer your other question, you are free to rewrite Django's model layer (as done by... | [
2
] | [] | [] | [
"amazon_s3",
"django",
"django_models",
"python"
] | stackoverflow_0004687250_amazon_s3_django_django_models_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.