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:
storing 'object'
Does PyTables support storing Python objects?
something like this :
dtype = np.dtype([('Name', '|S2'), ('objValue', object)])
data = np.zeros(3, dtype)
file.createArray(box3,'complicated',data)
I get error when trying to do this of course...
How to properly store arrays of objects?Is it possible?... | storing 'object' | Does PyTables support storing Python objects?
something like this :
dtype = np.dtype([('Name', '|S2'), ('objValue', object)])
data = np.zeros(3, dtype)
file.createArray(box3,'complicated',data)
I get error when trying to do this of course...
How to properly store arrays of objects?Is it possible?
Thanks
| [
"You can save generic Python object with Pytables:\n>>> dtype = np.dtype([('Name', '|S2'), ('objValue', object)])\n>>> data = np.zeros(3, dtype)\n>>> file = tables.openFile('/tmp/test.h5', 'w')\n>>> myobjects = file.createVLArray(file.root, 'myobjects', tables.ObjectAtom())\n>>> myobjects.append(data)\n>>> myobject... | [
5,
1
] | [] | [] | [
"pytables",
"python"
] | stackoverflow_0004104812_pytables_python.txt |
Q:
what is the right regex for this?
what is the regex for such a task? -->
replace "[[...:" with "[["
That is to say, I want to replace *some text * inside [[...: with [[.
The problem with my code is that it remove *text * inside the first [[ ]]
>>> string = "Some text here [[dont remove me]] and some extra text [[... | what is the right regex for this? | what is the regex for such a task? -->
replace "[[...:" with "[["
That is to say, I want to replace *some text * inside [[...: with [[.
The problem with my code is that it remove *text * inside the first [[ ]]
>>> string = "Some text here [[dont remove me]] and some extra text [[remove me:and let this]] here."
>>> cle... | [
"re.sub(r'\\[\\[[^:\\]]+:', '[[', string)\n\n[^:\\]] is used instead of . to constrain that the stuff to remove is limited within a tag.\n",
"Instead of . use an expression that excludes : and the closing ]]:\nr'\\[\\[(?:[^:\\]]|\\][^\\]])*:'\n\n"
] | [
1,
0
] | [] | [] | [
"python",
"regex",
"replace"
] | stackoverflow_0004148039_python_regex_replace.txt |
Q:
SQL zero instead of null
This function:
for i in Selection:
cursor.execute(Query)
ydata[i] = [int(x[0]) for x in cursor.fetchall()]
raises:
ValueError: invalid literal for int(): NULL if a null value is found.
How can I make my query return zeros instead of nulls so that I can fix this? (I am plotting ... | SQL zero instead of null | This function:
for i in Selection:
cursor.execute(Query)
ydata[i] = [int(x[0]) for x in cursor.fetchall()]
raises:
ValueError: invalid literal for int(): NULL if a null value is found.
How can I make my query return zeros instead of nulls so that I can fix this? (I am plotting the data, so I cannot add "is ... | [
"You can fix this before it gets to Python with a case statement in your query:\nCASE WHEN FIELD_NAME IS NULL THEN 0 ELSE FIELD_NAME END,\n\nbegin edit\nOther SQL variants do it differently (taken from other answers):\nCOALESCE(FIELD_NAME, 0)\n\nor\nIFNULL(FIELD_NAME, 0)\n\nend edit\nOr handle it in your list comp ... | [
6,
2,
2,
2
] | [] | [] | [
"null",
"python",
"sql",
"sqlite",
"zero"
] | stackoverflow_0004148205_null_python_sql_sqlite_zero.txt |
Q:
'meta' extension for Markdown not loading in Python2.6?
I'm trying to get the meta extension working with markdown in Python 2.6.
The code looks like this:
import markdown as m
print "Markdown version: ", m.version
file = "file.md"
md = m.Markdown( extensions = ['meta']) # doesn't complain
print "Registered exten... | 'meta' extension for Markdown not loading in Python2.6? | I'm trying to get the meta extension working with markdown in Python 2.6.
The code looks like this:
import markdown as m
print "Markdown version: ", m.version
file = "file.md"
md = m.Markdown( extensions = ['meta']) # doesn't complain
print "Registered extensions: ", md.registeredExtensions
text = open(file)
try:
... | [
"convert() expects text. Replace md.convert(file) by md.convert(open(file).read()).\nimport markdown as m\n\nprint \"Markdown version: \", m.version\nfile = \"file.md\"\nmd = m.Markdown(extensions=['meta']) # doesn't complain\n\nprint \"Registered extensions: \", md.registeredExtensions\nprint \"Preprocessors:\", m... | [
2
] | [] | [] | [
"markdown",
"meta",
"python"
] | stackoverflow_0004148036_markdown_meta_python.txt |
Q:
Python: map in place
I was wondering if there is a way to run map on something. The way map works is it takes an iterable and applies a function to each item in that iterable producing a list. Is there a way to have map modify the iterable object itself?
A:
A slice assignment is often ok if you need to modify a ... | Python: map in place | I was wondering if there is a way to run map on something. The way map works is it takes an iterable and applies a function to each item in that iterable producing a list. Is there a way to have map modify the iterable object itself?
| [
"A slice assignment is often ok if you need to modify a list in place\nmylist[:] = map(func, mylist)\n\n",
"It's simple enough to write:\ndef inmap(f, x):\n for i, v in enumerate(x):\n x[i] = f(v)\n\na = range(10)\ninmap(lambda x: x**2, a)\nprint a\n\n",
"You can use a lambda (or a def) or better ... | [
13,
4,
1,
1
] | [] | [] | [
"iterable",
"map_function",
"python"
] | stackoverflow_0003000461_iterable_map_function_python.txt |
Q:
Django relative urls and https
I have a Django project using https for certain part of the url (/account/, /admin/, /purchase/).
When on one of this page in https mode, all the relative inner links {% url foo %} will point to https://my_url.
However I do not want to have those pages shown as https :home, contact... | Django relative urls and https | I have a Django project using https for certain part of the url (/account/, /admin/, /purchase/).
When on one of this page in https mode, all the relative inner links {% url foo %} will point to https://my_url.
However I do not want to have those pages shown as https :home, contacts ...
What are the solutions for thi... | [
"Idea: you can use a custom middleware to redirect from https to http (or vice versa) for centrain URLs or URL patterns. This could also be done in Apache (or other web server) configuration.\n",
"As Tomasz suggests, one way to do it is to set up middleware to redirect to and from https as necessary. Here's one i... | [
4,
4,
2,
2,
2
] | [] | [] | [
"django",
"https",
"python",
"ssl"
] | stackoverflow_0004148009_django_https_python_ssl.txt |
Q:
Patterns in Binary Fractions with Python
Researching pattern identification requires to identify the repeating patterns in binary representations of fractions of rational numbers. bin(2**24/n) strips the leading zeros, e.g. bin(2**24/11) -> 0b101110100010111010001 instead of 0b000101110100010111010001. The number... | Patterns in Binary Fractions with Python | Researching pattern identification requires to identify the repeating patterns in binary representations of fractions of rational numbers. bin(2**24/n) strips the leading zeros, e.g. bin(2**24/11) -> 0b101110100010111010001 instead of 0b000101110100010111010001. The number of leading zeros is variable of course. The o... | [
"This can be done with string formatting, in 2.6+:\n>>> '{0:024b}'.format(23)\n'000000000000000000010111'\n\n",
"You might find the bitstring module useful if you have more advanced needs than string formatting can provide. \n>>> from bitstring import BitArray\n>>> a = BitArray(24) # 24 zero bits\n>>> a.... | [
4,
2
] | [] | [] | [
"binary",
"numbers",
"python"
] | stackoverflow_0004148132_binary_numbers_python.txt |
Q:
Overwriting a specific row in a csv file using Python's CSV module
I'm using Python's csv module to do some reading and writing of csv files.
I've got the reading fine and appending to the csv fine, but I want to be able to overwrite a specific row in the csv.
For reference, here's my reading and then writing co... | Overwriting a specific row in a csv file using Python's CSV module | I'm using Python's csv module to do some reading and writing of csv files.
I've got the reading fine and appending to the csv fine, but I want to be able to overwrite a specific row in the csv.
For reference, here's my reading and then writing code to append:
#reading
b = open("bottles.csv", "rb")
bottles... | [
"I will add to Steven Answer :\nimport csv\n\nbottle_list = []\n\n# Read all data from the csv file.\nwith open('a.csv', 'rb') as b:\n bottles = csv.reader(b)\n bottle_list.extend(bottles)\n\n# data to override in the format {line_num_to_override:data_to_write}. \nline_to_override = {1:['e', 'c', 'd'] }\n\n# ... | [
18,
4
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0004148772_csv_python.txt |
Q:
Use of *args and **kwargs
So I have difficulty with the concept of *args and **kwargs.
So far I have learned that:
*args = list of arguments - as positional arguments
**kwargs = dictionary - whose keys become separate keyword arguments and the values become values of these arguments.
I don't understand what prog... | Use of *args and **kwargs | So I have difficulty with the concept of *args and **kwargs.
So far I have learned that:
*args = list of arguments - as positional arguments
**kwargs = dictionary - whose keys become separate keyword arguments and the values become values of these arguments.
I don't understand what programming task this would be help... | [
"The syntax is the * and **. The names *args and **kwargs are only by convention but there's no hard requirement to use them.\nYou would use *args when you're not sure how many arguments might be passed to your function, i.e. it allows you pass an arbitrary number of arguments to your function. For example:\n>>> ... | [
1768,
506,
339,
74,
49,
44,
20,
18,
10,
8,
3
] | [] | [] | [
"args",
"keyword_argument",
"python"
] | stackoverflow_0003394835_args_keyword_argument_python.txt |
Q:
Help with this typerror in a dictionary
benfordd = dict()
for attr in attrs:
benfordd.setdefault(attr, []).extend([val*1e6 for val in x if not np.isnan(val)])
the above is just parts of my code, why is it that when I run this in ipython, I get this:
TypeError: function not supported for these types, and c... | Help with this typerror in a dictionary | benfordd = dict()
for attr in attrs:
benfordd.setdefault(attr, []).extend([val*1e6 for val in x if not np.isnan(val)])
the above is just parts of my code, why is it that when I run this in ipython, I get this:
TypeError: function not supported for these types, and can't coerce safely to supported types.
does a... | [
"I believe this error can occur when using Sage with numpy. The reason is that Sage preparses your input, so that e.g. 0.6**2 is translated to RealNumber('0.6') ** Integer(2). This allows it to handle real numbers with arbitrary precision. Unfortunately, numpy can't handle these, because it doesn't know what a Real... | [
1
] | [] | [] | [
"dictionary",
"python",
"typeerror"
] | stackoverflow_0004149076_dictionary_python_typeerror.txt |
Q:
Python-style pickling for C++?
Does anyone know of a "language level" facility for pickling in C++? I don't want something like Boost serialization, or Google Protocol Buffers. Instead, something that could automatically serialize all the members of a class (with an option to exclude some members, either because... | Python-style pickling for C++? | Does anyone know of a "language level" facility for pickling in C++? I don't want something like Boost serialization, or Google Protocol Buffers. Instead, something that could automatically serialize all the members of a class (with an option to exclude some members, either because they're not serializable, or else b... | [
"I don't believe there's any way to do this in a language with no run-time introspection capabilities.\n",
"\nsomething that could automatically\n serialize all the members of a class\n\nThis is not possible in C++. Python, C#, Java et al. use run-time introspection to achieve this. You can't do that in C++, RTT... | [
4,
2,
1,
1,
0
] | [] | [] | [
"boost",
"c++",
"pickle",
"python",
"serialization"
] | stackoverflow_0004149086_boost_c++_pickle_python_serialization.txt |
Q:
Dynamic images resizing
I'm working on project where we are trying to adopt and resize template images to the various resolutions. For example if the website is viewed in 800px width (800x600) and 1024px width or larger the image size should be viewed in same quality.
I've had in mind to use sprite with 3 types o... | Dynamic images resizing | I'm working on project where we are trying to adopt and resize template images to the various resolutions. For example if the website is viewed in 800px width (800x600) and 1024px width or larger the image size should be viewed in same quality.
I've had in mind to use sprite with 3 types of images for each range of th... | [
"Well, for resizing it would of course be better to use GD... But indexed, I think. So that you have an upload script that automatically generates the images' in other sizes, and saves them somewhere.\nHowever, it matters whether you have more disk space, or performance... Performance would get worse IF you have ma... | [
4,
2,
2,
1,
1
] | [] | [] | [
"javascript",
"jquery",
"php",
"python"
] | stackoverflow_0004149112_javascript_jquery_php_python.txt |
Q:
How can I access any element in a web page with Python?
I would like to access any element in a web page. I know how to do that when I have a form (form = cgi.FieldStorage()), but not when I have, for example, a table.
How can I do that?
Thanks
A:
If you are familiar with javascript, you should be familiar with ... | How can I access any element in a web page with Python? | I would like to access any element in a web page. I know how to do that when I have a form (form = cgi.FieldStorage()), but not when I have, for example, a table.
How can I do that?
Thanks
| [
"If you are familiar with javascript, you should be familiar with the DOM. This should help you to get the information you want, seeing how this parses HTML, among other things. Then it's up to you to extract the information you need\n",
"HTML parsing using either HTMLParser or Beautiful Soup if you're trying to ... | [
1,
0,
0,
0
] | [] | [] | [
"cgi",
"html_parsing",
"python"
] | stackoverflow_0004149598_cgi_html_parsing_python.txt |
Q:
replace some part of a word with regex
how do you delete text inside <ref> *some text*</ref> together with ref itself?
in '...and so on<ref>Oxford University Press</ref>.'
re.sub(r'<ref>.+</ref>', '', string) only removes <ref> if
<ref> is followed by a whitespace
EDIT: it has smth to do with word boundaries I gu... | replace some part of a word with regex | how do you delete text inside <ref> *some text*</ref> together with ref itself?
in '...and so on<ref>Oxford University Press</ref>.'
re.sub(r'<ref>.+</ref>', '', string) only removes <ref> if
<ref> is followed by a whitespace
EDIT: it has smth to do with word boundaries I guess...or?
EDIT2 What I need is that it will ... | [
"I don't really see you problem, because the code pasted will remove the <ref>...</ref> part of the string. But if what you mean is that and empty ref tag is not removed:\nre.sub(r'<ref>.+</ref>', '', '...and so on<ref></ref>.')\n\nThen what you need to do is change the .+ with .*\nA + means one or more, while * me... | [
3,
1,
1,
0
] | [] | [] | [
"python",
"ref",
"replace"
] | stackoverflow_0004149517_python_ref_replace.txt |
Q:
One last step! (python tuning)
I have this code:
emailRows = []
for rowTuple in listOfRows: #row loop
emailLine = []
for tup in rowTuple: #field loop
emailLine.append(str(tup).center(20))
emailRows.append('\t'.join([field.strip().c... | One last step! (python tuning) | I have this code:
emailRows = []
for rowTuple in listOfRows: #row loop
emailLine = []
for tup in rowTuple: #field loop
emailLine.append(str(tup).center(20))
emailRows.append('\t'.join([field.strip().center(20) for field in emailLine]))
... | [
"'\\n'.join(('\\t'.join([field.strip().center(20) for\n field in [str(tup).center(20) for\n tup in rowTuple]])) for rowTuple in listOfRows)\n\nWow, that's obfuscated. I hope cProfile says this guy is a heavy hitter.\n",
"I'm not convinced the result is worth the effort, but if you're going to go down th... | [
1,
1,
1
] | [] | [] | [
"functional_programming",
"join",
"python"
] | stackoverflow_0004149496_functional_programming_join_python.txt |
Q:
Django validate form based on multiple fields (file fields)
Is there a way in django to validate a form based on multiple fields. I have seen some examples where people recommend overriding a form's clean method and raising a ValidationError if it fails to meet your custom validation. The problem for me is that I'... | Django validate form based on multiple fields (file fields) | Is there a way in django to validate a form based on multiple fields. I have seen some examples where people recommend overriding a form's clean method and raising a ValidationError if it fails to meet your custom validation. The problem for me is that I'm not sure you can check whether or not a file was uploaded from ... | [
"The method you've described (raising ValidationError from within Form.clean) is the official way to do multi-field validation.\nYou can access uploaded files from self.files within the clean method. From django/forms/forms.py:\nclass BaseForm(StrAndUnicode):\n # This is the main implementation of all the Form ... | [
3
] | [] | [] | [
"django",
"model_view_controller",
"python"
] | stackoverflow_0004149908_django_model_view_controller_python.txt |
Q:
How to use pythons map with a non-iterable and iterable set of parameters?
To make a simple example, I don't care about the practicality, just the implemenation. Say I create some class with a few methods. I want to create a list containing whether or not they're callable. So I can take this example from:
Findin... | How to use pythons map with a non-iterable and iterable set of parameters? | To make a simple example, I don't care about the practicality, just the implemenation. Say I create some class with a few methods. I want to create a list containing whether or not they're callable. So I can take this example from:
Finding what methods an object has
[method for method in dir(object) if callable(getat... | [
"I will admit to not understanding why, since the LC works, but:\nmap(lambda x: callable(getattr(object, x)), dir(object))\n\n",
"If you're not clear on what the lambda above does, equivalently you could define:\ndef myMap(fun1,obj,iterlist):\n def fun2(x):\n return fun1(obj,x)\n return m... | [
4,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004149783_python.txt |
Q:
Logging hierarchy vs. root logger?
Somewhere in the bowels of my code I have something like:
logger = logging.getLogger('debug0.x')
The way I understand it, this should only respond when I have previously done something like:
logging.basicConfig(filename='10Nov2010a.txt',level=logging.DEBUG, name='debug0')
note ... | Logging hierarchy vs. root logger? | Somewhere in the bowels of my code I have something like:
logger = logging.getLogger('debug0.x')
The way I understand it, this should only respond when I have previously done something like:
logging.basicConfig(filename='10Nov2010a.txt',level=logging.DEBUG, name='debug0')
note that name has been defined as debug0. Ho... | [
"The Python logging module organizes loggers in a hierarchy. All loggers are descendants of the root logger. Each logger passes log messages on to its parent.\nNew loggers are created with the getLogger() function. The function call logging.getLogger('debug0.x') creates a logger x which is a child of debug0 whic... | [
119,
17
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0004150148_logging_python.txt |
Q:
How to get self into a Python method without explicitly accepting it
I'm developing a documentation testing framework -- basically unit tests for PDFs. Tests are (decorated) methods of instances of classes defined by the framework, and these are located and instantiated at runtime and the methods are invoked to ex... | How to get self into a Python method without explicitly accepting it | I'm developing a documentation testing framework -- basically unit tests for PDFs. Tests are (decorated) methods of instances of classes defined by the framework, and these are located and instantiated at runtime and the methods are invoked to execute the tests.
My goal is to cut down on the amount of quirky Python syn... | [
"My accepted answer to this question was pretty dumb but I was just starting out. Here's a much better way. This is only scantily tested but it's good for a demonstration of the proper way to do this thing which is improper to do. It works on 2.6.5 for sure. I haven't tested any other versions but no opcodes are h... | [
6,
5,
4,
3,
2
] | [] | [] | [
"local",
"python",
"self",
"variables"
] | stackoverflow_0003453976_local_python_self_variables.txt |
Q:
multi lines python indentation on emacs
Im an emacs newbie, I want emacs to be able to indent my code like this
egg = spam.foooooo('vivivivivivivivivi')\
.foooooo('emacs', 'emacs', 'emacs', 'emacs')
It's not possible to do this automatically by default (without manually inserting spaces or C-c >), since... | multi lines python indentation on emacs | Im an emacs newbie, I want emacs to be able to indent my code like this
egg = spam.foooooo('vivivivivivivivivi')\
.foooooo('emacs', 'emacs', 'emacs', 'emacs')
It's not possible to do this automatically by default (without manually inserting spaces or C-c >), since emacs always indents 4 spaces (unless Im spl... | [
"I agree with Aaron about the desirability of your stylistic choice, but since I also agree with him that Emacs Lisp is fun, I'll describe how you might go about implementing this.\nEmacs python-mode computes the indentation of a line in the function python-calculate-indentation and the relevant section for handlin... | [
25,
3
] | [] | [] | [
"elisp",
"emacs",
"indentation",
"python"
] | stackoverflow_0004057988_elisp_emacs_indentation_python.txt |
Q:
Python: Nesting counters
For my customers, iterating through multiple counters is turning into a recurring task.
The most straightforward way would be something like this:
cntr1 = range(0,2)
cntr2 = range(0,5)
cntr3 = range(0,7)
for li in cntr1:
for lj in cntr2:
for lk in cntr3:
print li, ... | Python: Nesting counters | For my customers, iterating through multiple counters is turning into a recurring task.
The most straightforward way would be something like this:
cntr1 = range(0,2)
cntr2 = range(0,5)
cntr3 = range(0,7)
for li in cntr1:
for lj in cntr2:
for lk in cntr3:
print li, lj, lk
The number of counters... | [
"What you want is itertools.product\nfor li, lj, lk in itertools.product(cntr1, cntr2, cntr3):\n print li, lj, lk\n\nWill do exactly what you are requesting. The name derives from the concept of a Cartesian product. \n"
] | [
7
] | [] | [] | [
"iteration",
"python"
] | stackoverflow_0004150467_iteration_python.txt |
Q:
Determine Index of Highest Value in Python's NumPy
I want to generate an array with the index of the highest max value of each row.
a = np.array([ [1,2,3], [6,5,4], [0,1,0] ])
maxIndexArray = getMaxIndexOnEachRow(a)
print maxIndexArray
[[2], [0], [1]]
There's a np.argmax function but it doesn't appear to do wh... | Determine Index of Highest Value in Python's NumPy | I want to generate an array with the index of the highest max value of each row.
a = np.array([ [1,2,3], [6,5,4], [0,1,0] ])
maxIndexArray = getMaxIndexOnEachRow(a)
print maxIndexArray
[[2], [0], [1]]
There's a np.argmax function but it doesn't appear to do what I want...
| [
"The argmax() function does do what you want:\nprint a.argmax(axis=1)\narray([2, 0, 1])\n\n"
] | [
20
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0004150542_numpy_python.txt |
Q:
cherrypy and relative path in WSGI app
running cherrypy with mod_wsgi on apache along with another php app. The cherrypy app is NOT mounted on root, but rather on something like 'localhost/apps/myapp' via WSGIScriptAlias in the apache config file.
In testapp.py, I have tried the following, and when I try to access... | cherrypy and relative path in WSGI app | running cherrypy with mod_wsgi on apache along with another php app. The cherrypy app is NOT mounted on root, but rather on something like 'localhost/apps/myapp' via WSGIScriptAlias in the apache config file.
In testapp.py, I have tried the following, and when I try to access localhost/apps/myapp in a browser:
app = ch... | [
"I am doing this, although this would require cherrypy to know the relative path:\nclass Dir: pass\nroot = Dir()\nroot.apps = Dir()\nroot.apps.myapp = MyApp()\ncherrypy.tree.mount(root)\n\nThis allows me to structure the application in any way I need. I'm using nginx and not Apache, but I don't think it'll make any... | [
1,
0
] | [] | [] | [
"cherrypy",
"python"
] | stackoverflow_0004129929_cherrypy_python.txt |
Q:
Django: Obtaining the absolute URL without access to a request object
I have a model like the one below. When an instance is created, I want to send out an e-mail to an interested party:
class TrainStop(models.Model):
name = models.CharField(max_length=32)
notify_email = models.EmailField(null=True, blank=... | Django: Obtaining the absolute URL without access to a request object | I have a model like the one below. When an instance is created, I want to send out an e-mail to an interested party:
class TrainStop(models.Model):
name = models.CharField(max_length=32)
notify_email = models.EmailField(null=True, blank=True)
def new_stop_created(sender, instance, created, *args, **kwargs):
... | [
"There's the sites framework, as yedpodtrzitko mentioned, but, as you mentioned, it's very much a manual setup.\nThere's requiring a setting in settings.py, but it's only slightly less manual than setting up sites. (It can handle multiple domains, just as well as sites and the SITE_ID setting can).\nThere's an ide... | [
5,
4
] | [] | [] | [
"django",
"django_settings",
"django_signals",
"python"
] | stackoverflow_0004150258_django_django_settings_django_signals_python.txt |
Q:
sqlite returning nothing after 2nd cursor.fetchall()
Why do I get nothing when I execute cursor.fetchall() twice after a cursor.execute()? Is there anyway of preventing this from happening? Do I need to store the information on a variable? Is it suppose to work this way?
A:
fetchall does what it says--it fetche... | sqlite returning nothing after 2nd cursor.fetchall() | Why do I get nothing when I execute cursor.fetchall() twice after a cursor.execute()? Is there anyway of preventing this from happening? Do I need to store the information on a variable? Is it suppose to work this way?
| [
"fetchall does what it says--it fetches all. There's nothing left after that. To get more results, you'd need to run another query (or the same query again).\nFrom the python db-api 2.0 specification:\n\ncursor.fetchall() \n\n Fetch all (remaining) rows of a query result, returning\n them as a seque... | [
5
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0004150957_python_sqlite.txt |
Q:
Exception: Failed to start new browser session: Error while launching browser Selenium in Python
I am getting the following errors when running a basic Selenium test script in Python:
======================================================================
ERROR: test_untitled (__main__.TestTesting)
----------------... | Exception: Failed to start new browser session: Error while launching browser Selenium in Python | I am getting the following errors when running a basic Selenium test script in Python:
======================================================================
ERROR: test_untitled (__main__.TestTesting)
----------------------------------------------------------------------
Traceback (most recent call last):
File "Test... | [
"The fix that I got to work was that the display for firefox was not set. So I needed to execute the following statement:\nexport DISPLAY=:0\n\nright before I started the Selenium server. This solve the issue, but a new one has arisen. \n",
"This normally happens when another firefox is already opened. i.e. You a... | [
2,
0,
0
] | [] | [] | [
"python",
"selenium",
"ubuntu"
] | stackoverflow_0003388714_python_selenium_ubuntu.txt |
Q:
Storing tokenized text in the db?
I have a simple question. I'm doing some light crawling so new content arrives every few days. I've written a tokenizer and would like to use it for some text mining purposes. Specifically, I'm using Mallet's topic modeling tool and one of the pipe is to tokenize the text into tok... | Storing tokenized text in the db? | I have a simple question. I'm doing some light crawling so new content arrives every few days. I've written a tokenizer and would like to use it for some text mining purposes. Specifically, I'm using Mallet's topic modeling tool and one of the pipe is to tokenize the text into tokens before further processing can be do... | [
"Caching Intermediate Representations\nIt's pretty normal to cache the intermediate representations created by slower components in your document processing pipeline. For example, if you needed dependency parse trees for all the sentences in each document, it would be pretty crazy to do anything except parsing the ... | [
1,
1
] | [] | [] | [
"caching",
"nlp",
"postgresql",
"python",
"tokenize"
] | stackoverflow_0004122940_caching_nlp_postgresql_python_tokenize.txt |
Q:
(Python) List traversal in a nested for-loop?
I can't figure out what's happening here. I've got a few lists set up, one for each individual color with corresponding RGB values as its member, and then the list, colors[], that contains each individual color list. Then I've got a nested for loop: the outer loop crea... | (Python) List traversal in a nested for-loop? | I can't figure out what's happening here. I've got a few lists set up, one for each individual color with corresponding RGB values as its member, and then the list, colors[], that contains each individual color list. Then I've got a nested for loop: the outer loop creates columns of color-filled rectangles and the inne... | [
"I can't say anything about the pygame method, but a more idiomatic way to declare the list would be\ncolors = []\ncolors.append(white)\n...\n\nrather than creating and then overwriting a range. You could even do\ncolors = [white, white, ...]\n\nthough that would probably be an ugly line. Also, your first list elem... | [
3,
1
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0004150888_pygame_python.txt |
Q:
Django search_fields & Many-To-One Relations
As an example, I have two models: Household and Person:
from django.db import models
class Household(models.Model):
address = # ...
class Person(models.Model):
household = models.ForeignKey(Household)
name = # ...
How can I search for Households by names of... | Django search_fields & Many-To-One Relations | As an example, I have two models: Household and Person:
from django.db import models
class Household(models.Model):
address = # ...
class Person(models.Model):
household = models.ForeignKey(Household)
name = # ...
How can I search for Households by names of Persons inside the Django admin?
| [
"As mentioned in the docs for search_fields:\n\nYou can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API \"follow\" notation:\nsearch_fields = ['foreign_key__related_fieldname']\n\nFor example, if you have a blog entry with an author, the following definition would enable search ... | [
7
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004151256_django_python.txt |
Q:
How can this be made to do fewer calculations? It is very inefficient with large numbers
num = input ()
fact = 0
while fact != num:
fact = fact + 1
rem = num % fact
if rem == 0:
print fact
A:
You only need to go to the square root of the input number to get all the factors (not as far as... | How can this be made to do fewer calculations? It is very inefficient with large numbers | num = input ()
fact = 0
while fact != num:
fact = fact + 1
rem = num % fact
if rem == 0:
print fact
| [
"You only need to go to the square root of the input number to get all the factors (not as far as half the number, as suggested elsewhere). For example, 24 has factors 1, 2, 3, 4, 6, 8, 12, 24. sqrt(24) is approx 4.9. Check 1 and also get 24, check 2 and also get 12, check 3 and also get 8, check 4 and also get ... | [
3,
2,
2,
2,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004150563_python.txt |
Q:
Why list as key dictionary, will still show itself as tuple as key dictionary
When I define a dictionary which use list as key
collections.defaultdict(list)
When I print it out, it shows itself is using tuple as key.
May I know why?
import collections
tuple_as_dict_key = collections.defaultdict(tuple)
tuple_as_d... | Why list as key dictionary, will still show itself as tuple as key dictionary | When I define a dictionary which use list as key
collections.defaultdict(list)
When I print it out, it shows itself is using tuple as key.
May I know why?
import collections
tuple_as_dict_key = collections.defaultdict(tuple)
tuple_as_dict_key['abc', 1, 2] = 999
tuple_as_dict_key['abc', 3, 4] = 999
tuple_as_dict_key['... | [
"The parameter to defaultdict is not the type of the key, it is a function that creates default data. Your test cases don't exercise this because you're filling the dict with defined values and not using any defaults. If you were to try to get the value list_as_dict_key['abc', 7, 8] it would return an empty list, s... | [
3,
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004151589_python.txt |
Q:
Python: referencing lines in a table
I am trying to take lines from a file and put them into a table that will be displayed on the web. I need to be able to reference these lines individually to alter the table information using an if...else statement.
Can anyone help me find a way to reference these lines when th... | Python: referencing lines in a table | I am trying to take lines from a file and put them into a table that will be displayed on the web. I need to be able to reference these lines individually to alter the table information using an if...else statement.
Can anyone help me find a way to reference these lines when they are pulled through - this is my code so... | [
"Set an id HTML attribute for each table entry (or row, depending on your needs). E.g.\n<tr id=\"Foo\">\n\n",
"Use format strings to your advantage. For instance, If I wanted to conditionally add a greeting, I would default the variable to the empty string and change it, based on my mood. Also:\n\nInstead of inst... | [
2,
0
] | [] | [] | [
"html",
"html_table",
"python"
] | stackoverflow_0004150828_html_html_table_python.txt |
Q:
Downloading a file in Python
import urllib2, sys
if len(sys.argv) !=3:
print "Usage: download.py <link> <saveas>"
sys.exit(1)
site = urllib2.urlopen(sys.argv[1])
meta = site.info()
print "Size: ", meta.getheaders("Content-Length")
f = open(sys.argv[2], 'wb')
f.write(site.read())
f.clo... | Downloading a file in Python | import urllib2, sys
if len(sys.argv) !=3:
print "Usage: download.py <link> <saveas>"
sys.exit(1)
site = urllib2.urlopen(sys.argv[1])
meta = site.info()
print "Size: ", meta.getheaders("Content-Length")
f = open(sys.argv[2], 'wb')
f.write(site.read())
f.close()
I'm wondering how to display... | [
"using urllib.urlretrieve\n\n\n import urllib, sys\n\n def progress_callback(blocks, block_size, total_size):\n #blocks->data downloaded so far (first argument of your callback)\n #block_size -> size of each block\n #total-size -> size of the file\n #implement code to calculate th... | [
5,
1
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0004151841_python_urllib2.txt |
Q:
Pythonic way to rewrite the following C++ string processing code
Previous, I am having a C++ string processing code which is able to do this.
input -> Hello 12
output-> Hello
input -> Hello 12 World
output-> Hello World
input -> Hello12 World
output-> Hello World
input -> Hello12World
output-> HelloWorld
The f... | Pythonic way to rewrite the following C++ string processing code | Previous, I am having a C++ string processing code which is able to do this.
input -> Hello 12
output-> Hello
input -> Hello 12 World
output-> Hello World
input -> Hello12 World
output-> Hello World
input -> Hello12World
output-> HelloWorld
The following is the C++ code.
std::string Utils::toStringWithoutNumerical(... | [
"Edit: This reproduces more accurately what the C++ code does than the previous version.\ns = re.sub(r\"\\d+\", \"\", s)\ns = re.sub(r\"(\\s)\\s*\", \"\\1\", s)\n\nIn particular, if the first whitespace in a run of several whitespaces is a tab, it will preserve the tab.\nFurther Edit: To replace by a space anyway,... | [
7,
5,
1,
0,
0
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0004150832_c++_python.txt |
Q:
Simple sqlite question
When I use:
for i in Selection:
Q = "SELECT columnA FROM DB WHERE wbcode='"+i+"' and commodity='1'"
cursor.execute(Q)
ydata[i] = cursor.fetchall()
I get:
ydata = {'GBR': [(u'695022',), (u'774291',), (u'791499',)... ]}
How can I change my code to get:
ydata = {'GBR': [695022, 77... | Simple sqlite question | When I use:
for i in Selection:
Q = "SELECT columnA FROM DB WHERE wbcode='"+i+"' and commodity='1'"
cursor.execute(Q)
ydata[i] = cursor.fetchall()
I get:
ydata = {'GBR': [(u'695022',), (u'774291',), (u'791499',)... ]}
How can I change my code to get:
ydata = {'GBR': [695022, 774291, 791499,...]}
Thank yo... | [
"[int(x[0]) for x in cursor.fetchall()]\n\n",
"Based on this and another question of yours, you need to understand SQLite's affinity and how you are populating the database. Other databases require that the values stored in a column are all of the same type - eg all strings or all integers. SQLite allows you to... | [
4,
2
] | [] | [] | [
"python",
"sql",
"sqlite"
] | stackoverflow_0004147338_python_sql_sqlite.txt |
Q:
Why is dictionary in object not different from the other?
I have the following Python code:
#!/usr/bin/env python2.6
class container(object):
name = 'container'
configuration = {'var1': 'var1',
'var2': 'var2'}
if __name__ == "__main__":
container1 = container()
container2 ... | Why is dictionary in object not different from the other? | I have the following Python code:
#!/usr/bin/env python2.6
class container(object):
name = 'container'
configuration = {'var1': 'var1',
'var2': 'var2'}
if __name__ == "__main__":
container1 = container()
container2 = container()
container2.name = 'container2'
container2... | [
"Because configuration is a class variable and not an instance variable. Fixing this should fix your problem.\nclass container(object):\n def __init__(self):\n self.name = 'container'\n\n self.configuration = {'var1': 'var1',\n 'var2': 'var2'}\n\nWhat's going on here is ... | [
3,
3,
0
] | [] | [] | [
"object",
"python"
] | stackoverflow_0004152210_object_python.txt |
Q:
In Django, what is the best way to manage both a mobile and desktop site?
I'd like everything to function correctly, except when it's mobile, the entire site will used a set of specific templates.
Also, I'd like to autodetect if it's mobile. If so, then use that set of templates throughout the entire site.
A:
Ha... | In Django, what is the best way to manage both a mobile and desktop site? | I'd like everything to function correctly, except when it's mobile, the entire site will used a set of specific templates.
Also, I'd like to autodetect if it's mobile. If so, then use that set of templates throughout the entire site.
| [
"Have two sets of templates, one for mobile, one for desktop. Store the filenames in a pair of dictionaries, and use the User-agent header to detect which set should be used. Also allow manual selection of which site to use via a session entry.\n",
"If you place a class on your body (Django uses something similar... | [
9,
1,
1,
0,
0,
0
] | [] | [] | [
"css",
"django",
"mobile",
"python",
"templates"
] | stackoverflow_0002396938_css_django_mobile_python_templates.txt |
Q:
Import an existing python project to XCode
I've got a python project I've been making in terminal with vim etc.. I've read that XCode supports Python development at that it supports SVN (which I am using) but I can't find documentation on how to start a new XCode project from an existing code repository.
Other dev... | Import an existing python project to XCode | I've got a python project I've been making in terminal with vim etc.. I've read that XCode supports Python development at that it supports SVN (which I am using) but I can't find documentation on how to start a new XCode project from an existing code repository.
Other developers are working on the project not using XCo... | [
"I don't think it's worth using Xcode for a pure python project. Although the Xcode editor does syntax-highlight Python code, Xcode does not give you any other benefit for writing a pure-python app. On OS X, I would recommend TextMate as a text editor or Eclipse with PyDev as a more full-featured IDE.\n",
"I reco... | [
7,
2,
1,
1
] | [] | [] | [
"macos",
"python",
"xcode"
] | stackoverflow_0000709397_macos_python_xcode.txt |
Q:
plotting sparce time with matplotlib
I want to plot a trading timeseries, e.g. close of 5 min bars. The markets are closed over night. So I have two queries:
How to plot time in MatPlotLib (as well as date). E.g. so I need to implement a new axis or new hourLocators etc.
How to remove overnight gaps from my plot. ... | plotting sparce time with matplotlib | I want to plot a trading timeseries, e.g. close of 5 min bars. The markets are closed over night. So I have two queries:
How to plot time in MatPlotLib (as well as date). E.g. so I need to implement a new axis or new hourLocators etc.
How to remove overnight gaps from my plot. I.e. I want the last bar on Monday evening... | [
"Look at this example. It skips weekend gaps in a series of daily data and is very easy to adapt to your case.\n"
] | [
3
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0004152396_matplotlib_python.txt |
Q:
Render Externally Defined Block In Django Template
I'm writing a simple blog-like application for Django and am trying to get the effect of having a front page with posts limited to 5, with a comprehensive archive that lists something like 100 posts at a time. (100 is not realistic, just throwing a number out ther... | Render Externally Defined Block In Django Template | I'm writing a simple blog-like application for Django and am trying to get the effect of having a front page with posts limited to 5, with a comprehensive archive that lists something like 100 posts at a time. (100 is not realistic, just throwing a number out there)
Since the blog post blocks will look exactly the same... | [
"You're looking for an inclusion tag.\n",
"Why don't you filter for the blog posts you want to show in your view? That way you can keep the template the same:\n{% for object in blogposts %}\n# ...\n{% endfor %}\n\nYou define blogposts in your view, which either includes 5 or 100 posts.\n",
"Ignacio is right tha... | [
2,
0,
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0004152710_django_django_templates_python.txt |
Q:
Authentication in Facebook Canvas App using New Graph API
I am building a Facebook canvas application that loads in an iframe with Django. I would like the login process to work similarly to the way Zynga does it. In this method, if you are not logged in you are redirected to a Facebook login page and then to a ... | Authentication in Facebook Canvas App using New Graph API | I am building a Facebook canvas application that loads in an iframe with Django. I would like the login process to work similarly to the way Zynga does it. In this method, if you are not logged in you are redirected to a Facebook login page and then to a permissions request page for the app (without any popups).
As f... | [
"\nIs there a way to use the\n javascript SDK to redirect to the\n login page rather than loading it as a\n popup?\n\nNo. The JavaScript SDK will open a new window rather than redirect the current window.\nTo present the user with a full-screen version of the authorization dialog, you need to redirect them to ht... | [
13,
0
] | [] | [] | [
"django",
"facebook",
"javascript",
"python"
] | stackoverflow_0003302908_django_facebook_javascript_python.txt |
Q:
is it possible not to use "self" in a class?
Possible Duplicate:
Python: How to avoid explicit 'self'?
In python class if I need to reference the class member variable, I need to have a self. before it. This is anonying, can I not use that but reference the class member?
Thanks.
Bin
A:
No.
>>> import this
...... | is it possible not to use "self" in a class? |
Possible Duplicate:
Python: How to avoid explicit 'self'?
In python class if I need to reference the class member variable, I need to have a self. before it. This is anonying, can I not use that but reference the class member?
Thanks.
Bin
| [
"No.\n>>> import this\n...\nExplicit is better than implicit.\n...\n\n",
"To reference a class variables, you do not need explicit self. You need it for referencing object (class instance) variables. To reference a class variable, you can simply use that class name, like this:\nclass C:\n x = 1\n def set(se... | [
6,
3,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004152850_python.txt |
Q:
sqlite: check reader/writer lock
I have 2 processes which both access an sqlite3 database. While reading is not a problem in sqlite, only one process can write to the database. According to the faq:
http://www.sqlite.org/faq.html#q5 sqlite uses reader/writer locks.
How do i check if the database is locked for wri... | sqlite: check reader/writer lock | I have 2 processes which both access an sqlite3 database. While reading is not a problem in sqlite, only one process can write to the database. According to the faq:
http://www.sqlite.org/faq.html#q5 sqlite uses reader/writer locks.
How do i check if the database is locked for writing by another process, both from pyt... | [
"When SQLite tries to access a locked database, it's default behaviour is to return SQLITE_BUSY. The documentation describes ways to add custom handling to this event: http://www.sqlite.org/faq.html#q5.\nI understand from the documentation that any function you call that tries to write to this locked database will... | [
2
] | [] | [] | [
"c++",
"python",
"sqlite"
] | stackoverflow_0004153091_c++_python_sqlite.txt |
Q:
If I have a queue (SQS, AMQP), how do I notify my worker servers when there is an object in it?
A lot of times my queue will remain empty. But when it does fill up, how does that queue notify my server to execute a python script?
I could make it so that the python script hits the queue every 5 seconds, but that's ... | If I have a queue (SQS, AMQP), how do I notify my worker servers when there is an object in it? | A lot of times my queue will remain empty. But when it does fill up, how does that queue notify my server to execute a python script?
I could make it so that the python script hits the queue every 5 seconds, but that's silly.
| [
"You should have a consumer on the queue, which registers a callback. The consumer will then poll the queue and call the callback when an item is received.\nYou don't say how you're accessing the queue, but a library like carrot does this for you.\n"
] | [
0
] | [] | [] | [
"amqp",
"distributed",
"events",
"python",
"queue"
] | stackoverflow_0004153006_amqp_distributed_events_python_queue.txt |
Q:
How do I send midi Control Change messages (CC's) using pyPortMidi or pygame?
I'm using Python along with Pygame which uses pyPortMidi for it's midi module, and I'm currently sending NoteOn and NoteOff messages through Midi Yoke to Ableton live, which works great. But I can't seem to figure out how I send CC messa... | How do I send midi Control Change messages (CC's) using pyPortMidi or pygame? | I'm using Python along with Pygame which uses pyPortMidi for it's midi module, and I'm currently sending NoteOn and NoteOff messages through Midi Yoke to Ableton live, which works great. But I can't seem to figure out how I send CC messages..
Anyone?
The (working) class basically looks like this.
class MidiIO: ... | [
"It looks like you would use the write_short method to write raw MIDI packets, or the write method if you want to send several of them at once. So, for example, if you want to send the value 123 on controller 17, that would look like this:\nself.midi_out.write_short(0xb0, 17, 123)\n\nThe reason you probably didn't... | [
3,
0
] | [] | [] | [
"midi",
"pygame",
"python"
] | stackoverflow_0004011498_midi_pygame_python.txt |
Q:
Portable Python (Mac -> Windows)
I have a lovely Macbook now, and I'm enjoying coding on the move. I'm also enjoying coding in Python. However, I'd like to distribute the end result to friends using Windows, as an executable.
I know that Py2Exe does this, but I don't know how portable Python is across operating sy... | Portable Python (Mac -> Windows) | I have a lovely Macbook now, and I'm enjoying coding on the move. I'm also enjoying coding in Python. However, I'd like to distribute the end result to friends using Windows, as an executable.
I know that Py2Exe does this, but I don't know how portable Python is across operating systems. Can anyone offer any advice? I'... | [
"The Python scripts are reasonably portable, as long as the interpreter and relevant libraries are installed. Generated .exe and .app files are not.\n",
"Py2exe generates Windows executables, so they will only work on the Windows Platform. The FAQ at http://www.py2exe.org/index.cgi/FAQ has more information on ho... | [
3,
2,
0,
0
] | [] | [] | [
"portability",
"pygame",
"python"
] | stackoverflow_0004086675_portability_pygame_python.txt |
Q:
python class property does not evaluated in the if condition
I have a python class as follow
class Application(models.Model):
name = models.CharField(help_text="Application's name",max_length=200)
current_status = models.IntegerField(null=True, blank=True)
class Meta:
ordering = ["name"]
@... | python class property does not evaluated in the if condition | I have a python class as follow
class Application(models.Model):
name = models.CharField(help_text="Application's name",max_length=200)
current_status = models.IntegerField(null=True, blank=True)
class Meta:
ordering = ["name"]
@property
def status(self):
"""Returns the current Appl... | [
"You said:\n\nAlthough I am sure that the status of the application is not None, the else clause is executed\n\nThe code you posted is:\nif app.status is None:\n #do some thing\nelse:\n #do another thing\n\nIf the status is not None then the else clause will be executed.\nWhat I can't understand if ho... | [
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004143057_python.txt |
Q:
Python and Server Load
Is there a way, using Python, to check the server load of a Linux machine periodically and inform me of it in some way?
A:
Python has a function to get the system's load average as part of the os module
>>> import os
>>> os.getloadavg()
(1.1200000000000001, 1.0600000000000001, 0.7900000000... | Python and Server Load | Is there a way, using Python, to check the server load of a Linux machine periodically and inform me of it in some way?
| [
"Python has a function to get the system's load average as part of the os module\n>>> import os\n>>> os.getloadavg()\n(1.1200000000000001, 1.0600000000000001, 0.79000000000000004)\n\nFrom there, you can do whatever checks you need, and then email you, or similar.\n",
"os.getloadavg()\n"
] | [
48,
9
] | [] | [] | [
"python"
] | stackoverflow_0004153881_python.txt |
Q:
python uninstall and update packages
I want to update all eggs and uninstall some I installed using easy_install.
How could I do that?
I've been looking for ways of updating/removing eggs and I find out that it's just one big crap - there is no way to do that other than writing my own software for that. Is that ... | python uninstall and update packages | I want to update all eggs and uninstall some I installed using easy_install.
How could I do that?
I've been looking for ways of updating/removing eggs and I find out that it's just one big crap - there is no way to do that other than writing my own software for that. Is that really so great crap that I cannot update/... | [
"Look at this post.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0004153873_python.txt |
Q:
Why is self only a convention and not a real Python keyword?
As far as I know, self is just a very powerful convention and it's not really a reserved keyword in Python. Java and C# have this as a keyword. I really find it weird that they didn't make a reserved keyword for it in Python. Is there any reason behind t... | Why is self only a convention and not a real Python keyword? | As far as I know, self is just a very powerful convention and it's not really a reserved keyword in Python. Java and C# have this as a keyword. I really find it weird that they didn't make a reserved keyword for it in Python. Is there any reason behind this?
| [
"Because self is just a parameter to a function, like any other parameter. For example, the following call:\n\na = A()\na.x()\n\nessentially gets converted to:\n\na = A()\nA.x(a)\n\nNot making self a reserved word has had the fortunate result as well that for class methods, you can rename the first parameter to som... | [
5,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0004131582_python.txt |
Q:
How to use comparison and ' if not' in python?
In one piece of my program I doubt if i use the comparison correctly. i want to make sure that ( u0 <= u < u0+step ) before do something.
if not (u0 <= u) and (u < u0+step):
u0 = u0+ step # change the condition until it is satisfied
else:
do something. # cond... | How to use comparison and ' if not' in python? | In one piece of my program I doubt if i use the comparison correctly. i want to make sure that ( u0 <= u < u0+step ) before do something.
if not (u0 <= u) and (u < u0+step):
u0 = u0+ step # change the condition until it is satisfied
else:
do something. # condition is satisfied
| [
"You can do:\nif not (u0 <= u <= u0+step):\n u0 = u0+ step # change the condition until it is satisfied\nelse:\n do sth. # condition is satisfied\n\nUsing a loop:\nwhile not (u0 <= u <= u0+step):\n u0 = u0+ step # change the condition until it is satisfied\ndo sth. # condition is satisfied\n\n",
"Operator... | [
57,
10,
4,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0004153260_python.txt |
Q:
Anyone know of a C++ or Python library that will divide an image into pieces of arbitrary shape?
I'm working on a project involving puzzles made out of user-supplied images. I have been very hard-pressed to find a library that will serve my purposes. I would like to write the program in either Python or C++. I hav... | Anyone know of a C++ or Python library that will divide an image into pieces of arbitrary shape? | I'm working on a project involving puzzles made out of user-supplied images. I have been very hard-pressed to find a library that will serve my purposes. I would like to write the program in either Python or C++. I have been considering using Qt (or PyQt) to do it, so if you know of a library that will work with Qt it ... | [
"You can't expect to find a library for any specific task. In this case, you need image-processing library, which is able to:\n\ndraw image region with transparent background. You have piece configuration, use it as a mask to cut out edges.\nsave drawn image to some format.\n\nQt graphics is totally able to do all ... | [
2
] | [] | [] | [
"c++",
"image_processing",
"pyqt",
"python",
"qt"
] | stackoverflow_0004151746_c++_image_processing_pyqt_python_qt.txt |
Q:
Python - generate the time difference
I am trying to generate a report for the usage statistics.Below is the sample data that i have in in an array and this is fetched from Mysql table.How to implement a logic saying that if the user is idle for more than 30 minutes he has not used the system else calculate the ti... | Python - generate the time difference | I am trying to generate a report for the usage statistics.Below is the sample data that i have in in an array and this is fetched from Mysql table.How to implement a logic saying that if the user is idle for more than 30 minutes he has not used the system else calculate the time mean time of the usage.
timestamp=[]
for... | [
"I think this is what you want. It goes through the list calculating the difference between each entry and the previous one. If the difference is bigger than or equal 30 minutes it ignores it. If it is less than 30 minutes it adds it to the total usage for that user. (I'm assuming all the timestamps are for the ... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0004154116_python.txt |
Q:
0A hex bug on writing to file?
I have a little problem:
why does this code
somefile = open('foo.txt', 'w')
somefile.write('0B0B0B'.decode('hex'))
somefile.close()
write 0B0B0B in file, and this code
somefile = open('foo.txt', 'w')
somefile.write('0A0A0A'.decode('hex'))
somefile.close()
write 0D0A0D0A0D0A in file... | 0A hex bug on writing to file? | I have a little problem:
why does this code
somefile = open('foo.txt', 'w')
somefile.write('0B0B0B'.decode('hex'))
somefile.close()
write 0B0B0B in file, and this code
somefile = open('foo.txt', 'w')
somefile.write('0A0A0A'.decode('hex'))
somefile.close()
write 0D0A0D0A0D0A in file? Where does that '0D' come from?
| [
"It comes from the \\n -> \\r\\n transformation due to the fact that you're running on Windows. Open the file in binary mode ('wb') if you want to avoid this.\n"
] | [
9
] | [] | [] | [
"hex",
"python"
] | stackoverflow_0004154369_hex_python.txt |
Q:
JavaScript, Django, and Google App Engine - Replace Text
My goal is to associate a tooltip (containing a definition) to certain words on the client side using JS.
The text is generated with Django/Python (from a GAE datastore).
To accomplish this, I need to scan a block of text for multiple key words that requir... | JavaScript, Django, and Google App Engine - Replace Text | My goal is to associate a tooltip (containing a definition) to certain words on the client side using JS.
The text is generated with Django/Python (from a GAE datastore).
To accomplish this, I need to scan a block of text for multiple key words that require definitions and dynamically create a html 'title' for the to... | [
"The easiest way to do this would be to simply build up the string within the Django for loop, replacing on it each time, then only outputting it at the end:\n{% for i in thing %}\nstr = str.replace(/{{i.word}}/gi, \"<strong><a title='{{i.tooltip}}'> {{i.word}}</a></strong>\"));\n{% endfor %}\ndocument.write(str);\... | [
1
] | [] | [] | [
"django",
"google_app_engine",
"javascript",
"python",
"str_replace"
] | stackoverflow_0004154317_django_google_app_engine_javascript_python_str_replace.txt |
Q:
Python script to switch user automatically
I'm working on windows xp. How can i write a simple script which would automatically log me out of this account and log into another account on this computer upon execution of a trigger point I set in my application??
Please help.
A:
What do you need to do on another ac... | Python script to switch user automatically | I'm working on windows xp. How can i write a simple script which would automatically log me out of this account and log into another account on this computer upon execution of a trigger point I set in my application??
Please help.
| [
"What do you need to do on another account? If you want to run some commands on another account os.system and runas will help you.\n",
"To logoff, call ExitWindowsEx() with EWX_LOGOFF (0). To automatically login afterwards, write DefaultUserName and DefaultPassword to HKLM\\SOFTWARE\\Microsoft\\Windows NT\\Curren... | [
3,
2,
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0004153969_python_windows.txt |
Q:
Python YouTube Gdata Player Error
I'm trying something really simple: get a list of player urls from the youtube gdata module,
def getlist():
index = 1
prev = 0
urls = []
while True:
uri = "http://gdata.youtube.com/feeds/api/playlists/E005D335B57338D1?start-index=%i&max-results=50" % index
feed = y... | Python YouTube Gdata Player Error | I'm trying something really simple: get a list of player urls from the youtube gdata module,
def getlist():
index = 1
prev = 0
urls = []
while True:
uri = "http://gdata.youtube.com/feeds/api/playlists/E005D335B57338D1?start-index=%i&max-results=50" % index
feed = yt_service.GetYouTubeVideoFeed(uri)
... | [
"You should add a check to guarantee that the player is not null:\n...\nfor entry in feed.entry:\n if entry.media.player is not None:\n urls.append(entry.media.player.url)\n...\n\n"
] | [
1
] | [] | [] | [
"gdata",
"python",
"youtube"
] | stackoverflow_0003938703_gdata_python_youtube.txt |
Q:
Capturing tablet data at constant rate, instead of at frame rate (python, pygame, wintab, cgkit)
First of all, I am not a veteran programmer i any language. But I've been tinkering with python pretty substantially the last couple of months so I wouldn't consider my self completely green either.
Some keywords for y... | Capturing tablet data at constant rate, instead of at frame rate (python, pygame, wintab, cgkit) | First of all, I am not a veteran programmer i any language. But I've been tinkering with python pretty substantially the last couple of months so I wouldn't consider my self completely green either.
Some keywords for you:
- Windows
- Python 2.6
- Pygame, CGKit
Okay, so I've got the CGKit module, which contains a WinTab... | [
"without being experienced on the subject, I would say that threads are not a good idea for precise timing functions. From what I studied there is not a precise timing enforced on them . \nI remember there is a function inside the time pygame module that forces your code to run at a specific time and thus limits th... | [
1
] | [] | [] | [
"pygame",
"python",
"windows"
] | stackoverflow_0003993900_pygame_python_windows.txt |
Q:
How to see "Actual execution plan" of our query in python?
I have a sql query in python which is pretty slow, it contain some inner join,
And some one suggest that in this case we can: turn on the "Show Actual Execution Plan" option and then take a close look at what is causing the slowdown.
Here some one has sim... | How to see "Actual execution plan" of our query in python? | I have a sql query in python which is pretty slow, it contain some inner join,
And some one suggest that in this case we can: turn on the "Show Actual Execution Plan" option and then take a close look at what is causing the slowdown.
Here some one has similar prolem as me : Slow SQL Query due to inner and left join?
D... | [
"You issue the EXPLAIN query the same as you would any other query.\n"
] | [
4
] | [] | [] | [
"python",
"sql_execution_plan",
"sqlite"
] | stackoverflow_0004155046_python_sql_execution_plan_sqlite.txt |
Q:
AttributeError: 'myWindow' object has no attribute 'txtFirstName'
I'm trying to make a simple PyQT4 application that will let me show the text from two textboxes in a single message box. It's pretty straight forward, so I'm sure I'm missing something really tiny.
Thanks for your help.
import sys
from PyQt4 import ... | AttributeError: 'myWindow' object has no attribute 'txtFirstName' | I'm trying to make a simple PyQT4 application that will let me show the text from two textboxes in a single message box. It's pretty straight forward, so I'm sure I'm missing something really tiny.
Thanks for your help.
import sys
from PyQt4 import QtGui, QtCore
class myWindow(QtGui.QWidget):
def __init__(self, pa... | [
"The problem is in __init__, where txtLastName is created. It's not created as a class member, but rather as a local variable inside the __init__ method. To make it a class member you can later refer to, use self.: \n self.txtFirstName = QtGui.QLineEdit('', self)\n self.txtFirstName.setGeometry(35, 35, 150, 2... | [
3
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0004155559_pyqt_python.txt |
Q:
How can I display a picture on a control in PyQt4?
I'd like to display a picture on my form using PyQt4.
Here is my code:
import sys
from PyQt4 import QtGui, QtCore
class myWindow(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
#The setGeometry method is ... | How can I display a picture on a control in PyQt4? | I'd like to display a picture on my form using PyQt4.
Here is my code:
import sys
from PyQt4 import QtGui, QtCore
class myWindow(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
#The setGeometry method is used to position the control.
#Order: X, Y posit... | [
"There are many ways, for example using the QPixmap class. Once again, I encourage you to take a look at the examples available with PyQt. For example, examples\\animation\\appchooser\\, or examples\\widgets\\icons\\\n"
] | [
1
] | [] | [] | [
"image",
"pyqt",
"python"
] | stackoverflow_0004155752_image_pyqt_python.txt |
Q:
match a paragraph starts with some letter
I have a file that contains paragraphs starting with AB, I wanted to get all these paragraphs,
I used the following code, but it returns nothing:
import re
paragraphs = re.findall(r'AB[.\n]+AD',text) #AD is the beginning of the next paragraph
Any idea why did not this w... | match a paragraph starts with some letter | I have a file that contains paragraphs starting with AB, I wanted to get all these paragraphs,
I used the following code, but it returns nothing:
import re
paragraphs = re.findall(r'AB[.\n]+AD',text) #AD is the beginning of the next paragraph
Any idea why did not this work?
Thanks
| [
"Try:\nre.findall(r'AB.+?(?=AD)', text, re.DOTALL)\n\nThe re.DOTALL flag will let the dot cover everything included the newlines. And (?=AD) will match everything up to the last character before AD, but will not include AD into the matched string.\nYou can then rstrip() the resulting strings to remove all newlines ... | [
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004155794_python_regex.txt |
Q:
Starting jython program from python using subprocess module?
I have a jython server script (called rajant_server.py) that interacts with a java api file to communicate over special network radios. I have a python program which acts as a client (and does several other things as well). Currently, I have to start the... | Starting jython program from python using subprocess module? | I have a jython server script (called rajant_server.py) that interacts with a java api file to communicate over special network radios. I have a python program which acts as a client (and does several other things as well). Currently, I have to start the server first by opening a command/terminal window and typing:
cd ... | [
"The Popen function in subprocess accepts an optional parameter 'cwd', to define the current working directory of the child process.\nrajantserver = subprocess.Popen([\"cmd\",command],\\\n creationflags = subprocess.CREATE_NEW_CONSOLE,\\\n cwd = path)\n\nYou can get rid of the os.getcwd call and the t... | [
1
] | [] | [] | [
"jython",
"python",
"subprocess"
] | stackoverflow_0004129883_jython_python_subprocess.txt |
Q:
Good tutorials on profiling and speeding up bottlenecks in python with C/C++
looking to learn more about the above. Any recommendations for packages and tutorials about the above ?
A:
The Python extension documentation does a pretty good job of describing how to create C-extensions for your bottlenecks.
| Good tutorials on profiling and speeding up bottlenecks in python with C/C++ | looking to learn more about the above. Any recommendations for packages and tutorials about the above ?
| [
"The Python extension documentation does a pretty good job of describing how to create C-extensions for your bottlenecks.\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0004156355_python.txt |
Q:
Python - detect keyboard layout
Playing around with RFID reader in serial, using python to output to console through uinput/
The thing is, doing the conversion from fake-rfid-keyboard-codes to code sent to uinput/, I would better know if I am using a QWERTY or an AZERTY ('a' becoming 'q', etc...)
Back here in Belg... | Python - detect keyboard layout | Playing around with RFID reader in serial, using python to output to console through uinput/
The thing is, doing the conversion from fake-rfid-keyboard-codes to code sent to uinput/, I would better know if I am using a QWERTY or an AZERTY ('a' becoming 'q', etc...)
Back here in Belgium, especially during the event I am... | [
"You could start by looking at setxkbmap -print, but generally this is nontrivial.\nWhy not instead set the keyboard layout to QWERTY for the virtual keyboard device you're creating with uinput? X supports separate layouts for each device.\nxinput list # find the device ID, say, 12\nsetxkbmap -de... | [
1
] | [] | [] | [
"keyboard",
"layout",
"linux",
"python"
] | stackoverflow_0002989691_keyboard_layout_linux_python.txt |
Q:
How to create a python 2.x package - simple case
Please show the simple and up to date standard way to create a python package for python 2.x
I'd prefer to use pip for installing the package later.
The package should contain a single class:
class hello:
def greet(self):
print "hello"
One should be able to d... | How to create a python 2.x package - simple case | Please show the simple and up to date standard way to create a python package for python 2.x
I'd prefer to use pip for installing the package later.
The package should contain a single class:
class hello:
def greet(self):
print "hello"
One should be able to do the following later:
pip install my_package-0.1.1...... | [
"Start simple\nSimplest one-file package:\nMyProject/\n setup.py\n my_package.py\n\nSimplest setup.py:\nfrom setuptools import setup\nsetup(name='MyProject',\n version='0.1',\n author='Your Name',\n author_email='your.name@example.com',\n license='MIT',\n description='Example package ... | [
32,
4
] | [] | [] | [
"packaging",
"python",
"python_2.x"
] | stackoverflow_0004155914_packaging_python_python_2.x.txt |
Q:
Python Puzzle code review(spoiler)
I have been working on the problems presented in Python Challenge. One of the problems asks to sift through a mess of characters and pick out the rarest character/s.
My methodology was to read the characters from a text file, store the characters/occurrence as a key/value pair in... | Python Puzzle code review(spoiler) | I have been working on the problems presented in Python Challenge. One of the problems asks to sift through a mess of characters and pick out the rarest character/s.
My methodology was to read the characters from a text file, store the characters/occurrence as a key/value pair in a dictionary. Sort the dictionary by va... | [
"Refactoring: A Walkthrough\nI want to walk you through the process of refactoring. Learning to program is not just about knowing the end result, which is what you usually get when you ask a question on Stack Overflow. It's about how to get to that answer yourself. When people post short, dense answers to a questio... | [
7,
4,
2,
1,
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0004156699_algorithm_python.txt |
Q:
Passing array of strings as parameter in python ctypes
This is a followup to Multi-dimensional char array (array of strings) in python ctypes . I have a c function that manipulates an array of strings. The data type is static, so this helps:
void cfunction(char strings[8][1024])
{
printf("string0 = %s\nstring1 =... | Passing array of strings as parameter in python ctypes | This is a followup to Multi-dimensional char array (array of strings) in python ctypes . I have a c function that manipulates an array of strings. The data type is static, so this helps:
void cfunction(char strings[8][1024])
{
printf("string0 = %s\nstring1 = %s\n",strings[0],strings[1]);
strings[0][2] = 'd'; //this ... | [
"I think you need to define words as:\nwords = ((c_char * 1024) * 8)()\n\nThis would be an array of length 8 of character strings of length 1024.\n"
] | [
5
] | [] | [] | [
"ctypes",
"pointers",
"python"
] | stackoverflow_0004156992_ctypes_pointers_python.txt |
Q:
moving on from python
I use python heavily for manipulating data and then packaging it for statistical modeling (R through RPy2).
Feeling a little restless, I would like to branch out into other languages where
Faster than python
It's free
There's good books, documentations and tutorials
Very suitable for data ... | moving on from python | I use python heavily for manipulating data and then packaging it for statistical modeling (R through RPy2).
Feeling a little restless, I would like to branch out into other languages where
Faster than python
It's free
There's good books, documentations and tutorials
Very suitable for data manipulation
Lots of librar... | [
"Use Cython or PyPy or Unladen Swallow. Now you've got Python that's faster than Python and also satisfies all of your requirements.\n",
"If you just want to learn a new language you could take a look at scala. The language is influenced by languages like ruby, python and erlang, but is staticaly typed and runs o... | [
3,
1,
1,
0
] | [] | [] | [
"programming_languages",
"python"
] | stackoverflow_0004155955_programming_languages_python.txt |
Q:
How to get a list of local drives without SUBST'ituted ones in Python / Windows?
I'm looking for a way to get all the local drives on a Windows machine,
So far, I tried with two options
1)
# Win32Com
from win32com.client import Dispatch
import sys
fso = Dispatch('Scripting.FileSystemObject')
for drive in fso.Dr... | How to get a list of local drives without SUBST'ituted ones in Python / Windows? | I'm looking for a way to get all the local drives on a Windows machine,
So far, I tried with two options
1)
# Win32Com
from win32com.client import Dispatch
import sys
fso = Dispatch('Scripting.FileSystemObject')
for drive in fso.Drives:
print drive, drive.DriveType
2)
# win32api
import win32api
import win32fi... | [
"Google tells me that if you try and fetch a GUID for a SUBST-ed drive it will fail:\n>>> import win32file\n>>> win32file.GetVolumeNameForVolumeMountPoint(\"C:\\\\\")\n'\\\\\\\\?\\\\Volume{50c800a9-c62e-11df-b5bb-806e6f6e6963}\\\\'\n>>> win32file.GetVolumeNameForVolumeMountPoint(\"K:\\\\\")\nTraceback (most recent ... | [
1
] | [] | [] | [
"python",
"windows_xp"
] | stackoverflow_0004157904_python_windows_xp.txt |
Q:
Python reading a tabbed text file into a series of lists
Hi as an inexperieced python user I would appreciate any help with the following
programming challenge:
I have a text file with tabulated data, I want to read it and put the values
on each line into different python lists.
The file looks like this:
1 3032... | Python reading a tabbed text file into a series of lists | Hi as an inexperieced python user I would appreciate any help with the following
programming challenge:
I have a text file with tabulated data, I want to read it and put the values
on each line into different python lists.
The file looks like this:
1 303233.479 233942.326 52.500 0.000 97 47 39.5 INFIN... | [
"You should use a csv.reader; this is a built-in class in Python designed specifically for reading files like this.\n>>> import csv\n>>> fieldnames = (\"pntnums\", \"xcogo\", \"ycogo\", \"zcogo\", \"bearing\",\n \"rad\", \"grad\", \"mval\", \"HCOD\", \"VCOD\")\n>>> reader = csv.DictReader(open(...)... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0004158030_python.txt |
Q:
How to write this in a simpler way
i = 0
for x in range(0, 5):
for y in range(0, 5):
if 0 == outputAfterLearning[i]:
image.putpixel((x, y), (0, 0, 0))
elif 1 == outputAfterLearning[i]:
image.putpixel((x, y), (255, 255, 255))
i += 1
for x in range(0, 5):
for ... | How to write this in a simpler way | i = 0
for x in range(0, 5):
for y in range(0, 5):
if 0 == outputAfterLearning[i]:
image.putpixel((x, y), (0, 0, 0))
elif 1 == outputAfterLearning[i]:
image.putpixel((x, y), (255, 255, 255))
i += 1
for x in range(0, 5):
for y in range(5, 10):
if 0 == outpu... | [
"xdim, ydim = 10, 10\nxblocksize, yblocksize = 5, 5\nfor xblock in range(0, xdim, xblocksize):\n for yblock in range(0, ydim, yblocksize):\n for x in range(xblock, xblock+xblocksize):\n for y in range(yblock, yblock+yblocksize):\n # the common code.\n\nBut I would create a generator for th... | [
4
] | [] | [] | [
"optimization",
"python",
"refactoring"
] | stackoverflow_0004158045_optimization_python_refactoring.txt |
Q:
Why does Python raise TypeError rather than SyntaxError?
A question purely for curiosity's sake. This is obviously invalid syntax:
foo = {}
foo['bar': 'baz']
It's obvious what happened, the developer moved a line out of the dictionary definition but didn't change it from the literal dictionary declaration to the ... | Why does Python raise TypeError rather than SyntaxError? | A question purely for curiosity's sake. This is obviously invalid syntax:
foo = {}
foo['bar': 'baz']
It's obvious what happened, the developer moved a line out of the dictionary definition but didn't change it from the literal dictionary declaration to the assignment syntax (and has been suitably mocked as a result).
... | [
"Using the colon in an indexing operation generates a slice object, which is not hashable.\n",
"I just want to add some detail to Ignacio answer (which is great) and that take me some time to understand and for people like me that didn't get it (i may be the only one that didn't get it because i didn't see anyon... | [
65,
22
] | [] | [] | [
"python"
] | stackoverflow_0004157278_python.txt |
Q:
How to have recognized all the libraries Rpy2 R
How to have recognized all the libraries Rpy2 R.
Rpy2 not recognizing the libraries, utils, and tools.
import rpy2.robjects as robjects
R = robjects.r
>>> R['library']("utils")
RVector - Python:0x7f65fc85cfc8 / R:0x19bb980
>>> R['library']("tools")
RVector - P... | How to have recognized all the libraries Rpy2 R | How to have recognized all the libraries Rpy2 R.
Rpy2 not recognizing the libraries, utils, and tools.
import rpy2.robjects as robjects
R = robjects.r
>>> R['library']("utils")
RVector - Python:0x7f65fc85cfc8 / R:0x19bb980
>>> R['library']("tools")
RVector - Python:0x7f65fc85f5a8 / R:0x2419140
(>>> from rpy2.ro... | [
"In order to get the importr command to work, you probably need to upgrade your version of rpy2 -- try checking your version:\nprint rpy2.__version__\n\nI believe you need version 2.1.0 or greater. The following works for me under 2.1.7 but not on 2.0.3:\nIn [1]: import rpy2.robjects as robjects\n\nIn [2]: R = robj... | [
4,
1
] | [] | [] | [
"linux",
"python",
"r",
"rpy2",
"ubuntu"
] | stackoverflow_0004157926_linux_python_r_rpy2_ubuntu.txt |
Q:
Django/Python: how can i filter with Model's custom method?? Is this possible?
I have a model with a custom method. Here's the example:
class MyModel(models)
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50)
nickname = models.CharField(max_length=50)
time_created = models.D... | Django/Python: how can i filter with Model's custom method?? Is this possible? | I have a model with a custom method. Here's the example:
class MyModel(models)
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50)
nickname = models.CharField(max_length=50)
time_created = models.DateTimeField(auto_now_add=True)
def sample_method(self)
right_now = datet... | [
"You cannot use a custom method on your model for filtering, because the filters will be resolved to saw sql, which will not be possible with some python code. Nonetheless the following should solve your problem:\nimport datetime\nqueryset = MyModel.objects.filter(\\\n time_created__lt=(datetime.now()-datetime.... | [
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004157984_django_python.txt |
Q:
Is Django 1.3 alpha available in pypi yet?
I have a buildout script that gets django as a dependency. I'd like to play with Django 1.3 in my project, but I don't want to download and install it, I'd like my buildout to do that.
Does anyone know how I can do this, or am I better off just downloading from the websit... | Is Django 1.3 alpha available in pypi yet? | I have a buildout script that gets django as a dependency. I'd like to play with Django 1.3 in my project, but I don't want to download and install it, I'd like my buildout to do that.
Does anyone know how I can do this, or am I better off just downloading from the website and placing django in the appropriate spot?
UP... | [
"Either you wait for django to be released in PyPI or you include it with your packaging solution.\nEdit: If you want buildout to do it all for you, you can use the url attribute and let it download the package from the django website.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004158337_django_python.txt |
Q:
reading very large file where format is newline independent
My Python code supports reading and writing data in a file format created by others called the BLT format. The BLT format is white space and newline independent in that a newline is treated just like other white space. The primary entry in this format i... | reading very large file where format is newline independent | My Python code supports reading and writing data in a file format created by others called the BLT format. The BLT format is white space and newline independent in that a newline is treated just like other white space. The primary entry in this format is a "ballot" which ends with a "0", e.g.,
1 2 3 0
Since the form... | [
"For me, the most straightforward way to solve this is with generators.\ndef tokens(filename):\n with open(filename) as infile:\n for line in infile:\n for item in line.split():\n yield int(item)\n\ndef ballots(tokens):\n ballot = []\n for t in tokens:\n if t:\n ... | [
3,
1
] | [] | [] | [
"file_io",
"newline",
"python"
] | stackoverflow_0004158265_file_io_newline_python.txt |
Q:
Why doesn't Python "grouping" work for regular expressions in C?
Here is my Python program:
import re
print re.findall( "([se]{2,30})ting", "testingtested" )
Its output is:
['es']
Which is what I expect. I expect to get back "es" because I searched for 2-30 characters of "e" or "s" which are followed by "ting"... | Why doesn't Python "grouping" work for regular expressions in C? | Here is my Python program:
import re
print re.findall( "([se]{2,30})ting", "testingtested" )
Its output is:
['es']
Which is what I expect. I expect to get back "es" because I searched for 2-30 characters of "e" or "s" which are followed by "ting".
Here is my C program:
#include <stdio.h>
#include <stdlib.h>
#includ... | [
"pmatch is the whole match, not the first parenthesized subexpression.\nTry changing pmatch to an array of 2 elements, then passing 2 in place of 1 to regexec and using the [1] element to get the subexpression match.\nTo others who have cited differences between C and Python and different types of regular expressio... | [
3,
2
] | [] | [] | [
"c",
"python",
"regex"
] | stackoverflow_0004158392_c_python_regex.txt |
Q:
'WSGIRequest' object has no attribute 'user' in Google App Engine
I'm new to django and Google App Engine, and I'm having trouble with using the datastore. Every time I make a query, such as
db.GqlQuery("SELECT * FROM Listing ORDER BY date DESC LIMIT 10")
I receive the error:
'WSGIRequest' object has no attribute... | 'WSGIRequest' object has no attribute 'user' in Google App Engine | I'm new to django and Google App Engine, and I'm having trouble with using the datastore. Every time I make a query, such as
db.GqlQuery("SELECT * FROM Listing ORDER BY date DESC LIMIT 10")
I receive the error:
'WSGIRequest' object has no attribute 'user'
This error seems to be generated in context_processors.py with... | [
"UPDATE\nThe solution suggested by sdolan seems to be to add the following to the settings.py of the app:\nTEMPLATE_CONTEXT_PROCESSORS = (\n \"django.core.context_processors.debug\",\n \"django.core.context_processors.i18n\")\nThis effectively removes the third default processor, django.core.context_processor... | [
1
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0003692853_django_google_app_engine_python.txt |
Q:
Make the readline method of Python recognize both end-of-line variations?
I am writing a Python file that needs to read in several files of different types. I am reading the files in line by line with the traditional for line in f after using f = open("file.txt", "r").
This doesn't seem to be working for all file... | Make the readline method of Python recognize both end-of-line variations? | I am writing a Python file that needs to read in several files of different types. I am reading the files in line by line with the traditional for line in f after using f = open("file.txt", "r").
This doesn't seem to be working for all files. My guess is some files end with different encodings (such as \r\n versus ju... | [
"Use the universal newline support -- see http://docs.python.org/library/functions.html#open\n\nIn addition to the standard fopen()\n values mode may be 'U' or 'rU'. Python\n is usually built with universal\n newline support; supplying 'U' opens\n the file as a text file, but lines may\n be terminated by any o... | [
18,
0
] | [] | [] | [
"python"
] | stackoverflow_0004158645_python.txt |
Q:
tuple vs list objects in python
Can someone explain me this?
>>> [] is []
False
>>> () is ()
True
>>> (1,) is (1,)
False
I understand that I should use "==" instead of "is"to compare the values, I am just wondering why it is this way?
A:
is is based on object identity. I.E., are the left and right the same obj... | tuple vs list objects in python | Can someone explain me this?
>>> [] is []
False
>>> () is ()
True
>>> (1,) is (1,)
False
I understand that I should use "==" instead of "is"to compare the values, I am just wondering why it is this way?
| [
"is is based on object identity. I.E., are the left and right the same object?\nIn all these cases, the objects would ordinarily be different (since you have six separate literals). However, the empty tuples are the same object due to implementation-dependent interning. As you noted, you should never rely on thi... | [
10,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0004158361_python.txt |
Q:
just a canvas in a tkinter window
If I try to place a canvas in a tkinter window and nothing else with this code:
from tkinter import ttk
from tkinter import *
from tkinter.ttk import *
class Application(Frame):
def createWidgets(self):
self.can = Canvas(self.master, width=500, height=250)
self... | just a canvas in a tkinter window | If I try to place a canvas in a tkinter window and nothing else with this code:
from tkinter import ttk
from tkinter import *
from tkinter.ttk import *
class Application(Frame):
def createWidgets(self):
self.can = Canvas(self.master, width=500, height=250)
self.can.grid(row=2, column=1)
self... | [
"The problem is that you are mixing geometry managers in the same window. You can only use one within a given parent widget. You can use both within your application as a whole, but you are using them both on widgets that have the same parent. \nYou need to rewrite your code to use only grid, or only pack, for all ... | [
6
] | [] | [] | [
"geometry",
"layout",
"python",
"tkinter"
] | stackoverflow_0004158087_geometry_layout_python_tkinter.txt |
Q:
Python: create a list of dictionaries using a list comprehension
I have a list of dictionaries, and I want to use it to create another list of dictionaries, slightly amended.
Here's what I want to do:
entries_expanded[:] = [{entry['id'], myfunction(entry['supplier'])} for entry in entries_expanded]
So I end up ... | Python: create a list of dictionaries using a list comprehension | I have a list of dictionaries, and I want to use it to create another list of dictionaries, slightly amended.
Here's what I want to do:
entries_expanded[:] = [{entry['id'], myfunction(entry['supplier'])} for entry in entries_expanded]
So I end up with another list of dictionaries, just with one entry altered.
The sy... | [
"Isn't this what you want?\nentries_expanded[:] = [\n dict((entry['id'], myfunction(entry['supplier']))) \n for entry in entries_expanded\n]\n\nYou could think of it as a generator that creates tuples followed by a list comprehension that makes dictionaries:\nentryiter = ((entry['id'], entry['supplier']) for ... | [
3,
3
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0004158961_list_comprehension_python.txt |
Q:
Encoding problems in python x64
i´m trying to write a little script for writting a sqlite table from an archive list saved in a file. the code so far is this:
import os import _sqlite3 import sys
print sys.path[0] mydir = sys.path[0] print (mydir) def listdir(mydir):
lis=[]
for root, dirs, files in os.wa... | Encoding problems in python x64 | i´m trying to write a little script for writting a sqlite table from an archive list saved in a file. the code so far is this:
import os import _sqlite3 import sys
print sys.path[0] mydir = sys.path[0] print (mydir) def listdir(mydir):
lis=[]
for root, dirs, files in os.walk(mydir):
for name in files... | [
"(zero). please reformat your code\n\nafter for line in file: do something like line = line.decode('encoding-of-the-file'), with encoding being something like utf-8, or iso-8859-1 -- you have to know your input encoding\nIf you don't know the encoding or not care about having a clean decoding, you can guess the mos... | [
1
] | [] | [] | [
"encoding",
"python",
"sqlite"
] | stackoverflow_0004158840_encoding_python_sqlite.txt |
Q:
Synchronizing embedded Python in multi-threaded program
Here is the example of using Python interpreter in multi-threaded program:
#include <python.h>
#include <boost/thread.hpp>
void f(const char* code)
{
static volatile auto counter = 0;
for(; counter < 20; ++counter)
{
auto state = PyGILSta... | Synchronizing embedded Python in multi-threaded program | Here is the example of using Python interpreter in multi-threaded program:
#include <python.h>
#include <boost/thread.hpp>
void f(const char* code)
{
static volatile auto counter = 0;
for(; counter < 20; ++counter)
{
auto state = PyGILState_Ensure();
PyRun_SimpleString(code);
PyGILS... | [
"When CPython calls out to a function that may block (or re-enter Python), it releases the global interpreter lock before calling the function, and then re-acquires the lock after the function returns. In your code, it's your call to the built-in print function that causes the interpreter lock to be released and th... | [
4,
2
] | [] | [] | [
"c",
"c++",
"multithreading",
"python"
] | stackoverflow_0004153140_c_c++_multithreading_python.txt |
Q:
Find the index of a partial dictionary element in a list
I have a list of dictionary as follows:
myList=[{'id':1,'key1':'a','key2':'b'},{'id':8,'key1':'c','key2':'d'},
{'id':6,'key1':'a','key2':'p'}]
To find index of element, I am currently executing following statement:
print myList.index({'id':8,'k... | Find the index of a partial dictionary element in a list | I have a list of dictionary as follows:
myList=[{'id':1,'key1':'a','key2':'b'},{'id':8,'key1':'c','key2':'d'},
{'id':6,'key1':'a','key2':'p'}]
To find index of element, I am currently executing following statement:
print myList.index({'id':8,'key1':'c','key2':'d'})
which returns 1
However, I would like t... | [
"If you're looking for a one-liner (as opposed to reusable code), and your data size is small, you could do something like:\n[elem[\"id\"] for elem in myList].index(8)\n\nwhich extracts the id from each dict, and then finds the index of the provided id. Depending on what your overall goals and data set look like, t... | [
3,
1,
1
] | [
"You could implement your own list. Here is an example that prints the first found result. I added the ValueError to duplicate the existing behavior of .index().\nclass DictList(list):\n\n def index(self, obj):\n for i, o in enumerate(self):\n if o['id'] == obj['id']:\n return i\... | [
-1
] | [
"dictionary",
"indexing",
"python"
] | stackoverflow_0004157400_dictionary_indexing_python.txt |
Q:
Recursively search networkx graph
A question about recursion (and tangentially the graphing library networkx): I have an directed graph with node that have edges that have an attribute ["value"] that can be 0 or 1 (effectively edge weights).
I want to be able to examine a node's neighbor recursively until a neigh... | Recursively search networkx graph | A question about recursion (and tangentially the graphing library networkx): I have an directed graph with node that have edges that have an attribute ["value"] that can be 0 or 1 (effectively edge weights).
I want to be able to examine a node's neighbor recursively until a neighbor's node fails a certain threshold. F... | [
"disclaimer : I don't know anything about networkx, but from my understanding of your problem, maybe this can help:\ndef examine(node, neighbors_list)\n \n for neighbor in graph.neighbors(node):\n if graph[x][\"neighbor\"][\"value\"] = 1:\n return\n else:\n neighbors_list.a... | [
3
] | [] | [] | [
"networkx",
"python",
"recursion"
] | stackoverflow_0004159247_networkx_python_recursion.txt |
Q:
Bittorrent up-to-date library written in python
Is there any up-to-date bittorrent library which is written in python and can be used on windows to write client? Some time ago bitcomet was written in python and it was ok. Any alternatives?
And second question: does bittorrent protocol change? For example what may ... | Bittorrent up-to-date library written in python | Is there any up-to-date bittorrent library which is written in python and can be used on windows to write client? Some time ago bitcomet was written in python and it was ok. Any alternatives?
And second question: does bittorrent protocol change? For example what may happen if I will use old bitcomet library
| [
"The main bittorrent client, from bittorrent.com is all python based I believe. I have hacked it in the past, and it's very clean code easy to modify.\n"
] | [
2
] | [] | [] | [
"bittorrent",
"client",
"python"
] | stackoverflow_0004159847_bittorrent_client_python.txt |
Q:
What are efficient practices for importing python modules?
I'm writing some views in Django, the are just python functions really. I'm curious as to whether there's a better way for me to arrange my files.
It this...
import a, b
def x(request): return a(request)
def y(request): return b(request)
Less efficient th... | What are efficient practices for importing python modules? | I'm writing some views in Django, the are just python functions really. I'm curious as to whether there's a better way for me to arrange my files.
It this...
import a, b
def x(request): return a(request)
def y(request): return b(request)
Less efficient than putting it in two files?
import a
def x(request): return a(re... | [
"Unless you're running Django via CGI (which I really hope you're not), the imports will be cached after the first time they're performed, and this whole argument is meaningless.\n",
"There's not a whole lot of difference, use whatever is most readable.\n",
"You don't need to worry about how many files you use;... | [
3,
2,
0,
0
] | [] | [] | [
"django",
"django_views",
"python",
"python_import"
] | stackoverflow_0004159332_django_django_views_python_python_import.txt |
Q:
Safely evaluate string in Python to call hashlib
I would like to allow people to provide the name of a hash function as a means of digitally fingerprinting some object:
def create_ref(obj, hashfn='sha256'):
"""
Returns a tuple of hexdigest and the method used to generate
the digest.
>>> create_ref... | Safely evaluate string in Python to call hashlib | I would like to allow people to provide the name of a hash function as a means of digitally fingerprinting some object:
def create_ref(obj, hashfn='sha256'):
"""
Returns a tuple of hexdigest and the method used to generate
the digest.
>>> create_ref({}, 'sha1')
('bf21a9e8fbc5a3846fb05b4fa0859e0917b... | [
"No.\nIf you apply some of the SQL Injection attack concepts, it would be conceviable for the user to supply something like this:\n\"sha1(...); some_evil_code(); hashlib.sha1\"\nWhich would totally blow the \"security\" away by ending up like this:\n\"hashlib.\" + \"sha1(...); some_evil_code(); hashlib.sha1\" + \"(... | [
4,
3,
1
] | [
"TYPES = {'sha256':hashlib.sha256 , 'sha1': hashlib.sha1, 'md5': hashlib.md5, ...}\ndef create_ref(obj, hashfn='sha256'):\n #var 1 - use sha256 as default on invalid hashfun\n #func=TYPES.get(hashfn, hashlib.sha256)\n\n #var 2 raise error on invalid hashfun\n if TYPES.has_key(hashfn):\n func=TYPE... | [
-1
] | [
"python"
] | stackoverflow_0004159754_python.txt |
Q:
Computing averages of records from multiple files with python
Dear all,
I am beginner in Python. I am looking for the best way to do the following in Python: let's assume I have three text files, each one with m rows and n columns of numbers, name file A, B, and C. For the following, the contents can be indexed as... | Computing averages of records from multiple files with python | Dear all,
I am beginner in Python. I am looking for the best way to do the following in Python: let's assume I have three text files, each one with m rows and n columns of numbers, name file A, B, and C. For the following, the contents can be indexed as A[i][j], or B[k][l] and so on. I need to compute the average of A[... | [
"Have a look at numpy. It can read the three files into three arrays (using fromfile), calculate the average and export it to a text file (using tofile).\nimport numpy as np\n\n\na = np.fromfile('A.csv', dtype=np.int) \nb = np.fromfile('B.csv', dtype=np.int) \nc = np.fromfile('C.csv', dtype=np.int) \n\nd = (a... | [
1,
0,
0
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0004159582_file_io_python.txt |
Q:
Django get_query_set override is being cached
I'm overriding Django's get_query_set function on one of my models dynamically. I'm doing this to forcibly filter the original query set returned by Model.objects.all/filter/get by a "scenario" value, using a decorator. Here's the decorator's function:
# Get the base Q... | Django get_query_set override is being cached | I'm overriding Django's get_query_set function on one of my models dynamically. I'm doing this to forcibly filter the original query set returned by Model.objects.all/filter/get by a "scenario" value, using a decorator. Here's the decorator's function:
# Get the base QuerySet for these models before we modify their
# Q... | [
"What about creating a Manager object for the model which takes the user as an argument where this filtering is done. My understanding of being DRY w/ Django querysets is to use a Model Manager\n#### view code:\ndef some_view(request):\n expenses = Expense.objects.filter_by_cur_scenario(request.user)\n\n # a... | [
0,
0
] | [] | [] | [
"django",
"django_queryset",
"dry",
"filter",
"python"
] | stackoverflow_0004158283_django_django_queryset_dry_filter_python.txt |
Q:
Can't import EasyDialogs - ImportError: No module named _Dlg
I'm trying to use the EasyDialogs python module to produce some simple dialog boxes for my python script on OSX. Whenever I try and import the EasyDialogs module I get the following error:
>>> import EasyDialogs
Traceback (most recent call last):
File ... | Can't import EasyDialogs - ImportError: No module named _Dlg | I'm trying to use the EasyDialogs python module to produce some simple dialog boxes for my python script on OSX. Whenever I try and import the EasyDialogs module I get the following error:
>>> import EasyDialogs
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/EPD64.f... | [
"From the paths in your traceback, you appear to be using a 64-bit Enthought Python Distribution. The EasyDialogs module uses various OS X Carbon interfaces, many of which OS X only provides 32-bit versions and have been deprecated by Apple. For this reason, the Python Carbon wrapper and EasyDialogs modules are d... | [
3
] | [] | [] | [
"python",
"user_interface"
] | stackoverflow_0004159194_python_user_interface.txt |
Q:
Can I somehow "compile" a python script to work on PC without Python installed?
So I have a Python script:
myscript.py
I am executing it like this:
python D:\myscript.py
However, I must have Python installed and included in the PATH environment variable for that to work.
Is it somehow possible to "bundle" Python... | Can I somehow "compile" a python script to work on PC without Python installed? | So I have a Python script:
myscript.py
I am executing it like this:
python D:\myscript.py
However, I must have Python installed and included in the PATH environment variable for that to work.
Is it somehow possible to "bundle" Python executable with a Python script so other people will be able to run it on their PCs ... | [
"Here is one way to do it (for Windows, using py2exe).\nFirst, install the py2exe on your Windows box.\nThen create a python script named compile.py, like this:\nimport sys\nfrom distutils.core import setup\nimport py2exe\n\nentry_point = sys.argv[1]\nsys.argv.pop()\nsys.argv.append('py2exe')\nsys.argv.append('-q')... | [
29,
13,
11,
9,
7
] | [] | [] | [
"compilation",
"python"
] | stackoverflow_0004158369_compilation_python.txt |
Q:
Python basics- why aren't the contents of my file printing?
I'm running this from eclipse, the file name I'm working with is ex16_text.txt (yes I type it in correctly. It writes to the file correctly (the input appears), but the "print txt.read()" doesn't seem to do anything (prints a blank line), see the output... | Python basics- why aren't the contents of my file printing? | I'm running this from eclipse, the file name I'm working with is ex16_text.txt (yes I type it in correctly. It writes to the file correctly (the input appears), but the "print txt.read()" doesn't seem to do anything (prints a blank line), see the output after the code:
filename = raw_input("What's the file name we'll... | [
"You should flush the file after you have written to it to ensure that the bytes have been written. Also read the warning:\n\nNote: flush() does not necessarily write the file’s data to disk. Use flush() followed by os.fsync() to ensure this behavior.\n\nYou should also close the file if you have finished writing t... | [
6,
4
] | [] | [] | [
"python"
] | stackoverflow_0004160444_python.txt |
Q:
algorithm to find the correct set of numbers
i will take either python of c# solution
i have about 200 numbers:
19.16
98.48
20.65
122.08
26.16
125.83
473.33
125.92
3,981.21
16.81
100.00
43.58
54.19
19.83
3,850.97
20.83
20.83
86.81
37.71
36.33
6,619.42
264.53
...
...
i ... | algorithm to find the correct set of numbers | i will take either python of c# solution
i have about 200 numbers:
19.16
98.48
20.65
122.08
26.16
125.83
473.33
125.92
3,981.21
16.81
100.00
43.58
54.19
19.83
3,850.97
20.83
20.83
86.81
37.71
36.33
6,619.42
264.53
...
...
i know that in this set of numbers, there is a combi... | [
"Here's a recursive function in Python that will find ALL solutions of any size with only two arguments (that you need to specify).\ndef find_all_sum_subsets(target_sum, numbers, offset=0):\n solutions = []\n for i in xrange(offset, len(numbers)):\n value = numbers[i]\n if target_sum == value:\n... | [
4,
3,
1,
1,
1
] | [] | [] | [
"c#",
"python"
] | stackoverflow_0004158988_c#_python.txt |
Q:
Python - Speed up an A Star Pathfinding Algorithm
I've coded my first slightly-complex algorithm, an implementation of the A Star Pathfinding algorithm. I followed some Python.org advice on implementing graphs so a dictionary contains all the nodes each node is linked too. Now, since this is all for a game, each n... | Python - Speed up an A Star Pathfinding Algorithm | I've coded my first slightly-complex algorithm, an implementation of the A Star Pathfinding algorithm. I followed some Python.org advice on implementing graphs so a dictionary contains all the nodes each node is linked too. Now, since this is all for a game, each node is really just a tile in a grid of nodes, hence how... | [
"An easy optimization is to use sets instead of lists for the open and closed sets. \nopenSet = set()\nclosedSet = set()\n\nThis will make all of the in and not in tests O(1) instead of O(n).\n",
"I would use the sets as have been said, but I would also use a heap to find the minimum element (the one that will ... | [
39,
10,
5
] | [] | [] | [
"a_star",
"algorithm",
"performance",
"python"
] | stackoverflow_0004159331_a_star_algorithm_performance_python.txt |
Q:
Conditional removal of an element from XML document tree
My task is to do minor refactoring of some elements of XML tree in python 3, namely replace following structure:
<span class="nobr">
<a href="http://www.google.com/">
http://www.google.com/
<sup>
<img align="absmiddle" alt="" border="0" class="render... | Conditional removal of an element from XML document tree | My task is to do minor refactoring of some elements of XML tree in python 3, namely replace following structure:
<span class="nobr">
<a href="http://www.google.com/">
http://www.google.com/
<sup>
<img align="absmiddle" alt="" border="0" class="rendericon" height="7" src="http://jira.atlassian.com/icon.gif" widt... | [
"This is most definitely a task for an XPath expression, in your case probably in conjunction with lxml. \nThe XPath is probably something along the lines of: \n//span[@class=\"nobr\"]/a[@href]/sup[img/@class=\"rendericon\"]\nMatch your tree with this XPath expression and remove all matched elements.\nNo need for e... | [
1,
1,
1,
0
] | [] | [] | [
"pattern_matching",
"python",
"recursion"
] | stackoverflow_0004159413_pattern_matching_python_recursion.txt |
Q:
HTML drop-down box with Google App Engine
I am creating a Google App Engine web application written in Python, and I would like to create a drop down box that displays different values corresponding to pages of a book that a user could choose from. I would like the action of the drop down box to be to direct the ... | HTML drop-down box with Google App Engine | I am creating a Google App Engine web application written in Python, and I would like to create a drop down box that displays different values corresponding to pages of a book that a user could choose from. I would like the action of the drop down box to be to direct the user to the page that corresponds to this link:... | [
"Use a Jump Menu. Here is a pretty straight forward implementation.\nBasically you'll just add a bit of JavaScript, and instead of writing an a tag, you'll write an option:\n<option value='/viewpage/{{bookpage.key}}'>{{ bookpage.page }} </option>\n\n",
"What about <option value='/viewpage/{{bookpage.key.id}}'>{{... | [
1,
0,
0
] | [] | [] | [
"google_app_engine",
"html",
"python"
] | stackoverflow_0004160401_google_app_engine_html_python.txt |
Q:
How to create dynamic fields in Google App Engine expando class?
I have a db expando class called widget.
I'm passing in a json string and converting it to a dict and then adding it to the datastore.
My question is how can I loop through my dict to create dynamic fields.
widget = Widget.get_by_key_name(key_name)
w... | How to create dynamic fields in Google App Engine expando class? | I have a db expando class called widget.
I'm passing in a json string and converting it to a dict and then adding it to the datastore.
My question is how can I loop through my dict to create dynamic fields.
widget = Widget.get_by_key_name(key_name)
widget.name = self.request.get('wname')
fields = simplejson.loads(self.... | [
"The syntax widget.k references the attribute k on object widget. To dynamically choose which attribute you set, use the built-in setattr method:\nsetattr(widget, k, v)\n\nDynamically setting an attribute like this will create the field on that particular entity.\n"
] | [
4
] | [
"Try:\nfor k, v in fields.items()\n\n"
] | [
-3
] | [
"datastore",
"dynamic_variables",
"expando",
"google_app_engine",
"python"
] | stackoverflow_0004160752_datastore_dynamic_variables_expando_google_app_engine_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.