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:
How to remove white space at the bottom of matplotlib graph?
I looked over the matplotlib user guide and cant seem to find a way to remove the white space that is generated at the bottom of my graph.
fig = plt.figure(1,figsize=(5,10))
axis = fig.add_subplot(211, autoscale_on=False,xlim=(1,10),ylim=(0,1))
Are the ... | How to remove white space at the bottom of matplotlib graph? | I looked over the matplotlib user guide and cant seem to find a way to remove the white space that is generated at the bottom of my graph.
fig = plt.figure(1,figsize=(5,10))
axis = fig.add_subplot(211, autoscale_on=False,xlim=(1,10),ylim=(0,1))
Are the configurations I am using on the graph. I tried using frameon=Fal... | [
"You're creating space for a second plot and not using it. The line\naxis = fig.add_subplot(211, autoscale_on=False,xlim=(1,10),ylim=(0,1))\n\nadds a subplot to the figure, but the 211 means \"two plots high by one plot wide, position 1\". You could add a second plot below your current one with another subplot call... | [
12,
7,
3,
0,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0007001008_matplotlib_python.txt |
Q:
Celery: standard method for querying pending tasks?
Is there any standard/backend-independent method for querying pending tasks based on certain fields?
For example, I have a task which needs to run once after the “last user interaction”, and I'd like to implement it something like:
def user_changed_content():
... | Celery: standard method for querying pending tasks? | Is there any standard/backend-independent method for querying pending tasks based on certain fields?
For example, I have a task which needs to run once after the “last user interaction”, and I'd like to implement it something like:
def user_changed_content():
task = find_task(name="handle_content_change")
if ta... | [
"No, this is not possible.\nEven if some transports may support accessing the \"queue\" out of order (e.g. Redis)\nit is not a good idea.\nThe task may not be on the queue anymore, and instead reserved by a worker.\nSee this part in the documentation: http://docs.celeryproject.org/en/latest/userguide/tasks.html#sta... | [
9
] | [] | [] | [
"celery",
"python"
] | stackoverflow_0006998377_celery_python.txt |
Q:
is there something like a python parser for j2me?
I have a phone that does java and I want to program in bed, on my phone.
Is there any (python) parser on java basis for J2me, possibly?
is there a website where I can write and test python code? Then I could code in Opera.
A:
for the 1st question
see these links... | is there something like a python parser for j2me? | I have a phone that does java and I want to program in bed, on my phone.
Is there any (python) parser on java basis for J2me, possibly?
is there a website where I can write and test python code? Then I could code in Opera.
| [
"for the 1st question\nsee these links\nhttp://isiam.blogspot.com/2007/01/jython-examples.html\nhttp://www.awaretek.com/pymo.html\nfor the 2nd question\nyes you can write python in a browser\nhttp://codepad.org\nhttp://py-ide-online.appspot.com/\nthere's also a bunch of extensions for google chrome like this one\nh... | [
1
] | [] | [] | [
"java",
"python"
] | stackoverflow_0007008418_java_python.txt |
Q:
python append and += problem with dict
this seems really simple but I don't know what I got wrong.
d1 = dict(zip(range(10), [[]]*10))
l1 = zip(range(10), range(10,20))
for pair in l1:
d1[pair[0]].append(pair)
resulting d1:
>>> d1
{0: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8... | python append and += problem with dict | this seems really simple but I don't know what I got wrong.
d1 = dict(zip(range(10), [[]]*10))
l1 = zip(range(10), range(10,20))
for pair in l1:
d1[pair[0]].append(pair)
resulting d1:
>>> d1
{0: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)], 1: [(0, 10), (1, 11), (2, 1... | [
"Don't use multiplication with mutable objects. It gives you X references to the object, not X different objects.\nd1 = dict((idx, []) for idx in range(10))\n\n",
"Instead of [[]]*10, you should use \n[[] for i in range(10)]\n\nas the first one just makes a list of elements that point to a single array reference.... | [
5,
3
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0007009806_python_syntax.txt |
Q:
Change the type in a Python list?
Is there a Pythonic way to change the type of every object in a list?
For example, I have a list of objects Queries.
Is there a fancy way to change that list to a list of strings?
e.g.
lst = [<Queries: abc>, <Queries: def>]
would be changed to
lst = ['abc', 'def']
When str() is ... | Change the type in a Python list? | Is there a Pythonic way to change the type of every object in a list?
For example, I have a list of objects Queries.
Is there a fancy way to change that list to a list of strings?
e.g.
lst = [<Queries: abc>, <Queries: def>]
would be changed to
lst = ['abc', 'def']
When str() is used on a Queries object, the strings I... | [
"newlst = [str(x) for x in lst]\n\nYou could use a list comprehension.\n",
"Try this:\nnew_list = map(str, lst)\n\n",
"Try this (Python 3):\nnew_list = list(map(str, lst))\n\nor\nnew_list = [str(q) for q in lst]\n\n"
] | [
11,
9,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0007009984_list_python.txt |
Q:
Writing alternate lists' elements - Python
I am trying to write alternating elements of multiple lists to a file using Python. I can write all of one list, and then all of another list, but am having difficulty doing it in an alternate order. My code looks like this:
foo = ['a', 'b', 'c']
bar = ['1', '2', '3']
fil... | Writing alternate lists' elements - Python | I am trying to write alternating elements of multiple lists to a file using Python. I can write all of one list, and then all of another list, but am having difficulty doing it in an alternate order. My code looks like this:
foo = ['a', 'b', 'c']
bar = ['1', '2', '3']
fileout = open('zut.txt', 'w')
for i, el in foo, ba... | [
">>> zip(foo,bar)\n[('a', '1'), ('b', '2'), ('c', '3')]\n\nYou can then iterate over the list and access the elements of the tuple.\n>>> for tpl in zip(foo, bar):\n... print '%s\\t%s' % tpl\n...\na 1\nb 2\nc 3\n\n",
"You can use the following code:\nfoo = ['a', 'b', 'c']\nbar = ['1', '2', '3']... | [
5,
3,
2,
1
] | [] | [] | [
"formatting",
"list",
"python"
] | stackoverflow_0007010060_formatting_list_python.txt |
Q:
Is it possible to use Lambdas like this in Ruby?
Here is what I do quite often in Python:
simple_call = lambda name: extract(some[fairly][hidden], name)
result1 = simple_call('myname')
result2 = simple_call('yourname')
result3 = simple_call('hisname')
This is really handy if you have to extract some data from som... | Is it possible to use Lambdas like this in Ruby? | Here is what I do quite often in Python:
simple_call = lambda name: extract(some[fairly][hidden], name)
result1 = simple_call('myname')
result2 = simple_call('yourname')
result3 = simple_call('hisname')
This is really handy if you have to extract some data from some complex data structure or some strange API repeatedl... | [
"Short answer: No. The closest thing is:\nsimple_call = lambda {|name| extract(some[:fairly][:hidden], name) }\nresult1 = simple_call.call(\"myname\")\nresult2 = simple_call.call(\"yourname\")\nresult3 = simple_call.call(\"hisname\")\n\nWhy? Because parenthesis in Ruby are optional. Then, you need to tell ruby to c... | [
6,
6,
5,
4,
2
] | [] | [] | [
"closures",
"lambda",
"python",
"ruby"
] | stackoverflow_0007009048_closures_lambda_python_ruby.txt |
Q:
How to print the empty data present in a table from its HTML code?
I am using the HTMLParser module present in python to print the data in a table by parsing the HTML page through the HTMLParser. I am unable to print the empty field in the table.
Here is the code I'm using:
class MyParser(HTMLParser):
def __i... | How to print the empty data present in a table from its HTML code? | I am using the HTMLParser module present in python to print the data in a table by parsing the HTML page through the HTMLParser. I am unable to print the empty field in the table.
Here is the code I'm using:
class MyParser(HTMLParser):
def __init__(self, data ):
HTMLParser.__init__(self)
self.feed(... | [
"Well, if you really need this, try using handle_endtag:\nclass MyParser(HTMLParser):\n def __init__(self, data ):\n HTMLParser.__init__(self)\n self.data = \"\"\n self.feed(data)\n def handle_data(self, data):\n self.data = data\n def handle_endtag(self, tag, attrs):\n p... | [
0
] | [] | [] | [
"html_parsing",
"python"
] | stackoverflow_0007007858_html_parsing_python.txt |
Q:
Path Problems (command line)
I have created a script with an array containing file names. The script searches for pdf files through directories and sub-directories by recursion and adds them to an array. It then outputs a string into the command line for pdftk so as to merge them.
pdftk takes arguments such as:
pd... | Path Problems (command line) | I have created a script with an array containing file names. The script searches for pdf files through directories and sub-directories by recursion and adds them to an array. It then outputs a string into the command line for pdftk so as to merge them.
pdftk takes arguments such as:
pdftk inputpdf1.pdf inputpdf2.pdf ca... | [
"You need to escape the paths by enclosing them in double quotes, because of the whitespaces. Otherwise, your shell will interpret every whitespace as a seperator for a new file.\n\" \".join('\"' + str(f) + '\"' for f in filesArr)\n\nSeveral more things:\n\nYou call PDFTK for every PDF. You should put that out of t... | [
3,
0
] | [] | [] | [
"cmd",
"path",
"pdftk",
"python"
] | stackoverflow_0007010316_cmd_path_pdftk_python.txt |
Q:
Python Django template
Can I catch in any way the current year in the Django template language? I need to create a link for the current year and I don't want to pass it by hand. And sending it via the view throws me an error:
Caught NoReverseMatch while rendering: Reverse for 'blog_archive_year' with arguments '()... | Python Django template | Can I catch in any way the current year in the Django template language? I need to create a link for the current year and I don't want to pass it by hand. And sending it via the view throws me an error:
Caught NoReverseMatch while rendering: Reverse for 'blog_archive_year' with arguments '()' and keyword arguments '{'y... | [
"First you should define the year pattern in the url:\nurl(r'^(?P<year>\\d{4})/$', 'post_archive_year', name='blog_archive_year')\n\nTo print the current year in a template use:\n{% now Y %}\n\n"
] | [
2
] | [] | [] | [
"django",
"error_handling",
"python",
"templates"
] | stackoverflow_0007010524_django_error_handling_python_templates.txt |
Q:
Regex for identifying version numbers - Python
I need to find and replace version numbers within text with a generic placeholder e.g. '*'.
Problem is writing the regex that would capture the version numbers.
Some examples:
Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.1 (KHTML, like Gecko) Ubuntu/11.04 Chromium/1... | Regex for identifying version numbers - Python | I need to find and replace version numbers within text with a generic placeholder e.g. '*'.
Problem is writing the regex that would capture the version numbers.
Some examples:
Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.1 (KHTML, like Gecko) Ubuntu/11.04 Chromium/14.0.825.0 Chrome/14.0.825.0 Safari/535.1
Mozilla/5.... | [
"In the re module, use the sub function. It will return a string where all the matches for the input regex are replaced by the output of a function, or just a string. The problem is in determining which version numbers in each string you want to replace. I'm assuming that you want all version numbers replaced.\nimp... | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007010725_python_regex.txt |
Q:
Otsu's Method and A Median Filter in Python
I've tried looking around and have been unable to find any implementation of either Otsu's method or a median filter into Python other than OpenCV.These are the only two links of documentation for the OpenCV functions that I've tried.
http://opencv.willowgarage.com/docum... | Otsu's Method and A Median Filter in Python | I've tried looking around and have been unable to find any implementation of either Otsu's method or a median filter into Python other than OpenCV.These are the only two links of documentation for the OpenCV functions that I've tried.
http://opencv.willowgarage.com/documentation/c/image_filtering.html
http://www.cs.ind... | [
"In response to the Otsu Method I was able to find an image processing packaged called Mahotas that contained it. All I had to do was easy_install it. The documentation can be found here.\nhttp://packages.python.org/mahotas/index.html?highlight=otsu#mahotas.otsu\n",
"I am not sure about Otsu's method but the Scip... | [
7,
2,
0
] | [] | [] | [
"image_processing",
"python"
] | stackoverflow_0006944150_image_processing_python.txt |
Q:
Rearrange a grouping of numbers into a list of tuples
Given:
x = '1 (2,3), 4 (5)'
How would I get:
y = [(1,2),(1,3),(4,5)] ?
Thank you.
A:
>>> x = '1 (2,3), 4 (5)'
>>> gp = re.compile('\d+\s*\([\d,]+\)(?=,?)')
>>> # digit, whitespace, (, digits or commas, ), maybe a comma
>>> for token in gp.findall(x):
... ... | Rearrange a grouping of numbers into a list of tuples | Given:
x = '1 (2,3), 4 (5)'
How would I get:
y = [(1,2),(1,3),(4,5)] ?
Thank you.
| [
">>> x = '1 (2,3), 4 (5)'\n>>> gp = re.compile('\\d+\\s*\\([\\d,]+\\)(?=,?)')\n>>> # digit, whitespace, (, digits or commas, ), maybe a comma\n>>> for token in gp.findall(x):\n... token = token.split(\"(\", 1)\n... left, right = int(token[0]), map(int, token[1][:-1].split(\",\"))\n... for elt in right:\... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0007010993_python.txt |
Q:
django staticfiles with multiple apps
Let's say I have two apps:
foo and bar
the project structure like below, how do I make sure app styles do not conflict? Running manage.py collectstatic dissolves either one of the files currently... The admin app is imported to the collected directory within an 'admin' folder ... | django staticfiles with multiple apps | Let's say I have two apps:
foo and bar
the project structure like below, how do I make sure app styles do not conflict? Running manage.py collectstatic dissolves either one of the files currently... The admin app is imported to the collected directory within an 'admin' folder however my app static data gets imported di... | [
"Don't do that this way. With or without staticfiles/collectstatic, djando would ever serve one of the two style.css files. Just prepend the app name inside static/. See also how django/contrib/(admin|auth|...)/static are laid out\nProject\n|-- foo\n| |-- static\n| | `-- foo\n| | `-- css\n| | ... | [
9
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007011041_django_python.txt |
Q:
Matlab function equivalent for Python (Flood Fill)
Quick question, I'm looking for a python function that performs the equivalent job that matlab's imfill.m does. I realize that python has openCV but I have been unable to get that to work properly and am trying to find a substitute for it. The part of imfill that ... | Matlab function equivalent for Python (Flood Fill) | Quick question, I'm looking for a python function that performs the equivalent job that matlab's imfill.m does. I realize that python has openCV but I have been unable to get that to work properly and am trying to find a substitute for it. The part of imfill that I'm trying to replicate is the 'holes' part of it.
I ha... | [
"I was able to find a function within scipy that performed similar to what imfill does. It's called binary_fill_holes and it can be found here for anyone that is having the same problem as myself.\nAlthough I can't take full/any real credit for finding it since it was answered here to one of my other questions PIL ... | [
6
] | [] | [] | [
"flood_fill",
"image_processing",
"python"
] | stackoverflow_0006946152_flood_fill_image_processing_python.txt |
Q:
Django-guardian on DB with shared (non-exclusive) access
I am developing a Django app being a Web frontend to some Oracle database with another local DB keeping app's data such as Guardian permissions. The problem is that it can be modified from different places that I don't have control of.
Let's say we have 3 mo... | Django-guardian on DB with shared (non-exclusive) access | I am developing a Django app being a Web frontend to some Oracle database with another local DB keeping app's data such as Guardian permissions. The problem is that it can be modified from different places that I don't have control of.
Let's say we have 3 models: User, Thesis and UserThesis.
UserThesis - a table specif... | [
"I decided to go with manually checking the permissions, caching it whenever I can. I ended up with get_perms_from_cache(self, user) model method which helps me a lot.\n"
] | [
0
] | [] | [] | [
"database_permissions",
"django",
"django_permissions",
"python"
] | stackoverflow_0006775359_database_permissions_django_django_permissions_python.txt |
Q:
404 Error on urllib2.urlopen()
I'm trying to scrape a website using urllib2. However I get a 400 Page not found error. Here is my code:
rec_text = 'Genesis 1:1'
my_text = rec_text.strip()
book = my_text.split()[0]
chapter_verse = my_text.split()[1]
chapter = chapter_verse.split(':')[0]
verse = chapter_verse.split(... | 404 Error on urllib2.urlopen() | I'm trying to scrape a website using urllib2. However I get a 400 Page not found error. Here is my code:
rec_text = 'Genesis 1:1'
my_text = rec_text.strip()
book = my_text.split()[0]
chapter_verse = my_text.split()[1]
chapter = chapter_verse.split(':')[0]
verse = chapter_verse.split(':')[1]
webpage = urllib2.urlopen('h... | [
"Looking at the bible.cc site, it appears that capitalization matters. You need genesis and not Genesis, which you can get by changing the line to book = my_text.split()[0].lower().\nEdit: The rest of this doesn't actually relate to the error, but has some other tips.\nYou can streamline your code a bit by using mu... | [
1,
0
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0007009760_python_urllib2.txt |
Q:
Dll from python module is not released in Eclipse / PyDev
I'm unit-testing a python c module in Eclipse using PyDev unit-testing.
The development steps are:
I first write the python tests in Eclipse and then the c code that passes
the tests for the module in Codeblocks. Here is where a script is called
to create ... | Dll from python module is not released in Eclipse / PyDev | I'm unit-testing a python c module in Eclipse using PyDev unit-testing.
The development steps are:
I first write the python tests in Eclipse and then the c code that passes
the tests for the module in Codeblocks. Here is where a script is called
to create a dll and ctypes bindings for it. After that the “dll” and the... | [
"This happens because PyDev launches a shell that imports that dll (to do code-completion). You can do Ctrl+2 kill (with focus in a PyDev editor), to kill all the shells that PyDev may have spawned (that way you can update it).\nCheers,\nFabio\n"
] | [
2
] | [] | [] | [
"dll",
"pydev",
"python",
"unit_testing"
] | stackoverflow_0007007635_dll_pydev_python_unit_testing.txt |
Q:
Django model inheritance using single DB table - problems accessing subclass from superclass
I am developing a Django application using Oracle with no modifications to DB schema allowed.
I have one table in which all Thesis exist, which can be seperated in two disjoint sets: PhdThesis and BscMscThesis. I have also... | Django model inheritance using single DB table - problems accessing subclass from superclass | I am developing a Django application using Oracle with no modifications to DB schema allowed.
I have one table in which all Thesis exist, which can be seperated in two disjoint sets: PhdThesis and BscMscThesis. I have also Review model, which links to Thesis DB table and doesn't care whether it is PhdThesis or BscMscTh... | [
"It seems there is no easy way for Django to do this. I ended up implementing methods like is_phd() and is_bsc_msc() and using them like this:\ndef get_absolute_url(self):\n if self.is_phd():\n return self.phdthesis.get_absolute_url()\n else:\n return self.bscmscthesis.get_absolute_url()\n\n"
] | [
1
] | [] | [] | [
"django",
"django_inheritance",
"django_models",
"python",
"single_table_inheritance"
] | stackoverflow_0006760207_django_django_inheritance_django_models_python_single_table_inheritance.txt |
Q:
change matlab path from python
So I have the following problem: I have a folder at a location known from a config.py file, in my case externals/bct. Now this needs to be added to matlab's path. Now I've searched for some examples to edit matlab path but from what I can see let's say here: matlab path the changes a... | change matlab path from python | So I have the following problem: I have a folder at a location known from a config.py file, in my case externals/bct. Now this needs to be added to matlab's path. Now I've searched for some examples to edit matlab path but from what I can see let's say here: matlab path the changes are done from matlab. My question wou... | [
"Thanks for the inputs. The project already has an adapter that allows runnig matlab code from python using from scipy.io import loadmat, savemat. The problem was that we are using BCT and that need to be added to matlab path dinamically at startup. The solution that worked for me was to use the method already de... | [
1,
0
] | [] | [] | [
"matlab",
"python"
] | stackoverflow_0007007696_matlab_python.txt |
Q:
getting elements in a list according to list of indices in python
I have a list of indices, something like:
b=[0,2]
and a list of elements:
a = ['elem0','elem1','elem2']
I need a list that is composed of the elements in a with the indices in b
(in this example: ['elem0','elem2'])
A:
Use a list comprehen... | getting elements in a list according to list of indices in python | I have a list of indices, something like:
b=[0,2]
and a list of elements:
a = ['elem0','elem1','elem2']
I need a list that is composed of the elements in a with the indices in b
(in this example: ['elem0','elem2'])
| [
"Use a list comprehension:\n[a[i] for i in b]\n\n",
"Or:\nfrom operator import itemgetter\n\nb=[0,2]\na = ['elem0','elem1','elem2']\n\nprint itemgetter(*b)(a)\n>>> ('elem0','elem2')\n\n",
"Use a list comprehension to map the indexes to the list:\nb=[0,2]\na = ['elem0','elem1','elem2'] \n\nsublist = [a[i] for i ... | [
8,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007011636_python.txt |
Q:
retrieve value from childnodes with minidom
I am very new to XML and I trying to retrieve the value from childnodes
from xml.dom import minidom
def Get_ExtList(progName):
progFile='%s.xml'%progName
xmldoc = minidom.parse(progFile)
extList=[]
rootNode=xmldoc.firstChild
progNode=rootNode.childNo... | retrieve value from childnodes with minidom | I am very new to XML and I trying to retrieve the value from childnodes
from xml.dom import minidom
def Get_ExtList(progName):
progFile='%s.xml'%progName
xmldoc = minidom.parse(progFile)
extList=[]
rootNode=xmldoc.firstChild
progNode=rootNode.childNodes[1]
for fileNodes in progNode.childNodes:
... | [
"You are looping not only through nodes that contain <file> tags (ELEMENT_NODE node type), but also indentation white space (TEXT_NODE node type). For example in this element:\n<a>\n <b>c</b>\n</a>\n\nThere are three elements:\n\nTEXT_NODE with value \\n__ (spaces indicated with _)\nELEMENT_NODE with value <b>c</b... | [
1,
0,
0
] | [] | [] | [
"minidom",
"python",
"xml"
] | stackoverflow_0007001295_minidom_python_xml.txt |
Q:
Does a Python threading.Condition.wait() suspend execution immediately?
If I call wait() on a python condition variable, does the calling thread suspend execution and yield or does it keep blocking until the next context switch?
A:
The thread does yield. This yielding is due to the implementation of pthread_cond... | Does a Python threading.Condition.wait() suspend execution immediately? | If I call wait() on a python condition variable, does the calling thread suspend execution and yield or does it keep blocking until the next context switch?
| [
"The thread does yield. This yielding is due to the implementation of pthread_cond_wait or the equivalent suspension mechanism in in PyThread_acquire_lock. Since the condition variable is implemented using the system call interface, and Python uses native threading, the operating system scheduler is responsible for... | [
2,
1
] | [] | [] | [
"condition_variable",
"multithreading",
"python",
"suspend"
] | stackoverflow_0007011884_condition_variable_multithreading_python_suspend.txt |
Q:
how to get POST data in django 1.3
Hey, I am following this tutorial to learn to make a wiki page with Django. However, it is made in django 0.96 and I use Django 1.3 so there are some things that are different. Some I already fixed myself, however this one I can't seem to make it work.
I made a form that submits ... | how to get POST data in django 1.3 | Hey, I am following this tutorial to learn to make a wiki page with Django. However, it is made in django 0.96 and I use Django 1.3 so there are some things that are different. Some I already fixed myself, however this one I can't seem to make it work.
I made a form that submits data to a view.
This is the form:
<form... | [
"You've got to include {% csrf_token %} in your form's template between your <form> tags.\n<form method=\"post\" action\"/wikicamp/{{page_name}}/save/\">\n {% csrf_token %}\n <textarea name=\"content\" rows=\"20\" cols=\"60\">{{content}}</textarea><br>\n <input type=\"submit\" value=\"Save Page\"/>\n</form... | [
9,
9,
2,
2
] | [] | [] | [
"django",
"django_1.3",
"http_post",
"python"
] | stackoverflow_0006020928_django_django_1.3_http_post_python.txt |
Q:
Python function long parameter list
I'm looking for the best way to give a list of arguments to my function :
def myFunc(*args):
retVal=[]
for arg in args:
retVal.append(arg+1)
return "test",retVal
The problem is that it becomes very annoying when you have a long list of parameters to pass to ... | Python function long parameter list | I'm looking for the best way to give a list of arguments to my function :
def myFunc(*args):
retVal=[]
for arg in args:
retVal.append(arg+1)
return "test",retVal
The problem is that it becomes very annoying when you have a long list of parameters to pass to your function because you have to write t... | [
"Two options:\n\nTry reducing the number of arguments by splitting the logic into multiple functions.\nIf 1.) is not possible, you can use a dictionary a single argument - encapsulating all your arguments. This would be a flexible (signature of function stays the same, even if you take away or add parameters) and m... | [
4,
3
] | [] | [] | [
"list",
"long_parameter_list",
"parameters",
"python"
] | stackoverflow_0007012553_list_long_parameter_list_parameters_python.txt |
Q:
How to write a call back function for ignore in shutil.copytree
I am relatively new to python. I am trying to copy a directory to another directory maintaining the structure.
I am using
shutil.copytree(src, dst, symlinks=False, ignore=None,
copy_function=copy2, ignore_dangling_symlinks=False)
I am tryin... | How to write a call back function for ignore in shutil.copytree | I am relatively new to python. I am trying to copy a directory to another directory maintaining the structure.
I am using
shutil.copytree(src, dst, symlinks=False, ignore=None,
copy_function=copy2, ignore_dangling_symlinks=False)
I am trying to write a call back function for ignore.
My aim is to take a list ... | [
"The return of the ignore function needs to be a list of directories and files to ignore. You aren't returning anything, which returns None, so you are getting the error TypeError: argument of type 'NoneType' is not iterable.\nHere's an example that will copy the folder structure and the files listed in 'copy_the... | [
7,
6,
0,
0
] | [] | [] | [
"file_copying",
"python",
"shutil"
] | stackoverflow_0007012686_file_copying_python_shutil.txt |
Q:
How do I give a deferred AMP reply without blocking the system?
(I'm very open to suggestions for a better title.)
I am using the AMP protocol over Twisted to create a scheduler that feeds out jobs to its agents. The agents pull jobs from the scheduler, so the scheduler is an AMP server and the agents connect as c... | How do I give a deferred AMP reply without blocking the system? | (I'm very open to suggestions for a better title.)
I am using the AMP protocol over Twisted to create a scheduler that feeds out jobs to its agents. The agents pull jobs from the scheduler, so the scheduler is an AMP server and the agents connect as clients.
The idea is for an agent to connect, pick up a job from the t... | [
"One thing you might have missed is that an AMP responder method itself is also allowed to return a Deferred (search for may also return Deferreds in the AMP API docs). As long as the Deferred eventually fires with a dictionary which matches up with the command's response definition, everything will work fine.\nAl... | [
4
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0007012853_python_twisted.txt |
Q:
Can the CSV module parse files with multi-character delimiters?
I have a "CSV" file that uses a multi-character delimiter, so the data looks something like
field1_|#|_field2_|#|_field3_|#|_field4
Is there a way to use the Python CSV module to parse this file?
A:
Try to replace the multichar delimiter with the s... | Can the CSV module parse files with multi-character delimiters? | I have a "CSV" file that uses a multi-character delimiter, so the data looks something like
field1_|#|_field2_|#|_field3_|#|_field4
Is there a way to use the Python CSV module to parse this file?
| [
"Try to replace the multichar delimiter with the singlechar one. \nSomethin like this:\nclass DelimitedFile:\n def __init__(self, fname, mode='rb', ind=',', outd=','):\n self.f = open(fname, mode)\n self.ind = ind\n self.outd = outd\n\n def __iter__(self):\n return self\n\n def next(self):\n line ... | [
6,
1
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0007012398_csv_python.txt |
Q:
Strange python print behavior with unicode
I am wondering why i can use print to print a unicode string in my OSX Terminal.app, but if i redirect stdout to a file or pipe it to 'more', i get an UnicodeEncodeError.
How does python decides whether it prints unicode or throws an exception.
A:
Because your terminal ... | Strange python print behavior with unicode | I am wondering why i can use print to print a unicode string in my OSX Terminal.app, but if i redirect stdout to a file or pipe it to 'more', i get an UnicodeEncodeError.
How does python decides whether it prints unicode or throws an exception.
| [
"Because your terminal encoding is set correctly and when you redirect to a file (or pipe) the encoding is set to the default encoding (ASCII in python2.) try print sys.stdout.encoding in both time (when you run your script as the terminal as stdout and when you redirect to a file) and you will see the difference. ... | [
2
] | [] | [] | [
"macos",
"python",
"unicode"
] | stackoverflow_0007013354_macos_python_unicode.txt |
Q:
Is there a wiki processor for Trac to format and colour Python tracebacks?
Understandably many of the tickets we file in Trac contain tracebacks. It would be excellent if these were nicely formatted and syntax highlighted.
I've conducted a cursory Google search for a Python traceback wiki processor and have not fo... | Is there a wiki processor for Trac to format and colour Python tracebacks? | Understandably many of the tickets we file in Trac contain tracebacks. It would be excellent if these were nicely formatted and syntax highlighted.
I've conducted a cursory Google search for a Python traceback wiki processor and have not found any quick hits.
I'm happy to roll my own if anyone can recommend a traceback... | [
"I don't believe you need that patch. You could specify the shortcode mapping in the trac.ini, but you can also (at least in trac 0.12) just use the mime type directly:\n{{{\n#!text/x-python-traceback\n<traceback>\n}}}\n\nSee more at http://trac.edgewall.org/wiki/TracSyntaxColoring. x-python-traceback isn't in the... | [
4,
2,
2
] | [] | [] | [
"python",
"syntax",
"trac"
] | stackoverflow_0001275401_python_syntax_trac.txt |
Q:
map in python, that map multiple objects to each object in list
Possible Duplicate:
Making a flat list out of list of lists in Python
how can I create form a list e.g [[1,2],[3,4]] or [(1,2),(3,4)]
the list [1,2,3,4]
list comprehension(or map, filter)doesn't seems to have map object to more than one other object... | map in python, that map multiple objects to each object in list |
Possible Duplicate:
Making a flat list out of list of lists in Python
how can I create form a list e.g [[1,2],[3,4]] or [(1,2),(3,4)]
the list [1,2,3,4]
list comprehension(or map, filter)doesn't seems to have map object to more than one other object.
like SelectMany in C#'s LINQ
| [
"Standard libs are cool:\n>>> import itertools\n>>> l = [[1,2],[3,4]]\n>>> list(itertools.chain(*l))\n[1, 2, 3, 4]\n\n",
"You want to flatten the list.\n[y for x in [[1,2],[3,4]] for y in x]\n\n",
"Provided you know that it will be exactly 2 levels deep, you can do\n[j for i in [[1,2],[3,4]] for j in i]\n\nwher... | [
2,
0,
0,
0
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0007013877_list_comprehension_python.txt |
Q:
How to automate shell input with python?
I am automating some tasks with python, but have hit a bit of a roadblock. One of the tasks I am automating requires user input in the shell.
The requirement is that you to run the command with an email address as a parameter (simple enough), and then you are asked to aut... | How to automate shell input with python? | I am automating some tasks with python, but have hit a bit of a roadblock. One of the tasks I am automating requires user input in the shell.
The requirement is that you to run the command with an email address as a parameter (simple enough), and then you are asked to authenticate with the password for that email add... | [
"I'm not sure what you're asking in the second part, but subprocesses can be controlled with the pexpect module. For example:\n#!/usr/bin/env python\n\nimport pexpect\nimport sys\n\n# Get email and password somehow\n#email = ...\n#password = ...\n\n# Start the subprocess\nchild = pexpect.spawn('mycommand %s' % emai... | [
3,
1,
0
] | [] | [] | [
"python",
"shell",
"unix"
] | stackoverflow_0007010690_python_shell_unix.txt |
Q:
Round to a given number in Python
I'm running a simulation in which people age in small (month, week) increments. However, I have hazards in non-consistent age-intervals. Is there an simple/efficient way to round my age at any time to the nearest age-group (for the purpose of extracting the hazards for that age?
... | Round to a given number in Python | I'm running a simulation in which people age in small (month, week) increments. However, I have hazards in non-consistent age-intervals. Is there an simple/efficient way to round my age at any time to the nearest age-group (for the purpose of extracting the hazards for that age?
age_groups = np.array([0, .01, .1, 5, 1... | [
"I assume you have ages such as .5, 5, 6, 10, 32, 32.5, ect. that need to fall into the age_groups array you have. \nThis is an easy one-liner :)\nAssuming you have:\nage_groups = np.array([0, .01, .1, 5, 10, 15, 20, 25, 30, 35, 40])\nage = .5\n\nThe solution is:\nnearest_age = age_groups[(np.abs(age_groups-age)).a... | [
3,
2,
0
] | [] | [] | [
"numpy",
"python",
"rounding"
] | stackoverflow_0007013749_numpy_python_rounding.txt |
Q:
Django, Ajax + Generic foreign keys
I have a generic foreign key in one of my models:
# models.py
class Tasks(models.Model):
content_type = models.ForeignKey(ContentType, limit_choices_to=tasktype_limits, null=True, blank=True)
object_id = models.PositiveIntegerField(null=True, blank=True, )
ta... | Django, Ajax + Generic foreign keys | I have a generic foreign key in one of my models:
# models.py
class Tasks(models.Model):
content_type = models.ForeignKey(ContentType, limit_choices_to=tasktype_limits, null=True, blank=True)
object_id = models.PositiveIntegerField(null=True, blank=True, )
target = generic.GenericForeignKey('content... | [
"I had serious problems using JSON and Generic Keys, this is the method i used to solve my problem. I first made a list of the thing i need for example:\nsome_list = [some.pk,some.CONTENT_OBJECT.name] for some in GenericModel.objects.all()]\n\nThen, dump the data with simple json found in django.utils\ndata = simpl... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003555018_django_python.txt |
Q:
Creating a wrapper for a C# library in Python
Main goal: Create a wrapper for a C# library, which can be used in Python (2.6).
UPDATE: Now, I have updates to the method I am using, which is however not working well.
The code for the simple C# class library:
using System;
using System.Text;
using System.Runtime.In... | Creating a wrapper for a C# library in Python | Main goal: Create a wrapper for a C# library, which can be used in Python (2.6).
UPDATE: Now, I have updates to the method I am using, which is however not working well.
The code for the simple C# class library:
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace Test
{
[Guid("8F38030... | [
"A alternative would be if you you use Python for .NET. There seem to be alpha releases for Windows CPython 2.6 and 2.7 available. You could run simply:\nimport clr\nclr.AddReference(\"Your.Assembly.Name\")\nimport Test\ntest = Test.TestClass()\nprint test.Eureka()\n\n"
] | [
3
] | [] | [] | [
"c#",
"python",
"wrapper"
] | stackoverflow_0007008733_c#_python_wrapper.txt |
Q:
compiling java from within python
I'm making an application where people can upload a java code and do stuff with it.
The application i'm making is in Python. I was wondering whether it was possible to call the 'javac' command from within python, in order to compile the uploaded java file
I'm also using JPype
A:
... | compiling java from within python | I'm making an application where people can upload a java code and do stuff with it.
The application i'm making is in Python. I was wondering whether it was possible to call the 'javac' command from within python, in order to compile the uploaded java file
I'm also using JPype
| [
"http://docs.python.org/library/subprocess.html\nBut are you sure that allowing people to submit arbitrary code is a good idea? There are security aspects of that to consider...\n",
"Entirely possible: just use the system command and invoke the java compiler. You'll probably need to set class paths and things of ... | [
4,
0
] | [] | [] | [
"compilation",
"java",
"javac",
"python"
] | stackoverflow_0007014532_compilation_java_javac_python.txt |
Q:
Behavior of Python ** and % operators with big numbers
When I put in Python interpreter a ** b % c with large a (20 figures) b (4 figures) c (20 figures) I saw that Python calculates it pretty fast, almost like pow (a,b,c). I expect another behavior that Python first calculate a ** b then get the modulo (%) of res... | Behavior of Python ** and % operators with big numbers | When I put in Python interpreter a ** b % c with large a (20 figures) b (4 figures) c (20 figures) I saw that Python calculates it pretty fast, almost like pow (a,b,c). I expect another behavior that Python first calculate a ** b then get the modulo (%) of result and such calculation will take significantly more time.
... | [
"If you are typing into the Python interpreter something like:\n20937505974095709374 ** 3438\n\nThen seeing a couple of seconds wait. Then trying:\n20937505974095709374 ** 3438 % 6\n\nAnd seeing no wait, and wondering why there is a difference, then the delay that you see in the first instance is actually the time ... | [
6,
4,
2,
0
] | [] | [] | [
"math",
"modulo",
"python"
] | stackoverflow_0007014512_math_modulo_python.txt |
Q:
Passing table name as a parameter in pyodbc
I am trying to pass a table name in pyodbc as a parameter to access data from ms sql 2005. I've tried to substitute it with ? but it never works. I would be glad to receive any advice on how to accomplish this.
A:
Since you are using pyodbc, I assume you are not callin... | Passing table name as a parameter in pyodbc | I am trying to pass a table name in pyodbc as a parameter to access data from ms sql 2005. I've tried to substitute it with ? but it never works. I would be glad to receive any advice on how to accomplish this.
| [
"Since you are using pyodbc, I assume you are not calling a SPROC. \nI recommend building your SQL string in python and then passing it to SQL to execute.\nimport pyodbc\ndbconn = pyodbc.connect(ConnectionString)\nc = dbconn.cursor()\n\nj = 'table1' #where table1 is entered, retreived, etc\nquery = \"Select * from ... | [
4,
2
] | [] | [] | [
"database",
"odbc",
"pyodbc",
"python",
"sql_server_2005"
] | stackoverflow_0006669009_database_odbc_pyodbc_python_sql_server_2005.txt |
Q:
Ubuntu 11.04: Installing PIL into a virtualenv with PIP
I have spent hours now trying to figure this out.
I do the following:
sudo apt-get install python-dev
sudo apt-get install libjpeg8-dev
sudo apt-get install libfreetype6 libfreetype6-dev
mkvirtualenv -p python2.7 --no-site-packages foobar
pip install PIL
Wh... | Ubuntu 11.04: Installing PIL into a virtualenv with PIP | I have spent hours now trying to figure this out.
I do the following:
sudo apt-get install python-dev
sudo apt-get install libjpeg8-dev
sudo apt-get install libfreetype6 libfreetype6-dev
mkvirtualenv -p python2.7 --no-site-packages foobar
pip install PIL
Whenever I try to upload an image in my django-cms website I ge... | [
"I've ran into the same issue while trying to use Django & Virtualenv - I couldn't upload images and after some research everything pointed towards PIL. I did try to reinstall the package but even with all the required libraries uploaded PIL still wouldn't support JPGs and PNGs.\nSeems that Ubuntu peeps decided to ... | [
16
] | [] | [] | [
"pip",
"python",
"python_imaging_library",
"ubuntu",
"virtualenv"
] | stackoverflow_0006138848_pip_python_python_imaging_library_ubuntu_virtualenv.txt |
Q:
Javascript-like TCP socket client written in python?
In the page http://pypi.python.org/pypi/websocket-client/0.4 the first snippet (the "Low Level API example") is very much like the client example in http://docs.python.org/library/socket.html#example.
What I'm interested in is if is there any possibility of maki... | Javascript-like TCP socket client written in python? | In the page http://pypi.python.org/pypi/websocket-client/0.4 the first snippet (the "Low Level API example") is very much like the client example in http://docs.python.org/library/socket.html#example.
What I'm interested in is if is there any possibility of making a TCP client that is even driven, like the "JavaScript ... | [
"Take a look at Tornado and specifically at tornado.iostream — Convenient wrappers for non-blocking sockets.\n"
] | [
1
] | [] | [] | [
"events",
"javascript",
"python",
"tcp",
"tcpclient"
] | stackoverflow_0007010745_events_javascript_python_tcp_tcpclient.txt |
Q:
Sending a one-way message with Python on all threads except the sender
I'm developing an application in Python which needs to send a one-way message to all threads (threading module in Python2) in an array, except the current thread. I have tried variables, but that would result in all threads responding to it ins... | Sending a one-way message with Python on all threads except the sender | I'm developing an application in Python which needs to send a one-way message to all threads (threading module in Python2) in an array, except the current thread. I have tried variables, but that would result in all threads responding to it instead of all but the sender.
What is the best way to send messages that way?
| [
"Why not make the \"message\" be a tuple of (thread_id, 'message'), and then send it to all threads - the thread that sent it can just ignore messages with its own thread_id.\n",
"This is what Queue's are for. Give each thread a Queue, and write into all but your own.\n"
] | [
2,
1
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0007015171_multithreading_python.txt |
Q:
Edit jar files with python
Do you know a python module with which i can add files to a JAR archive?
(what i wan't to do is add .class files to a jar archive)
and the program that has to do it has to be written in python
Thanks!
A:
.jar files are just .zip files with a different file extension and a manifest.
T... | Edit jar files with python | Do you know a python module with which i can add files to a JAR archive?
(what i wan't to do is add .class files to a jar archive)
and the program that has to do it has to be written in python
Thanks!
| [
".jar files are just .zip files with a different file extension and a manifest. \nTry http://docs.python.org/library/zipfile.html\n",
"This can be done with subprocess calling the jar command:\nimport subprocess\ndef add_to_jar(file2add, jar_file):\n cmd = 'jar -uf ' + jar_file + \" \" + file2add\n proc = ... | [
10,
0
] | [] | [] | [
"jar",
"java",
"python"
] | stackoverflow_0007015203_jar_java_python.txt |
Q:
map(function, sequence) where function returns two values
Look at the following Python code:
def function(x):
return x, x+1
sequence = range(5)
map(function, sequence)
this returns
[(0,1), (1,2), (2,3), (3,4), (4,5)]
I want to get the output
[0, 1, 2, 3, 4], [1, 2, 3, 4, 5]
That means, I want to get the t... | map(function, sequence) where function returns two values | Look at the following Python code:
def function(x):
return x, x+1
sequence = range(5)
map(function, sequence)
this returns
[(0,1), (1,2), (2,3), (3,4), (4,5)]
I want to get the output
[0, 1, 2, 3, 4], [1, 2, 3, 4, 5]
That means, I want to get the two outputs of function into two different lists. Can I achieve ... | [
"Hope this helps:\n>>> a = [(0,1), (1,2), (2,3), (3,4), (4,5)]\n>>> zip(*a)\n[(0, 1, 2, 3, 4), (1, 2, 3, 4, 5)]\n\nhttp://docs.python.org/library/functions.html#zip\n",
">>> a = zip(*map(function, sequence))\n>>> for i in a: print(i)\n...\n(0, 1, 2, 3, 4)\n(1, 2, 3, 4, 5)\n\n",
"Another approach would be:\n>>> ... | [
9,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0007015307_python.txt |
Q:
.ics attachment Issue in yahoo mail
I am sending meeting events from my service . so i am generating .ics file in icalendar format and sending to defferent mail clients.
My Aim is to get the event dates enter code here be imported to the calendar automatically and should be able to send response to my service by c... | .ics attachment Issue in yahoo mail | I am sending meeting events from my service . so i am generating .ics file in icalendar format and sending to defferent mail clients.
My Aim is to get the event dates enter code here be imported to the calendar automatically and should be able to send response to my service by clicking ( yes, no , maybe if gmail) Acc... | [
"What a shame that Yahoo! Mail does not manage iCalendar events in Yahoo! Calendar yet, in 2011!\nAt least events are now provided as ICS attachments in \"new\" Yahoo! Mail and you can manage invitations manually. Maybe Yahoo! Classic did in the past. I will check and consider to revert possibly.\nThis is the only ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0005296220_python.txt |
Q:
Python: Difference of 2 datetimes in months
Possible Duplicate:
Best way to find the months between two dates (in python)
I would like to know how I can have the exact number of months for this difference:
date1 = datetime.strptime(str('2011-08-15 12:00:00'), '%Y-%m-%d %H:%M:%S')
date2 = datetime.strptime(str('2... | Python: Difference of 2 datetimes in months |
Possible Duplicate:
Best way to find the months between two dates (in python)
I would like to know how I can have the exact number of months for this difference:
date1 = datetime.strptime(str('2011-08-15 12:00:00'), '%Y-%m-%d %H:%M:%S')
date2 = datetime.strptime(str('2012-02-15'), '%Y-%m-%d')
date2-date1 results in... | [
"You could use python-dateutil.\nIn [4]: from datetime import datetime\n\nIn [5]: date1 = datetime.strptime(str('2011-08-15 12:00:00'), '%Y-%m-%d %H:%M:%S')\n\nIn [6]: date2 = datetime.strptime(str('2012-02-15'), '%Y-%m-%d')\n\nIn [7]: from dateutil import relativedelta\n\nIn [8]: r = relativedelta.relativedelta(da... | [
85,
29,
26,
6
] | [] | [] | [
"date",
"datediff",
"python",
"timedelta"
] | stackoverflow_0007015587_date_datediff_python_timedelta.txt |
Q:
python dictionaries and django
hi I have a python dictionary. How do I output the list of keys in django?
If I do something like
{% for key in dict.keys() %}
<tr>
<td>
key
</td>
</tr>
{% endfor %}
I get
TemplateSyntaxError: Could not parse the remainder: '()' from
'dict.keys()'
Thanks!
A:
You... | python dictionaries and django | hi I have a python dictionary. How do I output the list of keys in django?
If I do something like
{% for key in dict.keys() %}
<tr>
<td>
key
</td>
</tr>
{% endfor %}
I get
TemplateSyntaxError: Could not parse the remainder: '()' from
'dict.keys()'
Thanks!
| [
"You have to use {{ key }} inside the loop for this to work. Also:\n{% for key in dict.keys %}\n",
"You just need dict.keys, not dict.keys() -- the Django template system will automatically try to call any part of the variable that's callable.\n{% for key in list.keys %}\n<tr><td>{{ key }}</td></tr>\n{% endfor %}... | [
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007015776_python.txt |
Q:
What Python exception should I throw when an external hardware connect fails?
I am writing some Python code that uses a library to communicate with an external piece of hardware over USB. When the hardware library is unable to connect to the device, it returns False - otherwise it returns True.
I would like to ex... | What Python exception should I throw when an external hardware connect fails? | I am writing some Python code that uses a library to communicate with an external piece of hardware over USB. When the hardware library is unable to connect to the device, it returns False - otherwise it returns True.
I would like to examine this return and use it to trigger an exception - to be more Pythonic. What w... | [
"An IOError. From the docs:\n\nRaised when an I/O operation (such as a print statement, the built-in\n open() function or a method of a file object) fails for an I/O-related\n reason, e.g., “file not found” or “disk full”.\n\nYou may want to wrap this in your own exception like:\n class ExternalDeviceNotFound(IO... | [
3
] | [] | [] | [
"exception",
"hardware",
"python"
] | stackoverflow_0007015805_exception_hardware_python.txt |
Q:
python paramiko: Permission denied
I have a sftp program called transmit. I use it to access a sftp server. I log in with username, password and everything works fine. I can delete, create and see everything.
Now I must access this sftp server with a python script. Therefore I installed parmiko. I set up everythi... | python paramiko: Permission denied | I have a sftp program called transmit. I use it to access a sftp server. I log in with username, password and everything works fine. I can delete, create and see everything.
Now I must access this sftp server with a python script. Therefore I installed parmiko. I set up everything as in the demo file but I strangly ge... | [
"I think the second argument should be a filename, instead of a dot .\nReplace \nsftp.get(\"~/myfolder/test.png\",\".\", None )\n\nwith something like\nsftp.get(\"~/myfolder/test.png\",\"~/test.png\", None )\n\n"
] | [
0
] | [] | [] | [
"paramiko",
"permission_denied",
"python",
"sftp"
] | stackoverflow_0007015817_paramiko_permission_denied_python_sftp.txt |
Q:
IMAP search for email address in the from field
I am trying to search and filter my imap mails using python's imaplib. I am running into a quite strange problem with the search command, searching for email addresses in the FROM field. I have the following script,
print('search with name')
status, results = con.sea... | IMAP search for email address in the from field | I am trying to search and filter my imap mails using python's imaplib. I am running into a quite strange problem with the search command, searching for email addresses in the FROM field. I have the following script,
print('search with name')
status, results = con.search(None, '(FROM "Shrikant Sharat")')
if status == 'O... | [
"use this as your filter:\n(HEADER FROM \"shrikantsharat.k@gmail.com\")\n\n"
] | [
8
] | [] | [] | [
"exchange_server",
"imap",
"imaplib",
"python"
] | stackoverflow_0005877529_exchange_server_imap_imaplib_python.txt |
Q:
Combining elements in list using python
Given input:
list = [['a']['a', 'c']['d']]
Expected Ouput:
mylist = a,c,d
Tried various possible ways, but the error recieved is TypeError: list indices must be integers not tuple.
Tried:
1.
k= []
list = [['a']['a', 'c']['d']]
#k=str(list)
for item in list:
k+=ite... | Combining elements in list using python | Given input:
list = [['a']['a', 'c']['d']]
Expected Ouput:
mylist = a,c,d
Tried various possible ways, but the error recieved is TypeError: list indices must be integers not tuple.
Tried:
1.
k= []
list = [['a']['a', 'c']['d']]
#k=str(list)
for item in list:
k+=item
print k
2.
print zip(*list)
etc.
Also to... | [
"What you want is flattening a list.\n>>> import itertools\n>>> l\n[['a'], ['a', 'c'], ['d']]\n>>> res = list(itertools.chain.from_iterable(l))\n>>> res\n['a', 'a', 'c', 'd']\n>>> set(res) #for uniqify, but doesn't preserve order\n{'a', 'c', 'd'}\n\nEdit: And your problem is, when defining a list, you should sepera... | [
4,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0007015889_list_python.txt |
Q:
Closing threaded Tkinter window
I use a Tkinter window to visualize some output of my programm. The window is threaded (see basic structure below) and basically it works quite fine. So far, I only have trouble closing the window. When I clicke the "X" button for closing the window it works.
However, when I call th... | Closing threaded Tkinter window | I use a Tkinter window to visualize some output of my programm. The window is threaded (see basic structure below) and basically it works quite fine. So far, I only have trouble closing the window. When I clicke the "X" button for closing the window it works.
However, when I call the Monitor.close() method from the mai... | [
"Python Threading and Tk(inter) used in this way do not mix well, as they violate the Tcl/Tk threading model of using Tk just from one thread.\nIt works great with message passing though, just not with direct calls from a thread. So you need to add some message passing via Queue to this.\nHave a look at http://effb... | [
3
] | [] | [] | [
"multithreading",
"python",
"tkinter"
] | stackoverflow_0007008187_multithreading_python_tkinter.txt |
Q:
Generator and actual variable values
I need to write a function which returns an list of sum functions, adding an input number to some binded value. This is what i did:
def addition_range(start, end):
if start >= end: return None
#res = ( (lambda x: x + i) for i in range(start, end) ) #1
res = [ (lamb... | Generator and actual variable values | I need to write a function which returns an list of sum functions, adding an input number to some binded value. This is what i did:
def addition_range(start, end):
if start >= end: return None
#res = ( (lambda x: x + i) for i in range(start, end) ) #1
res = [ (lambda x: x + i) for i in range(start, end) ] ... | [
"The easiest way to solve this is by adding a dummy parameter:\ndef addition_range(start, end):\n res = [(lambda x, i=i: x + i) for i in range(start, end)]\n return res or None\n\nThe dummy parameter is evaluated at the time the lambda is defined, whereas your version evaluates i only when the lambda is calle... | [
1
] | [] | [] | [
"generator",
"python"
] | stackoverflow_0007016260_generator_python.txt |
Q:
removing elements from a list
How can i remove elements with a value of 0 as they pop upp in this loop?
y = [4, 2, 7, 9]
x = input("run?")
while x:
for i in range(len(y)):
y[i] -= 1
y.append(len(y))
print(y)
A:
you could always use a list comprehension to filter them:
for i in range(len(y)):
... | removing elements from a list | How can i remove elements with a value of 0 as they pop upp in this loop?
y = [4, 2, 7, 9]
x = input("run?")
while x:
for i in range(len(y)):
y[i] -= 1
y.append(len(y))
print(y)
| [
"you could always use a list comprehension to filter them:\nfor i in range(len(y)):\n y[i] -= 1\ny = [x for x in y if x != 0] # <-- added here\ny.append(len(y))\n\nEDIT:\nI'm silly - these operations could even be combined as so:\nwhile whatever: #<-- fix as suggested by comment on your question\n y = [z-1 f... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0007016304_python.txt |
Q:
Python, basic question: How do I download multiple url's with urllib.request.urlretrieve
I have the following fully functional, working code:
import urllib.request
import zipfile
url = "http://url.com/archive.zip?key=7UCxcuCzFpYeu7tz18JgGZFAAgXQ2sop"
filename = "C:/test/archive.zip"
destinationPath = "C:/test"
... | Python, basic question: How do I download multiple url's with urllib.request.urlretrieve | I have the following fully functional, working code:
import urllib.request
import zipfile
url = "http://url.com/archive.zip?key=7UCxcuCzFpYeu7tz18JgGZFAAgXQ2sop"
filename = "C:/test/archive.zip"
destinationPath = "C:/test"
urllib.request.urlretrieve(url,filename)
sourceZip = zipfile.ZipFile(filename, 'r')
for name ... | [
"You want to put your urls in a list, then loop through that list and try each one. You catch but ignore exceptions they throw, and break the loop once one succeeds. Try this:\nimport urllib.request\nimport zipfile\n\nurls = [\"http://url.com/archive.zip?key=7UCxcuCzFpYeu7tz18JgGZFAAgXQ2sop\", \"other url\", \"anot... | [
3,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007016252_python.txt |
Q:
why is Python.h in my /usr/local/python2.6 folder when my Mac is using python 2.7?
I'm running a new mac with osx lion and it came with the latest Python 2.7. My /Library/Frameworks/Python.framework/Versions directory has 2.3, 2.5, 2.6, 2.7, and Current.
Now 2.5 and 2.6 have Python.h and many other header files i... | why is Python.h in my /usr/local/python2.6 folder when my Mac is using python 2.7? | I'm running a new mac with osx lion and it came with the latest Python 2.7. My /Library/Frameworks/Python.framework/Versions directory has 2.3, 2.5, 2.6, 2.7, and Current.
Now 2.5 and 2.6 have Python.h and many other header files in /include.
My problem is I can't find any header files except pyconfig.h in the 2.7/in... | [
"OK found the answer.\nYou need to install a newer version of Xcode. \nI had installed an older Xcode 3.2 on Lion. After upgrading, my /usr/include/python2.7 directory was populated with the header files.\n",
"Your headers should be in /usr/include.\nFor example:\n$ ls /usr/include/python2.*/Python.h\n/usr/includ... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0007015910_python.txt |
Q:
How do you deserialize a C# object in database using Python?
We have an application that takes user data in C#, serializes it and puts it in a database.
I need to write an admin program in Python that takes that value and deserialize it. I've tried using Pickle but I believe the format is different, because I k... | How do you deserialize a C# object in database using Python? | We have an application that takes user data in C#, serializes it and puts it in a database.
I need to write an admin program in Python that takes that value and deserialize it. I've tried using Pickle but I believe the format is different, because I keep getting errors.
Is this doable?
Thanks!
Edit 1: The type is b... | [
"Use IronPython so you can just use the .NET framework, like you did to save the data.\n"
] | [
0
] | [] | [] | [
"c#",
"python",
"serialization"
] | stackoverflow_0007016397_c#_python_serialization.txt |
Q:
Python, find specified file in folder
What is wrong in this code? I want to find a specified file in folder. Thansk for your help.
import os, fnmatch
def find(root, mask): //Error
files_list = os.listdir(os.path.abspath(root))
for filename in fnmatch.filter(files_list, mask):
yield filename
def t... | Python, find specified file in folder | What is wrong in this code? I want to find a specified file in folder. Thansk for your help.
import os, fnmatch
def find(root, mask): //Error
files_list = os.listdir(os.path.abspath(root))
for filename in fnmatch.filter(files_list, mask):
yield filename
def test():
res = find ('D:\\Sample\\', 'hal... | [
"Your function is a generator, it will yield filenames one by one. You can call list on res if you want a list of all matches:\nlist_of_matches = list(res)\n\nAlso your default argument of root=os.dir makes no sense. Maybe use '.'?\n",
"Some indentation missing for the test function\ndef test ():\n res = find ... | [
1,
0
] | [] | [] | [
"file",
"find",
"python"
] | stackoverflow_0007016452_file_find_python.txt |
Q:
Python: Interacting with Oracle database without using ODBC
I am new to python and currently writing a module to write error logs into Oracle database. Its not possible to install ODBC libraries on the server for this task so I am wondering what is the best way to handle this without using ODBC (such as pyodbc). I... | Python: Interacting with Oracle database without using ODBC | I am new to python and currently writing a module to write error logs into Oracle database. Its not possible to install ODBC libraries on the server for this task so I am wondering what is the best way to handle this without using ODBC (such as pyodbc). I am advised to use ORMs so any of you have some idea about this? ... | [
"There are apparently a number of options, a mere google search away:\nhttp://wiki.python.org/moin/Oracle\nMy guess is that cx_Oracle is the one you want.\n",
"cx_Oracle doesn't use ODBC but you have to install the Oracle client tools.\nIf the JVM and Jython is an option for you the Oracle Thin Driver for JDBC ca... | [
1,
1
] | [] | [] | [
"oracle",
"orm",
"python"
] | stackoverflow_0007016145_oracle_orm_python.txt |
Q:
Why does python's dictionary iteration seemingly work with a copy?
I am confused how python is iterating through this dictionary. From python's documentation, the itervalues returns an iterator over the dictionary's values.
dict = {"hello" : "wonderful", "today is" : "sunny", "more text" : "is always good"}
for x... | Why does python's dictionary iteration seemingly work with a copy? | I am confused how python is iterating through this dictionary. From python's documentation, the itervalues returns an iterator over the dictionary's values.
dict = {"hello" : "wonderful", "today is" : "sunny", "more text" : "is always good"}
for x in dict.itervalues():
x = x[2:]
print dict
This prints out the... | [
"This has nothing to do with strings or lists. The devil is in how the for is unfolded.\nDoing \nfor x in d.iteritems():\n # loop body\n\nis more-or-less equivalent to doing \niter = d.itervalues()\nwhile True:\n try:\n x = next(iter)\n # loop body\n except StopIteration:\n break\n\nSo... | [
7,
5,
1
] | [] | [] | [
"copy",
"items",
"iterator",
"python"
] | stackoverflow_0007016696_copy_items_iterator_python.txt |
Q:
In Python 2, creating a random question from shuffled numbers
I hope I can get some help with this, I've had absolutely no luck looking online. well that and the fact I'm new to Python.
I'm going through Learn Python The Hard Way, and am really starting to like python. So I made a simple little game. I'm looking ... | In Python 2, creating a random question from shuffled numbers | I hope I can get some help with this, I've had absolutely no luck looking online. well that and the fact I'm new to Python.
I'm going through Learn Python The Hard Way, and am really starting to like python. So I made a simple little game. I'm looking for a way to "cheat death", and my idea is that to escape death, yo... | [
"from random import shuffle\n\nnumbers = [1, 75, 64, 80275, 2, 7]\nshuffle(numbers)\nprint numbers\n# [80275, 64, 75, 2, 7, 1]\nquestion = \"%d + %d / %d * %d - %d * %d\" % tuple(numbers)\nprint question \n# 80275 + 64 / 75 * 2 - 7 * 1\nanswer = eval(question)\nprint answer\n# 80269.7066667\n\n",
"def cheat_death... | [
2,
0
] | [] | [] | [
"python",
"shuffle"
] | stackoverflow_0007016636_python_shuffle.txt |
Q:
Help with accessing module variable inside Python function?
I have the following function in a Python module called dictbuilder.py:
def my_dictbuilder(reader_o, writer):
fieldnames = ('name', 'number')
reader = csv.DictReader(reader_o, fieldnames = fieldnames, delimiter="\t")
my_dict = {}
id = 0
... | Help with accessing module variable inside Python function? | I have the following function in a Python module called dictbuilder.py:
def my_dictbuilder(reader_o, writer):
fieldnames = ('name', 'number')
reader = csv.DictReader(reader_o, fieldnames = fieldnames, delimiter="\t")
my_dict = {}
id = 0
for row in reader:
id += 1
my_dict[id] = row['nam... | [
"Well, you're returning my_dict, so just store the return value in your main module when you call it.\nmy_dict = dictbuilder.my_dictbuilder(reader_o, writer)\n\n"
] | [
1
] | [] | [] | [
"global_variables",
"local_variables",
"module",
"python",
"variables"
] | stackoverflow_0007016831_global_variables_local_variables_module_python_variables.txt |
Q:
imshow for 3D? (Python / Matplotlib)
does there exist an equivalent to matplotlib's imshow()-function for 3D-drawing of datas stored in a 3D numpy array?
A:
This is ill-defined, since how would you see stuff that was not at the surface of the cube?
The Mayavi documentation has various approaches of ways to do wh... | imshow for 3D? (Python / Matplotlib) | does there exist an equivalent to matplotlib's imshow()-function for 3D-drawing of datas stored in a 3D numpy array?
| [
"This is ill-defined, since how would you see stuff that was not at the surface of the cube?\nThe Mayavi documentation has various approaches of ways to do what you want to do, including cut planes and voxel-specific alpha channels. See visualizing volumetric scalar data. \nSuffice it to say this requires Mayavi an... | [
5,
4,
0,
0
] | [] | [] | [
"matplotlib",
"numpy",
"python"
] | stackoverflow_0007011428_matplotlib_numpy_python.txt |
Q:
Splitting Paragraphs in Python using Regular Expression containing abbreaviations
Tried using this function on a paragraph consisting of 3 strings and abbreviations.
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
def splitParagraphIntoSentences(paragraph):
''' break a paragraph into sentences
and retur... | Splitting Paragraphs in Python using Regular Expression containing abbreaviations | Tried using this function on a paragraph consisting of 3 strings and abbreviations.
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
def splitParagraphIntoSentences(paragraph):
''' break a paragraph into sentences
and return a list '''
import re
# to split by multile characters
# regular expres... | [
"The regex you want is:\n[.!?][\\s]{1,2}(?=[A-Z])\n\nYou want a positive lookahead assertion, which means you want to match the pattern if it's followed by a capital letter, but not match the capital letter.\nThe reason only the first one got matched is you don't have a space after the 2nd period.\n"
] | [
2
] | [] | [] | [
"python",
"regex",
"split"
] | stackoverflow_0007017193_python_regex_split.txt |
Q:
Python web crawler with MySQL database
I want to create or find an open source web crawler (spider/bot) written in Python. It must find and follow links, collect meta tags and meta descriptions, title's of web pages and the url of a webpage and put all of the data into a MySQL database.
Does anyone know of any ope... | Python web crawler with MySQL database | I want to create or find an open source web crawler (spider/bot) written in Python. It must find and follow links, collect meta tags and meta descriptions, title's of web pages and the url of a webpage and put all of the data into a MySQL database.
Does anyone know of any open source scripts that could help me? Also, i... | [
"I would suggest you to use Scrapy, which is a powerful scraping framework based on Twisted and lxml. It is particularly well suited for the kind of tasks you want to perform, it features regex based rules to follow links and lets you use either regular expressions or XPath expressions to extract data from the html... | [
4,
4,
3
] | [] | [] | [
"mysql",
"python",
"sql",
"web_crawler",
"web_scraping"
] | stackoverflow_0007017216_mysql_python_sql_web_crawler_web_scraping.txt |
Q:
Best way to deal with default params in Python?
I've got some code (that someone else wrote):
def render(self, name, value, attrs=None):
if not attrs:
attrs = {}
attrs.update({'class': 'ui-autocomplete-input'})
which I think could be re-written as:
def render(self, name, value, attrs={}):
attr... | Best way to deal with default params in Python? | I've got some code (that someone else wrote):
def render(self, name, value, attrs=None):
if not attrs:
attrs = {}
attrs.update({'class': 'ui-autocomplete-input'})
which I think could be re-written as:
def render(self, name, value, attrs={}):
attrs.update({'class': 'ui-autocomplete-input'})
This wo... | [
"Using attrs = {} in the function signature will bite you, since it will keep its value on successive calls to the function. The original code is best.\neg.\n>>> def a(attrs= {}):\n... print attrs\n... attrs.update({1:1})\n...\n>>> a()\n{}\n>>> a()\n{1: 1}\n\nNote how it kept the value assigned the first time,... | [
13,
2,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0007017414_python.txt |
Q:
split command question
I got problem with using split command.
The input string is as follows:
080821_HWI-EAS301_0002_30ALBAAXX:1:8:1649:2027 83 chr10 42038185 255 36M = 42037995 -225 GCCAGGTTTAATAAATTATTTATAGAATACTGCATC @?DDEAEFDAD@FBG@CDA?DBCDEECD@D?CBA>A NM:i:0 MD:Z:36
I want to grab '202... | split command question | I got problem with using split command.
The input string is as follows:
080821_HWI-EAS301_0002_30ALBAAXX:1:8:1649:2027 83 chr10 42038185 255 36M = 42037995 -225 GCCAGGTTTAATAAATTATTTATAGAATACTGCATC @?DDEAEFDAD@FBG@CDA?DBCDEECD@D?CBA>A NM:i:0 MD:Z:36
I want to grab '2027' from this string
my comma... | [
"It appears that what you want is\nline.split(':',4)[4].split()[0]\n\nThe numeric parameter to split indicates the maximum number of splits that will occur. So you have:\n>>> line='080821_HWI-EAS301_0002_30ALBAAXX:1:8:1649:2027 ...'\n>>> line.split(':',4)\n['080821_HWI-EAS301_0002_30ALBAAXX', '1', '8', '1649', '20... | [
6,
2,
1,
0,
0,
0,
0
] | [] | [] | [
"python",
"split"
] | stackoverflow_0007012963_python_split.txt |
Q:
Python question about exponents and int
Out of curiosity I ran the following:
>>> int(1e100)
And, the output was:
10000000000000000159028911097599180468360808563945281389781327557747838772170381060813469985856815104L
Why? Why does this not look like:
10000000000000000000000000000000000000000000000000000000000000... | Python question about exponents and int | Out of curiosity I ran the following:
>>> int(1e100)
And, the output was:
10000000000000000159028911097599180468360808563945281389781327557747838772170381060813469985856815104L
Why? Why does this not look like:
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000L
Is ... | [
"1e100 is a floating point number, with 53 bits of precision in the significand. The integer you're trying to represent requires 333 bits for exactness, so there is some rounding involved. The bottom bits are substituted to make the closest base 2 number to your desired result.\nSee: http://docs.python.org/tutorial... | [
9,
1,
0
] | [] | [] | [
"floating_point",
"python"
] | stackoverflow_0007017245_floating_point_python.txt |
Q:
PicklingError when using multiprocessing
I am having trouble when using the Pool.map_async() (and also Pool.map()) in the multiprocessing module. I have implemented a parallel-for-loop function that works fine as long as the function input to Pool.map_async is a "regular" function. When the function is e.g. a meth... | PicklingError when using multiprocessing | I am having trouble when using the Pool.map_async() (and also Pool.map()) in the multiprocessing module. I have implemented a parallel-for-loop function that works fine as long as the function input to Pool.map_async is a "regular" function. When the function is e.g. a method to a class, then I get a PicklingError:
cPi... | [
"The problem here is less of the \"pickle\" error message than conceptual:\nmultiprocess does fork your code in \"worker\" different processes in order to perform\nits magic.\nIt then sends data to and from the different process by seamlessly serializing and de-serializing the data (that is the part that uses the p... | [
22
] | [] | [] | [
"multiprocessing",
"python",
"python_multiprocessing"
] | stackoverflow_0007016567_multiprocessing_python_python_multiprocessing.txt |
Q:
django and backbone.js questions
I'm looking at making backbone.js (plus jQuery) work with my django app, but I have some questions. I've never used a restful setup before, so I have very little knowledge of the "proper" way to use REST.
Backbone uses REST architecture, but django doesn't support this by defaul... | django and backbone.js questions | I'm looking at making backbone.js (plus jQuery) work with my django app, but I have some questions. I've never used a restful setup before, so I have very little knowledge of the "proper" way to use REST.
Backbone uses REST architecture, but django doesn't support this by default. It looks like tastypie or piston a... | [
"you can point backbone collections/models toward whatever urls you want and parse the response however you want in your backbone \"subclasses\".\nModel.url:\nhttp://documentcloud.github.com/backbone/docs/backbone.html#section-43\nCollection.parse:\nhttp://documentcloud.github.com/backbone/docs/backbone.html#sectio... | [
21
] | [] | [] | [
"backbone.js",
"django",
"javascript",
"python"
] | stackoverflow_0007015638_backbone.js_django_javascript_python.txt |
Q:
how to write in next row using python?
1234 5678 9876 542 1231; 2333 1234 5678 579
i want to write this data in a csv (myfile.csv) file from a .txt (murtuz.txt) file such that after semi colon it starts from the next row.
I have tried the code mentioned below, it helps me to write data in csv file but i am failed ... | how to write in next row using python? | 1234 5678 9876 542 1231; 2333 1234 5678 579
i want to write this data in a csv (myfile.csv) file from a .txt (murtuz.txt) file such that after semi colon it starts from the next row.
I have tried the code mentioned below, it helps me to write data in csv file but i am failed to change the line after semi colon.
import ... | [
"csv.reader can accept any iterable as input. In particular, you can feed it lines yielded from a generator. You can use that generator to massage your input data -- for example, to split on semicolons:\ninput csv\ninput textwrap\ninput io\n\ndef splitter(iterable):\n for line in iterable:\n for part in l... | [
3,
0,
0,
0
] | [] | [] | [
"csv",
"file_io",
"python"
] | stackoverflow_0007017408_csv_file_io_python.txt |
Q:
Sqlite REFERENCES keyword
Does anyone know what the REFERENCES keyword does in sqlite? For example if I had the following statement: fr int REFERENCES contacts(id) what does that mean and how do I use it if I wanted to SELECT count(fr) from TABLE WHERE I know a contact's id?
In other words I want to create a SELEC... | Sqlite REFERENCES keyword | Does anyone know what the REFERENCES keyword does in sqlite? For example if I had the following statement: fr int REFERENCES contacts(id) what does that mean and how do I use it if I wanted to SELECT count(fr) from TABLE WHERE I know a contact's id?
In other words I want to create a SELECT statement that counts the num... | [
"to answer the other part of the question, you would do:\nselect count(*) from tablename where fr = contactid;\n\nsince the \"references\" indicates that the fr field contains values from the id field in contacts.\nsome extra details: you have two tables: contacts and \"tablename\". in contacts you have details of... | [
2,
1
] | [] | [] | [
"python",
"sql",
"sqlite"
] | stackoverflow_0007016128_python_sql_sqlite.txt |
Q:
I want a clever algorithm for indexing a file directory...pointers?
I have a directory of music on Ubuntu (.mp3, .wav, etc) files. This directory can have as many sub directories as it needs, no limits. I want to be able to make a music library out of it - that is, return list of songs based on filters of:
1) memb... | I want a clever algorithm for indexing a file directory...pointers? | I have a directory of music on Ubuntu (.mp3, .wav, etc) files. This directory can have as many sub directories as it needs, no limits. I want to be able to make a music library out of it - that is, return list of songs based on filters of:
1) membership to playlist
2) artist name
3) string search
4) name of song
etc, e... | [
"The hard part of this is the scanning of the directory, just because it can be expensive.\nBut that's a cruel reality since you can't use inotify et al.\nIn your database, simply create a node type record:\ncreate table node (\n nodeKey integer not null primary key,\n parentNode integer references node(nodeK... | [
3,
3,
2,
0,
0
] | [] | [] | [
"database",
"hash",
"mysql",
"python",
"sql"
] | stackoverflow_0006798351_database_hash_mysql_python_sql.txt |
Q:
python list getting element in django
I am trying to get the only element in a python list of dictionary.
If I do:
{{k.value}}
I get
[{'value_type': 2L, 'value_as_double': 74.0}]
How do I get just the 74?
A:
Try {{ k.value.0.value_as_double }}.
| python list getting element in django | I am trying to get the only element in a python list of dictionary.
If I do:
{{k.value}}
I get
[{'value_type': 2L, 'value_as_double': 74.0}]
How do I get just the 74?
| [
"Try {{ k.value.0.value_as_double }}.\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007017714_django_python.txt |
Q:
How to get a Python Tkinter Applet to Web Page
I wrote an applet in Python using the Tkinter library. I finished writing the applet but now I want to make it public on my website. Does anyone know a way to get the python script to work on my website? I don't want it to have to be something that needs to be downloa... | How to get a Python Tkinter Applet to Web Page | I wrote an applet in Python using the Tkinter library. I finished writing the applet but now I want to make it public on my website. Does anyone know a way to get the python script to work on my website? I don't want it to have to be something that needs to be downloaded, but can just run in the browser if possible.
T... | [
"What you ask is not possible. Several years ago there was a Tcl/Tk browser plugin, but the last time anyone touched that sourceforge project was back in 2006. I seriously doubt it could be made to work with tkinter. For that matter, I doubt it works for tcl/tk either. Browsers have advanced quite a bit since then.... | [
8
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0007017538_python_tkinter.txt |
Q:
Django: write SQL code from Model.save() in text file
How can I overwrite a model.save() method to write every SQL code it generates on a text file?
I am working with PostgreSQL, and it would also work if I did this on a database level (write every SQL code that changes a table on a text file).
A:
You can see th... | Django: write SQL code from Model.save() in text file | How can I overwrite a model.save() method to write every SQL code it generates on a text file?
I am working with PostgreSQL, and it would also work if I did this on a database level (write every SQL code that changes a table on a text file).
| [
"You can see the raw queries with django.db.connection.queries. More info here.\nSo examine that object in your save method and write the newest query to a file.\n"
] | [
1
] | [] | [] | [
"django",
"postgresql",
"python"
] | stackoverflow_0007017330_django_postgresql_python.txt |
Q:
Installing Lunatic Python on MacOS System
I am currently trying to get the lunatic python package running on my mac operating system. My problem is, there are several errors occurring while running LunPy's makefile.
Can somebody tell me how to properly set up the Lunatic Python package?
Thanks in advance!
luna... | Installing Lunatic Python on MacOS System | I am currently trying to get the lunatic python package running on my mac operating system. My problem is, there are several errors occurring while running LunPy's makefile.
Can somebody tell me how to properly set up the Lunatic Python package?
Thanks in advance!
lunatic-python-1.0 $ make
python setup.py build
run... | [
"You are probably using the Apple-supplied Python 2.6 on Mac OS X 10.6 (Snow Leopard) and you've also installed the new Xcode 4. You need to set the ARCHFLAGS environment variable as explained in this answer.\n"
] | [
0
] | [] | [] | [
"lua",
"python"
] | stackoverflow_0007017587_lua_python.txt |
Q:
Django Form Errors not showing
I have a form validator and when it fails, the error message doesn't show. Any idea what I'm missing?
views.py:
def setup_onesheet(request):
# if the form has been submitted
if request.method == 'POST':
if 'unverified_username' in request.POST:
form = Ones... | Django Form Errors not showing | I have a form validator and when it fails, the error message doesn't show. Any idea what I'm missing?
views.py:
def setup_onesheet(request):
# if the form has been submitted
if request.method == 'POST':
if 'unverified_username' in request.POST:
form = OnesheetURL(request.POST)
if... | [
"Try:\ndef setup_onesheet(request):\n # if the form has been submitted\n if request.method == 'POST':\n if 'unverified_username' in request.POST:\n form = OnesheetURL(request.POST)\n if form.is_valid():\n ...\n else:\n form = OnesheetURL()\n\n variables... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007017792_django_python.txt |
Q:
Getting contents of title tags with Python script
I want to make a really script in Python that gets the contents from the title tags of a specified web page and then puts them into a MySQL database.
I have very (and I mean very) little experience with Python but this needs to be done for my project. How can I do ... | Getting contents of title tags with Python script | I want to make a really script in Python that gets the contents from the title tags of a specified web page and then puts them into a MySQL database.
I have very (and I mean very) little experience with Python but this needs to be done for my project. How can I do this in the simplest way possible?
I hope you are able ... | [
"\nStudy urllib2 to see how to download the webpage.\nStudy BeautifulSoup to parse the HTML and pull out the title.\nStudy the Python Database API Specification to insert rows into\nthe MySQL database.\n\n\nHere is some example code to get you started:\nimport urllib2\nimport BeautifulSoup\nimport MySQLdb\n\nf = ur... | [
5,
1
] | [] | [] | [
"html",
"mysql",
"python",
"sql"
] | stackoverflow_0007017890_html_mysql_python_sql.txt |
Q:
wxPython continiuouly update panel
I am new in wxPython and can't solve one problem. I need to continuously update panel with clock value. I have a solution, but in this case I can't normally close window (alt+f4 not works).
Also I do not unsderstand what is the difference between .Update .Refresh and when .Destro... | wxPython continiuouly update panel | I am new in wxPython and can't solve one problem. I need to continuously update panel with clock value. I have a solution, but in this case I can't normally close window (alt+f4 not works).
Also I do not unsderstand what is the difference between .Update .Refresh and when .Destroy should be called?
Can some one reccome... | [
"If you need the clock updated every so often, why not use the AnalogClock, LEDNumberCtrl or maybe the TimeCtrl that's updated with a wx.Timer? The following tutorial will help you with the timer part: http://www.blog.pythonlibrary.org/2009/08/25/wxpython-using-wx-timers/\nThe first two widgets update themselves. Y... | [
2
] | [] | [] | [
"python",
"user_interface",
"wxpython"
] | stackoverflow_0007016595_python_user_interface_wxpython.txt |
Q:
Running quick if statements in Django template language
I'm using this code:
<div class="stream {% if streams.online %}online{% else %}offline{% endif %}">
It seems a little redundant. I'd love to run this code
<div class="stream {{ 'online' if stream.online else 'offline' }}">
But sadly that doesn't work. Is th... | Running quick if statements in Django template language | I'm using this code:
<div class="stream {% if streams.online %}online{% else %}offline{% endif %}">
It seems a little redundant. I'd love to run this code
<div class="stream {{ 'online' if stream.online else 'offline' }}">
But sadly that doesn't work. Is there a shorter and less messy way of doing what I want?
| [
"Can't you use the yesno built-in template filter?\nAs in,\n<div class=\"stream {{ stream.online|yesno:\"online,offline\" }}\">\n\n"
] | [
51
] | [] | [] | [
"django",
"django_templates",
"if_statement",
"python"
] | stackoverflow_0007018005_django_django_templates_if_statement_python.txt |
Q:
install pydev without rights to eclipse installation
My apologies if this has already been asked and answered. I don't know enough about eclipse & pydev setup to know what to search for.
I'd like to use pydev, but can't modify the existing installation of eclipse. Do I need to install my own eclipse so that I ca... | install pydev without rights to eclipse installation | My apologies if this has already been asked and answered. I don't know enough about eclipse & pydev setup to know what to search for.
I'd like to use pydev, but can't modify the existing installation of eclipse. Do I need to install my own eclipse so that I can then install pydev into it, or is there a way to install... | [
"The best solution I found was multiple installations: eclipse is not that big (~250mb I think), but it's quite slow, so you'll want to have as little plugins as possible.\n",
"Something that worked quite nicely for me when I was using Pydev with Eclipse as a non-privileged user on a shared computer was to instal... | [
0,
0
] | [] | [] | [
"eclipse",
"pydev",
"python"
] | stackoverflow_0007018089_eclipse_pydev_python.txt |
Q:
Python NameError troubles
I have some programming experience, but I'm very new to python and I'm trying to figure out how to use and import classes from .py files other than the main. I'm currently using netbeans, running CPython 3.2.1.
With my setup right now, all my .py files are in the same folder. Ignoring wh... | Python NameError troubles | I have some programming experience, but I'm very new to python and I'm trying to figure out how to use and import classes from .py files other than the main. I'm currently using netbeans, running CPython 3.2.1.
With my setup right now, all my .py files are in the same folder. Ignoring what the content actually is, it ... | [
"Your problem is caused by a circular import. Python is less flexible than some other languages in this regard, because of the sequential way in which things are defined. In your case, pythonprogram requires classB from otherfile before method1 can be defined. But otherfile requires method1 before classB can be def... | [
2,
0,
0
] | [] | [] | [
"cpython",
"nameerror",
"python"
] | stackoverflow_0007018272_cpython_nameerror_python.txt |
Q:
Using regex to extract information from a string
This is a follow-up and complication to this question: Extracting contents of a string within parentheses.
In that question I had the following string --
"Will Farrell (Nick Hasley), Rebecca Hall (Samantha)"
And I wanted to get a list of tuples in the form of (acto... | Using regex to extract information from a string | This is a follow-up and complication to this question: Extracting contents of a string within parentheses.
In that question I had the following string --
"Will Farrell (Nick Hasley), Rebecca Hall (Samantha)"
And I wanted to get a list of tuples in the form of (actor, character) --
[('Will Farrell', 'Nick Hasley'), ('R... | [
"import re\ncredits = \"\"\"Will Ferrell (Nick Halsey), Rebecca Hall (Samantha), Glenn Howerton (Gary, Brad), with\n Stephen Root and Laura Dern (Delilah, Stacy)\"\"\"\n\n# split on commas (only if outside of parentheses), \"with\" or \"and\"\nsplitre = re.compile(r\"\\s*(?:,(?![^()]*\\))|\\bwith\\b|\\band\\b)\\s*\... | [
4,
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007010672_python_regex.txt |
Q:
Python/django root logger level
In my django project I have following LOGGING config:
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'verbose': {
'format': '%(name)s %(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
},
... | Python/django root logger level | In my django project I have following LOGGING config:
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'verbose': {
'format': '%(name)s %(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
},
'simple': {
'format':... | [
"The South developers shouldn't really be setting its top level logger level to DEBUG. In fact if they don't set it at all, it would inherit the root logger's level, which is normally defined by the application developer (which I guess is you, in this case).\nI would suggest you report this as a bug on the relevant... | [
12
] | [] | [] | [
"django",
"logging",
"python"
] | stackoverflow_0006985251_django_logging_python.txt |
Q:
Python Form Processing Problem
I am a newbie. I wanted to know how to handle array based fields in CGI?
<form name="frmLogin" method="get" action="">
Username: <input type="text" name="login[username]" /><br/>
Password: <input type="password" name="login[password]" /><br/>
<input type="submit" name="login[submit]"... | Python Form Processing Problem | I am a newbie. I wanted to know how to handle array based fields in CGI?
<form name="frmLogin" method="get" action="">
Username: <input type="text" name="login[username]" /><br/>
Password: <input type="password" name="login[password]" /><br/>
<input type="submit" name="login[submit]" />
</form>
I have a form like abov... | [
"I don't think the cgi.FieldStorage has a similar method as the one you describe in php. However, you could write something like this to accomplish the same thing, given the name[attr] format you have on your field names:\ndef get(form, prefix):\n output = {}\n def parse(key):\n name = key.split('[')[1... | [
0
] | [] | [] | [
"cgi",
"python"
] | stackoverflow_0007017953_cgi_python.txt |
Q:
python string slicing with a list
Here is my list:
liPos = [(2,5),(8,9),(18,22)]
The first item of each tuple is the starting position and the second is the ending position.
Then I have a string like this:
s = "I hope that I will find an answer to my question!"
Now, considering my liPos list, I want to format th... | python string slicing with a list | Here is my list:
liPos = [(2,5),(8,9),(18,22)]
The first item of each tuple is the starting position and the second is the ending position.
Then I have a string like this:
s = "I hope that I will find an answer to my question!"
Now, considering my liPos list, I want to format the string by removing the chars between ... | [
"This assumes that liPos is already sorted, if it is not used sorted(liPos, reverse=True) in the for loop.\nliPos = [(2,5),(8,9),(18,22)]\ns = \"I hope that I will find an answer to my question!\"\nfor begin, end in reversed(liPos):\n s = s[:begin] + s[end+1:]\n\nprint s\n\nHere is an alternative method that con... | [
5,
3,
3,
2
] | [] | [] | [
"list",
"python",
"slice",
"string"
] | stackoverflow_0007018812_list_python_slice_string.txt |
Q:
python - connecting to a database with pyodbc - not working
I am trying to connect to an Access 2007 database with the following connection string.
conn = pyodbc.connect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=<C:\Users\JSeinfeld\Desktop\Backup databases\Database_6.7.accdb>;")
I get this error:
Tr... | python - connecting to a database with pyodbc - not working | I am trying to connect to an Access 2007 database with the following connection string.
conn = pyodbc.connect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=<C:\Users\JSeinfeld\Desktop\Backup databases\Database_6.7.accdb>;")
I get this error:
Traceback (most recent call last):
File "", line 1, in
c... | [
"Had the same issue - it was a simple case of escaping the backslash used in the location of the access db\n>>> conn = pyodbc.connect(\"Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\\\access\\\\site_be.accdb;\")\n\nworked as whereas \n>>> conn = pyodbc.connect(\"Driver={Microsoft Access Driver (*.mdb, *... | [
3,
2,
0,
0
] | [] | [] | [
"database",
"pyodbc",
"python"
] | stackoverflow_0006469545_database_pyodbc_python.txt |
Q:
Is it possible to use Python with Go
Possible Duplicate:
Mixing python with a faster language for optimization in GAE
I wounder if you can use python with Go, I have just introduced myself to Go (by mistake lol, although that it exists long time ago) to Go, it feels like python, I like it, but I'm not planning t... | Is it possible to use Python with Go |
Possible Duplicate:
Mixing python with a faster language for optimization in GAE
I wounder if you can use python with Go, I have just introduced myself to Go (by mistake lol, although that it exists long time ago) to Go, it feels like python, I like it, but I'm not planning to learn it because python satisfies me, I... | [
"You can use different languages in the same app -- however, each one in a different version. They will have access to the same datastore and memcache, however CRON and (I think) tasks will only work for the active version (because they target the main version url using a relative path). You would have to \"talk\" ... | [
5
] | [] | [] | [
"go",
"google_app_engine",
"python"
] | stackoverflow_0007018898_go_google_app_engine_python.txt |
Q:
"Hashtable" for Python Twitter Crawler
As part of the python twitter crawler I'm creating, I am attempting to make a "hash-table" of sorts to ensure that I don't crawl any user more than once. It is below. However, I am running into some problems. When I start crawling at the user NYTimesKrugman, I seem to crawl s... | "Hashtable" for Python Twitter Crawler | As part of the python twitter crawler I'm creating, I am attempting to make a "hash-table" of sorts to ensure that I don't crawl any user more than once. It is below. However, I am running into some problems. When I start crawling at the user NYTimesKrugman, I seem to crawl some users more than once. When I start crawl... | [
"The code sample you've given just plain doesn't work for starters, but I would guess your problem has something to do with not even making a hashtable (dictionary? set?).\nYou call L = len(L) when I cannot see anywhere else that L is defined. You then have a loop,\nfor x in (0, L):\n a = L[x]\n if a != ... | [
3,
3,
1
] | [] | [] | [
"python",
"twitter",
"web_crawler"
] | stackoverflow_0007018972_python_twitter_web_crawler.txt |
Q:
lxml iterparse in python can't handle namespaces
from lxml import etree
import StringIO
data= StringIO.StringIO('<root xmlns="http://some.random.schema"><a>One</a><a>Two</a><a>Three</a></root>')
docs = etree.iterparse(data,tag='a')
a,b = docs.next()
Traceback (most recent call last):
File "<stdin>", line 1, in... | lxml iterparse in python can't handle namespaces | from lxml import etree
import StringIO
data= StringIO.StringIO('<root xmlns="http://some.random.schema"><a>One</a><a>Two</a><a>Three</a></root>')
docs = etree.iterparse(data,tag='a')
a,b = docs.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "iterparse.pxi", line 478, in lxml.e... | [
"When there is a namespace attached, the tag isn't a, it's {http://some.random.schema}a. Try this (Python 3):\nfrom lxml import etree\nfrom io import BytesIO\n\nxml = '''\\\n<root xmlns=\"http://some.random.schema\">\n <a>One</a>\n <a>Two</a>\n <a>Three</a>\n</root>'''\ndata = BytesIO(xml.encode())\ndocs = etre... | [
12
] | [
"Why not with a regular expression ?\n1)\nUsing lxml is slower than using a regex.\nfrom time import clock\nimport StringIO\n\n\n\nfrom lxml import etree\n\ntimes1 = []\nfor i in xrange(1000):\n data= StringIO.StringIO('<root ><a>One</a><a>Two</a><a>Three\\nlittle pigs</a><b>Four</b><a>another</a></root>')\n ... | [
-3
] | [
"iterparse",
"lxml",
"python"
] | stackoverflow_0007018326_iterparse_lxml_python.txt |
Q:
pythons 'print' statement doesn't call the .write() method?
I thought the print statement just called the .write() method on the sys.stdout (by default) object.
but having written a subclass like this:
import time
class logfile(file):
def __init__(self, *args, **kwargs):
file.__init__(self, *args, **k... | pythons 'print' statement doesn't call the .write() method? | I thought the print statement just called the .write() method on the sys.stdout (by default) object.
but having written a subclass like this:
import time
class logfile(file):
def __init__(self, *args, **kwargs):
file.__init__(self, *args, **kwargs)
def write(self, logstr):
if logstr[-1] != '\n... | [
"Apparently this is an limitation of the implementation of Python 2 where print is a statement rather than an expression with side-effects (as it is in Python 3).\nI rewrote the code to something that works in Python 3:\nfrom io import FileIO\nimport time\n\nclass logfile(FileIO):\n def __init__(self, *args, **kwa... | [
4,
2,
1
] | [] | [] | [
"file",
"inheritance",
"oop",
"printing",
"python"
] | stackoverflow_0007017778_file_inheritance_oop_printing_python.txt |
Q:
Bypass exception to always execute command?
The following code works almost perfect, thanks to the help received here:
import urllib.request
import zipfile
import subprocess
urls = ["http://url.com/archive1.zip", "http://url.com/archive2.zip", "http://url.com/archive3.zip"]
filename = "C:/test/test.zip"
destinati... | Bypass exception to always execute command? | The following code works almost perfect, thanks to the help received here:
import urllib.request
import zipfile
import subprocess
urls = ["http://url.com/archive1.zip", "http://url.com/archive2.zip", "http://url.com/archive3.zip"]
filename = "C:/test/test.zip"
destinationPath = "C:/test"
for url in urls:
try:
... | [
"Set sourceZip = None prior to the for url in urls line. Then test if sourceZip is None after the for loop to determine if you were able to successfully fetch the file. For example:\nsourceZip = None\n\nfor url in urls:\n try:\n urllib.request.urlretrieve(url,filename)\n sourceZip = zipfile.ZipFi... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0007019615_python.txt |
Q:
Python: for loop between if-else, how/why does this work?
I'm currently going through the Lynda Python tutorial and in the section on generators I see the following code:
def isprime(n):
if n == 1:
return False
for x in range(2, n):
if n % x == 0:
return False
else:
... | Python: for loop between if-else, how/why does this work? | I'm currently going through the Lynda Python tutorial and in the section on generators I see the following code:
def isprime(n):
if n == 1:
return False
for x in range(2, n):
if n % x == 0:
return False
else:
return True
I didn't catch it at first, but as I was going thr... | [
"An else: block after a for: block only runs if the loop completed normally. If you break out of the loop, it won't run. In this case, this makes no difference because you never break out of the loop; you return before it ends or you let it complete normally.\n",
"The reason for this behavior is that in python fo... | [
8,
2
] | [] | [] | [
"conditional",
"if_statement",
"python"
] | stackoverflow_0007019794_conditional_if_statement_python.txt |
Q:
get_serving_url via remote_api_shell.py
I want to record all the current urls for images I'm storing using appengine. However, when using appengine's remote_api_shell.py console, I'm unable to use the get_serving_url function even though I have PIL set up correctly on my local machine.
>>> c.image_blob
<google.app... | get_serving_url via remote_api_shell.py | I want to record all the current urls for images I'm storing using appengine. However, when using appengine's remote_api_shell.py console, I'm unable to use the get_serving_url function even though I have PIL set up correctly on my local machine.
>>> c.image_blob
<google.appengine.ext.blobstore.blobstore.BlobInfo objec... | [
"remote_api doesn't currently have a mapping for the get_serving_url API call. You can add it yourself by importing remote_api_services and adding it to the dict in the appropriate place, but either way you should definitely file a feature request.\n"
] | [
2
] | [] | [] | [
"console",
"google_app_engine",
"python"
] | stackoverflow_0007017972_console_google_app_engine_python.txt |
Q:
python using ctypes to work with dll - structure OUT argument
In the header file of the dll I have the following structure
typedef struct USMC_Devices_st{
DWORD NOD; // Number of the devices ready to work
char **Serial; // Array of 16 byte ASCII strings
char **Version; // Array of 4 byte ASCII s... | python using ctypes to work with dll - structure OUT argument | In the header file of the dll I have the following structure
typedef struct USMC_Devices_st{
DWORD NOD; // Number of the devices ready to work
char **Serial; // Array of 16 byte ASCII strings
char **Version; // Array of 4 byte ASCII strings
} USMC_Devices; // Structure representing connected ... | [
"Use POINTER(c_char_p) for the char ** pointers. Indexing Serial or Version creates a Python string for the given null-terminated string. Note that indexing in the array beyond NOD - 1 either produces garbage values or will crash the interpreter.\nC:\n#include <windows.h>\n\ntypedef struct USMC_Devices_st {\n DW... | [
2
] | [] | [] | [
"ctypes",
"dll",
"python"
] | stackoverflow_0007017107_ctypes_dll_python.txt |
Q:
Should I do Material Clasification/ Recognition using histograms or some other higher Math tool, like Bayesian Networks?
I'm learning the basics of OpenCV, and I thought a good project would help me make the studying more fun. After thinking some ideas I came up with some material recognition project. Let's say, I... | Should I do Material Clasification/ Recognition using histograms or some other higher Math tool, like Bayesian Networks? | I'm learning the basics of OpenCV, and I thought a good project would help me make the studying more fun. After thinking some ideas I came up with some material recognition project. Let's say, I got myself a conveyor and it's transporting material for production of some product ( this product don't really matter, tho).... | [
"Quite an advanced idea for a starting project. The differences in lighting could be tackled by using the HSV or other color spaces, taking the Hue component. However the matter of \"texture\" can be handled in two ways:\n\nFeature descriptors: If you deal with the grey level image, there are a set of feature desc... | [
5
] | [] | [] | [
"bayesian_networks",
"object_recognition",
"opencv",
"python"
] | stackoverflow_0007016623_bayesian_networks_object_recognition_opencv_python.txt |
Q:
Which is the easiest Python web application framework to get started with, for general use?
Which is the easiest Python web application framework to get started with, for general use?
Referring to easiest - I mean one which a short learning curve / time, at least in order to be able to use it for fairly simple app... | Which is the easiest Python web application framework to get started with, for general use? | Which is the easiest Python web application framework to get started with, for general use?
Referring to easiest - I mean one which a short learning curve / time, at least in order to be able to use it for fairly simple apps. I have worked on non-trivial Ruby on Rails projects earlier, so it is not that I can't learn a... | [
"I think you'll find web2py to be one of the easiest to set up, learn, and use (those are among its primary goals). It makes it easy to do simple things (and even many complex things), but still has a great deal of power and flexibility. It was inspired by Rails, so your familiarity with Rails may make it even easi... | [
8,
5,
3,
3,
0
] | [] | [] | [
"python",
"web_frameworks"
] | stackoverflow_0007016885_python_web_frameworks.txt |
Q:
passing in self data in python
Can you please clarify how it is that self.add(x) below works the same way as self.data.append(x)?
That is, how does self.add(x) know to append to the list because we have not explicitly stated self.data.add(x)? When we state y.addtwice('cat'), 'cat' is added to 'self', not self.dat... | passing in self data in python | Can you please clarify how it is that self.add(x) below works the same way as self.data.append(x)?
That is, how does self.add(x) know to append to the list because we have not explicitly stated self.data.add(x)? When we state y.addtwice('cat'), 'cat' is added to 'self', not self.data.
class Bag:
def __init__(self)... | [
"Because addtwice calls methods which are defined on self, and because self.data is a \"mutable type\", addtwice's call to add will end up appending the value of self.data. add, in turn calls self.data.append\nWhen calling a function in a computer program, you can think of the process as being a series of substitut... | [
4,
1,
1,
1,
1
] | [] | [] | [
"instance_methods",
"python"
] | stackoverflow_0007020261_instance_methods_python.txt |
Q:
Unable to get URL-based context in django-template-repl
I'm trying out django-template-repl for debugging a template issue and it's pretty awesome.
One of the features of the tool is that you can go:
python manage.py templateshell -u /admin/
and pull up the context for that url location.
Unfortunately no matter ... | Unable to get URL-based context in django-template-repl | I'm trying out django-template-repl for debugging a template issue and it's pretty awesome.
One of the features of the tool is that you can go:
python manage.py templateshell -u /admin/
and pull up the context for that url location.
Unfortunately no matter what configuration of /admin/ or other urls in my site I try ... | [
"Finally got around to trying the solution codysoyland put up in the comments section. Sure enough, you need to have ipdb installed for this functionality to work. Now it works great.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006763489_django_python.txt |
Q:
Searching for python modules containing non-ASCII characters
I have a Python project containing hundreds of modules. In Python 2.6, the encoding of source files (modules) must be ASCII unless
an explicit encoding declaration is present. Is there a simple way to find out which python modules contain non-ASCII chara... | Searching for python modules containing non-ASCII characters | I have a Python project containing hundreds of modules. In Python 2.6, the encoding of source files (modules) must be ASCII unless
an explicit encoding declaration is present. Is there a simple way to find out which python modules contain non-ASCII characters? So that I can correct them.
Regards,
| [
"Have a look at the chardet python package. You can use the same os.walk approach as agf and call the chardet.detect method and flag files that are not ASCII (or with a lower confidence value).\nThis does leave some room for error though, so if you wanted to be more sure, you could also scan each file for character... | [
3,
1,
1
] | [] | [] | [
"ascii",
"character_encoding",
"module",
"python",
"search"
] | stackoverflow_0007020137_ascii_character_encoding_module_python_search.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.