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:
Problem with Django url regular expression
I am attempting to define a search url using Django with the following structure
www.example.com/afdata/search?device=television&category=news&query=channel&limit=30/
My goal is to extract the values television, news, channel and 30 from the above url and pass it to a vi... | Problem with Django url regular expression | I am attempting to define a search url using Django with the following structure
www.example.com/afdata/search?device=television&category=news&query=channel&limit=30/
My goal is to extract the values television, news, channel and 30 from the above url and pass it to a view defined as follows
def search(request, device... | [
"i suggest that you change your search url to:\n(r'^search', 'search')\n\nthen in your view do\ndef search(request):\n device = request.GET.get('device', 'all')\n category = request.GET.get('category', 'single')\n query = request.GET.get('query', '')\n limit = request.GET.get('limit', 30)\n\n return H... | [
5,
3,
1,
1
] | [] | [] | [
"django",
"python",
"regex"
] | stackoverflow_0006339476_django_python_regex.txt |
Q:
find a string within a tag without finding the tag in python
I have a string within a tag that I want to extract without finding the tag too. I tried:
string = re.search("\[tag\](.*?)\[tag\]", "[tag]string[tag]")
print(string.group(0))
and
string = re.search("/\[tag\](.*?)\[tag\]/i", "extra[tag]string[tag]extra")... | find a string within a tag without finding the tag in python | I have a string within a tag that I want to extract without finding the tag too. I tried:
string = re.search("\[tag\](.*?)\[tag\]", "[tag]string[tag]")
print(string.group(0))
and
string = re.search("/\[tag\](.*?)\[tag\]/i", "extra[tag]string[tag]extra")
print(string.group(0))
both return
[tag]string[tag]
| [
".group(0) is the entire match. Use .group(1) to get the section in parentheses that you want.\nimport re\nstring = re.search(\"\\[tag\\](.*?)\\[tag\\]\", \"[tag]string[tag]\")\nprint string.group(1) # prints 'string'\n\n\n\nPython 2.7 Documentation: re.MatchObject.group\n\n",
"group(0) is the entire match. You w... | [
6,
2,
1
] | [] | [] | [
"bbcode",
"python",
"regex"
] | stackoverflow_0006337088_bbcode_python_regex.txt |
Q:
python library to find outline of image
I am working with Python and PyQt4. I am looking a library with which I can find the outline path of an image (bitmap). With "outline path" I mean a polygon, which separates filled (non-transparent) pixels in the middle of the image from transparent pixels surrounding them.
... | python library to find outline of image | I am working with Python and PyQt4. I am looking a library with which I can find the outline path of an image (bitmap). With "outline path" I mean a polygon, which separates filled (non-transparent) pixels in the middle of the image from transparent pixels surrounding them.
I can not find anything via google, which kin... | [
"There are similar questions here on Stack Overflow which may be of use... ? Essentially you're trying to do edge detection; try searching for that..\n",
"OpenCV has a function called FindContours which does what I want.\n"
] | [
2,
2
] | [] | [] | [
"image",
"python"
] | stackoverflow_0006323047_image_python.txt |
Q:
Python RegEx- hangman algorithm
I am trying to write a hangman algorithm. My idea for it goes like this:
Pre-process a dictionary that contains the relative letter frequencies of words depending on their length. Step complete.
Example:
#Each key corresponds to length of the word.
frequencyDict = {2: ['a', ... | Python RegEx- hangman algorithm | I am trying to write a hangman algorithm. My idea for it goes like this:
Pre-process a dictionary that contains the relative letter frequencies of words depending on their length. Step complete.
Example:
#Each key corresponds to length of the word.
frequencyDict = {2: ['a', 'o', 'e', 'i', 'm', 'h', 'n', 'u', 's... | [
"That's quite a lot of questions. I'll try to answer a few.\n\nYour regex should look more like this: '^e[^e][^e][^e][^e]e[^e]$'. Those [^e] bits say \"match any character that is not 'e'. Note that unlike your regex, this will mach non-letter characters, but that shouldn't be a problem if you make sure your dictio... | [
3,
3
] | [] | [] | [
"algorithm",
"dictionary",
"python",
"regex"
] | stackoverflow_0006339473_algorithm_dictionary_python_regex.txt |
Q:
How to pick a random english word from a list
What would be the best way to go about getting a function that returns a random English word (preferably a noun), without keeping a list of all possible words in a file before hand?
A:
Word lists need not take up all that much space.
Here's a JSON wordlist with 2,465... | How to pick a random english word from a list | What would be the best way to go about getting a function that returns a random English word (preferably a noun), without keeping a list of all possible words in a file before hand?
| [
"Word lists need not take up all that much space.\nHere's a JSON wordlist with 2,465 words, all nouns. It clocks in at under 50K, the size of a medium-sized jpeg image.\nI'll leave choosing a random one as an exercise for the reader.\n",
"You can't. There is no algorithm to generate meaningful words. You can onl... | [
34,
10,
4,
3,
2,
1,
1,
0
] | [] | [] | [
"python",
"random",
"word_list"
] | stackoverflow_0000594273_python_random_word_list.txt |
Q:
pyparsing issue
Right now I have just started to use pyparsing to parse simple postfix expressions. At the moment, I got this far:
from pyparsing import *
integer = Word(nums)
op = Word("+-*/^", max=1)
space = Word(" ")
expr = Word(nums)+space+Word(nums)+space+op
parsed = expr.parseString("3 4 *")
print parsed
Bu... | pyparsing issue | Right now I have just started to use pyparsing to parse simple postfix expressions. At the moment, I got this far:
from pyparsing import *
integer = Word(nums)
op = Word("+-*/^", max=1)
space = Word(" ")
expr = Word(nums)+space+Word(nums)+space+op
parsed = expr.parseString("3 4 *")
print parsed
But when I run it, it p... | [
"White space is handled by default. There is also the handy oneOf:\nfrom pyparsing import *\ninteger = Word(nums)\nop = oneOf('* + - / ^')\nexpr = integer + integer + op\nparsed = expr.parseString(\"3 4 *\")\nprint parsed\n\n",
"White space is ignored by pyparser. You can explicitly test for whitespace by using ... | [
6,
4
] | [] | [] | [
"expression",
"parsing",
"postfix_operator",
"pyparsing",
"python"
] | stackoverflow_0006339920_expression_parsing_postfix_operator_pyparsing_python.txt |
Q:
Not getting any output or errors ghostscript python
No tif image is being generated anyone see the error? I am not receiving any errors. I am now seeing the message that ghosscript is running, still not getting an output tif though. from output I am now getting 'GPL Ghostscript 9.02 (2011-03-30)\nCopyright (C) 20... | Not getting any output or errors ghostscript python | No tif image is being generated anyone see the error? I am not receiving any errors. I am now seeing the message that ghosscript is running, still not getting an output tif though. from output I am now getting 'GPL Ghostscript 9.02 (2011-03-30)\nCopyright (C) 2010 Artifex Software, Inc. All rights reserved.\nThis sof... | [
"I don't see an input file for your command. Add the full path to an input file (PDF, PostScript, Encapsulated PostScript or AI) as the last argument, and your TIFFs should be generated...\nAlso, remove the -q. It tells Ghostscript to remain 'quiet'.\nLastly, you could add a -dDEBUG to your commandline. It tells Gh... | [
5,
1
] | [] | [] | [
"ghostscript",
"python"
] | stackoverflow_0006331357_ghostscript_python.txt |
Q:
Turbomail Integration with Pyramid
I am in need of a method to send an email from a Pyramid application. I know of pyramid_mailer, but it seems to have a fairly limited message class. I don't understand if it's possible to write the messages from pyramid_mailer using templates to generate the body of the email. Fu... | Turbomail Integration with Pyramid | I am in need of a method to send an email from a Pyramid application. I know of pyramid_mailer, but it seems to have a fairly limited message class. I don't understand if it's possible to write the messages from pyramid_mailer using templates to generate the body of the email. Further, I haven't seen anything regarding... | [
"I can't answer your Turbomail questions other than to say that I've heard it works fine with Pyramid.\nRegarding pyramid_mailer, it's entirely possible to render your emails using the same subsystem that lets pyramid render all of your templates.\nfrom pyramid.renderers import render\n\nopts = {} # a dictionary of... | [
4,
3
] | [] | [] | [
"pylons",
"pyramid",
"python",
"turbogears"
] | stackoverflow_0006258850_pylons_pyramid_python_turbogears.txt |
Q:
pylons redirect not working on Mac OS
I have a pylons app issuing a redirect to ask for a user to authenticate twitter.
the code in the controller looks something like this:
auth_url = 'http://twitter.com/oauth/authorize?oauth_token=mY0aUthaCc3s5T0k3n'
return redirect( auth_url )
But literally nothing happens... | pylons redirect not working on Mac OS | I have a pylons app issuing a redirect to ask for a user to authenticate twitter.
the code in the controller looks something like this:
auth_url = 'http://twitter.com/oauth/authorize?oauth_token=mY0aUthaCc3s5T0k3n'
return redirect( auth_url )
But literally nothing happens, only a blank page is rendered.
Now this i... | [
"Try redirect_to.\nfrom pylons.controllers.util import redirect_to\n\nclass SomeController(BaseController):\n def redirect(self):\n auth_url = 'http://twitter.com/oauth/authorize?oauth_token=mY0aUthaCc3s5T0k3n'\n redirect_to( auth_url )\n\nThis works on my mac.\n"
] | [
0
] | [] | [] | [
"pylons",
"python",
"redirect",
"twitter"
] | stackoverflow_0005321421_pylons_python_redirect_twitter.txt |
Q:
Pylons Routes url_for for a map.resource
How do I get the get, post, put and delete URLs for a restful routes resource using url_for?
For example, how do I get the PUT URL for a resource with id=1, and routes defined in routing.py like so:
map.resource('user', 'users', controller='user')
I know the correct URL is... | Pylons Routes url_for for a map.resource | How do I get the get, post, put and delete URLs for a restful routes resource using url_for?
For example, how do I get the PUT URL for a resource with id=1, and routes defined in routing.py like so:
map.resource('user', 'users', controller='user')
I know the correct URL is /users/1, but I don't want to hard code it.
| [
"Check out: http://routes.groovie.org/restful.html\nurl('user', id=1)\n\nshould give you '/users/1'\n",
"In routes.py your route should be:\nmap.resource('user', 'users/{id}', controller='user' action=\"some_action\")\n\nand in your controller you can get this URL with url_for like this:\nurl_for(controller=\"use... | [
1,
0
] | [] | [] | [
"pylons",
"python",
"routes"
] | stackoverflow_0006253628_pylons_python_routes.txt |
Q:
Python: how to control namespace after an unhandled exception?
Is there any way to control which namespace you'll end up in after an unhandled exception?
For example, in an IPython prompt, run myscript.py on a file with these contents:
def spam():
ham = "ham"
crash = 1/0
eggs = "eggs"
if __name__ == '... | Python: how to control namespace after an unhandled exception? | Is there any way to control which namespace you'll end up in after an unhandled exception?
For example, in an IPython prompt, run myscript.py on a file with these contents:
def spam():
ham = "ham"
crash = 1/0
eggs = "eggs"
if __name__ == '__main__':
foo = "foo"
spam()
it crashes out with the zero ... | [
"You can enable the automatic calling of pdb in the ipython prompt by typing %pdb.\n"
] | [
2
] | [] | [] | [
"debugging",
"ipython",
"namespaces",
"python"
] | stackoverflow_0006338889_debugging_ipython_namespaces_python.txt |
Q:
Python tcp send receive functions
In python the recv is a blocking function or not? I'm learned in the Uni C and there the was blocking and non-blocking socket. So I just wan to ask weather in python the recv function is a blocking function or not.
A:
Sockets in Python are blocking by the default. This behavior ... | Python tcp send receive functions | In python the recv is a blocking function or not? I'm learned in the Uni C and there the was blocking and non-blocking socket. So I just wan to ask weather in python the recv function is a blocking function or not.
| [
"Sockets in Python are blocking by the default. This behavior can be changed with setblocking or settimeout.\nAnother good place to find information on this is the socket how-to, especially the section on non-blocking sockets.\n",
"The socket in Python is blocking by default, unless you change it.\n"
] | [
5,
1
] | [] | [] | [
"python",
"recv"
] | stackoverflow_0006340739_python_recv.txt |
Q:
What is a good way to decorate an iterator to alter the value before next is called in python?
I am working on a problem that involves validating a format from within unified diff patch.
The variables within the inner format can span multiple lines at a time, so I wrote a generator that pulls each line and yields ... | What is a good way to decorate an iterator to alter the value before next is called in python? | I am working on a problem that involves validating a format from within unified diff patch.
The variables within the inner format can span multiple lines at a time, so I wrote a generator that pulls each line and yields the variable when it is complete.
To avoid having to rewrite this function when reading from a unifi... | [
"I still don't like this very much, but at least it's shorter and a tad more pythonic:\nfrom itertools import imap, izip\nfrom functools import partial\n\ndef inner_format_validator(inner_item):\n return not inner_item.startswith('+')\n\ninner_gen = partial(imap, inner_format_validator)\n\ndef split(astr):\n ... | [
2,
2,
1
] | [] | [] | [
"decorator",
"generator",
"iterator",
"python",
"validation"
] | stackoverflow_0006337742_decorator_generator_iterator_python_validation.txt |
Q:
Get Request Headers for Urllib2.Request?
Is there a way to get the headers from a request created with Urllib2 or to confirm the HTTP headers sent with urllib2.urlopen?
A:
An easy way to see request (and response headers) is to enable debug output:
opener = urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1))... | Get Request Headers for Urllib2.Request? | Is there a way to get the headers from a request created with Urllib2 or to confirm the HTTP headers sent with urllib2.urlopen?
| [
"An easy way to see request (and response headers) is to enable debug output:\nopener = urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1))\n\nYou then can see the precise headers sent/recieved:\n>>> opener.open('http://python.org')\nsend: 'GET / HTTP/1.1\\r\\nAccept-Encoding: identity\\r\\nHost: python.org\\r\... | [
21
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0006340782_python_urllib2.txt |
Q:
Editting ForeignKey from "child" table
I'm programming on py with django. I have models:
class Product(mymodels.Base):
title = models.CharField()
price = models.ForeignKey(Price)
promoPrice = models.ForeignKey(Price, related_name="promo_price")
class Price(mymodels.Base):
value = models.DecimalFie... | Editting ForeignKey from "child" table | I'm programming on py with django. I have models:
class Product(mymodels.Base):
title = models.CharField()
price = models.ForeignKey(Price)
promoPrice = models.ForeignKey(Price, related_name="promo_price")
class Price(mymodels.Base):
value = models.DecimalField(max_digits=10, decimal_places=3)
taxV... | [
"How about using this instead?\nclass Product(mymodels.Base):\n title = models.CharField()\n price = models.DecimalField(max_digits=10, decimal_places=3)\n tax = models.DecimalField(max_digits=10, decimal_places=3)\n promo_price = models.DecimalField(max_digits=10, decimal_places=3)\n promo_tax = mod... | [
0
] | [] | [] | [
"django",
"django_admin",
"django_forms",
"python"
] | stackoverflow_0002636741_django_django_admin_django_forms_python.txt |
Q:
python logging question
I have a question about python standard logging mechanism. So if I use logging.config.fileConfig to load my configuration file, then I create loggers for some modules using logging.getLogger test them right after creation and they work. Now if I call logging.config.fileConfig again with the... | python logging question | I have a question about python standard logging mechanism. So if I use logging.config.fileConfig to load my configuration file, then I create loggers for some modules using logging.getLogger test them right after creation and they work. Now if I call logging.config.fileConfig again with the same configuration file and ... | [
"Config files are intended to completely replace the existing configuration with whatever is in the confguration - any loggers which are not named in the configuration, or children thereof, are disabled by fileConfig(), as documented here. you can prevent this disabling, but only on recent Python versions. It's not... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0006340743_python.txt |
Q:
Math and change field color
from django.db import models
from django.contrib.auth.models import User
class Product(models.Model):
name = models.CharField(max_length = 127)
description = models.TextField()
code = models.CharField(max_length = 30)
lot_no = models.CharField(max_length = 30)
inventory = models.Intege... | Math and change field color | from django.db import models
from django.contrib.auth.models import User
class Product(models.Model):
name = models.CharField(max_length = 127)
description = models.TextField()
code = models.CharField(max_length = 30)
lot_no = models.CharField(max_length = 30)
inventory = models.IntegerField()
commited = models.Intege... | [
"def colored_available(self):\n if self.reorder < self.available:\n return self.reorder\n return '<span style=\"color: red;\">%d</span>' % self.reorder\n\ncolored_available.allow_tags = True\ncolored_available.short_description = \"Available\"\n\nAnd this to your model admin (padmin):\nlist_display = ('... | [
0
] | [] | [] | [
"django_admin",
"python"
] | stackoverflow_0002114618_django_admin_python.txt |
Q:
Is it possible to create a 1million x 1 million matrix using numpy?
Possible Duplicate:
Python Numpy Very Large Matrices
I tried numpy.zeros((100k x 100k)) and it returned "array is too big".
Response to comments:
1) I could create 10k x 10k matrix but not 100kx100k and 1milx1mil.
2) The matrix is not sparse.
... | Is it possible to create a 1million x 1 million matrix using numpy? |
Possible Duplicate:
Python Numpy Very Large Matrices
I tried numpy.zeros((100k x 100k)) and it returned "array is too big".
Response to comments:
1) I could create 10k x 10k matrix but not 100kx100k and 1milx1mil.
2) The matrix is not sparse.
| [
"We can do simple maths to find out. A 1 million by 1 million matrix has 1,000,000,000,000 elements. If each element takes up 4 bytes, it would require 4,000,000,000,000 bytes of memory. That is, 3.64 terabytes.\nThere are also chances that a given implementation of Python uses more than that for a single number. F... | [
15,
5,
2
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0006338986_numpy_python.txt |
Q:
How to select not only the maximum of a `numpy.ndarray` but the top 3 maximal values in python?
I have a list of float values (positive and negative ones) stored in a variable row of type <type 'numpy.ndarray'>.
max_value = max(row)
gives me the maximal value of row. Is there an elegant way to select the top 3 (5... | How to select not only the maximum of a `numpy.ndarray` but the top 3 maximal values in python? | I have a list of float values (positive and negative ones) stored in a variable row of type <type 'numpy.ndarray'>.
max_value = max(row)
gives me the maximal value of row. Is there an elegant way to select the top 3 (5, 10,...) values?
I came up with
selecting the maximum value from row
deleting the maximal value in... | [
"I would use np.argsort\na = np.arange(10)\na[np.argsort(a)[-3:]]\n\nEDIT\nTo also get the position, just use:\nii = np.argsort(a)[-3:] # positions\nvals = a[ii] # values\n\n",
"Why not just sort the numpy array and then read off the values you need:\nIn [33]: np.sort(np.array([1,5,4,6,7,2,3,9]))[-3:]\... | [
9,
2,
1
] | [] | [] | [
"max",
"numpy",
"python",
"select"
] | stackoverflow_0006256178_max_numpy_python_select.txt |
Q:
Matching two grids for data analysis, is there a good algorithm for my problem?
I'd like to compare two differently spaced datasets in python. I always want to find the closest (nearest neighbour) match and regrid the data, see this example:
Dataset A:
ALTITUDE[m] VALUE
1. a1
2. a2
3. ... | Matching two grids for data analysis, is there a good algorithm for my problem? | I'd like to compare two differently spaced datasets in python. I always want to find the closest (nearest neighbour) match and regrid the data, see this example:
Dataset A:
ALTITUDE[m] VALUE
1. a1
2. a2
3. a3
4. a4
Dataset B:
ALTITUDE[m] VALUE
0.7 b1
0.9 ... | [
"Two assumptions:\n1: You are not looking for the nearest neighbour, but for all altitudes within some range. So, let's say for a1 you want all bn that are within 0.5 of a1 (giving you b1 and b2 as per your example). I would define the 'nearest neighbour' as something different.\n2: You don't count nan in your medi... | [
2,
1,
1,
1,
0
] | [] | [] | [
"comparison",
"dataset",
"numpy",
"python",
"scipy"
] | stackoverflow_0006307159_comparison_dataset_numpy_python_scipy.txt |
Q:
Making a Foreign Key to an option of two different classes in Django
So, basically, I'm wondering if it's possible to make a ForiegnKey in Django potentially point to a choice of two objects. Not actually.
Eg:
class Car(models.Model):
pass
class Truck(models.Model):
pass
class NumberPlate(models.Model):
... | Making a Foreign Key to an option of two different classes in Django | So, basically, I'm wondering if it's possible to make a ForiegnKey in Django potentially point to a choice of two objects. Not actually.
Eg:
class Car(models.Model):
pass
class Truck(models.Model):
pass
class NumberPlate(models.Model):
vehicle = models.ForeignKey(Car or Truck)
I know in this example, the... | [
"It would probably be best to use a Generic Relation a NumberPlate can then be attached to any content type e.g\ncontent_type = models.ForeignKey(ContentType)\nobject_id = models.PositiveIntegerField()\ncontent_object = generic.GenericForeignKey('content_type', 'object_id')\n\n",
"You can use model inheritance to... | [
4,
0
] | [] | [] | [
"django",
"python",
"sql"
] | stackoverflow_0006341924_django_python_sql.txt |
Q:
numbering of members of a sequence
I need additional python codes that will number the left column of the output below like I have shown in the right column: The codes here just divides the sequence into 3s.
Now I want to number them from 1 to the last as I have done manually in the right column.
cds = "atgagtgaa... | numbering of members of a sequence | I need additional python codes that will number the left column of the output below like I have shown in the right column: The codes here just divides the sequence into 3s.
Now I want to number them from 1 to the last as I have done manually in the right column.
cds = "atgagtgaacgtctgagcattaccccgctggggccgtatatcggcgcac... | [
"cds = \"atgagtgaacgtctgagcattaccccgctggggccgtatatcggcgcacaataa\"\n\nfor num, i in enumerate(range(0,len(cds),3)):\n print cds[i:i+3], num + 1\n\n",
"Not sure that this is what you want, but:\ncds = \"atgagtgaacgtctgagcattaccccgctggggccgtatatcggcgcacaataa\"\nfor data in ((i+1, cds[i:i+3], i+1) for i in xrange(... | [
3,
1,
0,
0
] | [] | [] | [
"numbers",
"python",
"sequence"
] | stackoverflow_0006341553_numbers_python_sequence.txt |
Q:
piping together several subprocesses
I have 5 processes p1,p2,...,p5 where I want to write some data to stdin of p1, pipe p1 output to p2 stdin and finally read the final result from output of p5.
What I have tried so far:
p1 = Popen(['p1'], stdin=PIPE, stdout=PIPE)
p2 = Popen(['p2'], stdin=p1.stdout, stdout=PIPE)... | piping together several subprocesses | I have 5 processes p1,p2,...,p5 where I want to write some data to stdin of p1, pipe p1 output to p2 stdin and finally read the final result from output of p5.
What I have tried so far:
p1 = Popen(['p1'], stdin=PIPE, stdout=PIPE)
p2 = Popen(['p2'], stdin=p1.stdout, stdout=PIPE)
...
p5 = Popen(['p5'], stdin=p4.stdout, s... | [
"Maybe this can help:\nimport sys\nimport tempfile\nfrom subprocess import Popen, PIPE\n\n\ncmd = [sys.executable, '-c', 'print raw_input()']\n\n# Using a temp file to give input data to the subprocess instead of stdin.write to avoid deadlocks.\nwith tempfile.TemporaryFile() as f:\n f.write('foobar')\n f.seek... | [
10
] | [] | [] | [
"pipe",
"python"
] | stackoverflow_0006341451_pipe_python.txt |
Q:
Python - Datetime's Time is always zero
Strange little problem I'm facing with Datetime. Here's what I'm doing:
>>> from datetime import datetime, date
>>> t = date.timetuple(datetime.now())
>>> t
time.struct_time(tm_year=2011, tm_mon=6, tm_mday=14, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=165, tm_isdst=-... | Python - Datetime's Time is always zero | Strange little problem I'm facing with Datetime. Here's what I'm doing:
>>> from datetime import datetime, date
>>> t = date.timetuple(datetime.now())
>>> t
time.struct_time(tm_year=2011, tm_mon=6, tm_mday=14, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=165, tm_isdst=-1)
tm_hour, tm_min and tm_sec are all zero. ... | [
"Well t is a date, so of course it doesn't contain any time data. You have to use datetime.timetuple(datetime.now()) to have those fields populated.\n",
"I have tried this in my console and get the following results:\nfrom datetime import datetime, date\n\ndate.timetuple(datetime.now())\n>>> time.struct_time(tm_y... | [
5,
1,
1,
0
] | [] | [] | [
"datetime",
"python",
"time"
] | stackoverflow_0006342102_datetime_python_time.txt |
Q:
How to use C++ optimization flags in SWIG?
I am creating a python module that is implemented in C++. I am using SWIG to create the interface. There are various ways to create the extension, I'm using the "preferred approach," which is via python's distutils and which is described here. The name of my module is ... | How to use C++ optimization flags in SWIG? | I am creating a python module that is implemented in C++. I am using SWIG to create the interface. There are various ways to create the extension, I'm using the "preferred approach," which is via python's distutils and which is described here. The name of my module is "ParseEvents," and to compile it I run the follo... | [
"The GCC doc explicitly says:\nhttp://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Optimize-Options.html\nIf you use multiple -O options, with or without level numbers, the last such option is the one that is effective.\nThis means your code will be compiled with -O3 in effect, just as you want it. No need to bother for du... | [
3,
0
] | [] | [] | [
"c++",
"python",
"swig"
] | stackoverflow_0006340775_c++_python_swig.txt |
Q:
How to convert list of lists (tuples) to string in python with nice delimiters
What is the best way to convert list of lists/tuples to string with incremental indents.
So far I've ended up with such a function
def a2s(a, inc = 0):
inc += 1
sep = ' ' * inc
if type(a) == type(list()) or type(a) == type(t... | How to convert list of lists (tuples) to string in python with nice delimiters | What is the best way to convert list of lists/tuples to string with incremental indents.
So far I've ended up with such a function
def a2s(a, inc = 0):
inc += 1
sep = ' ' * inc
if type(a) == type(list()) or type(a) == type(tuple()):
a = sep.join(map(a2s, a))
else:
a = str(a)
return a
... | [
"Here is what you need:\nimport collections\n\ndef a2s(a):\n res = ''\n if isinstance(a, collections.Iterable):\n for item in a:\n res += str(a2s(item)) + ' '\n else:\n res = str(a)\n return res\n\nUsage:\na = [ [1, 2], [3, 4] ]\nprint(a2s(a))\n>>> 1 2 3 4\n\nRecursion rocks! ... | [
0,
0
] | [] | [] | [
"map",
"python",
"recursion"
] | stackoverflow_0006342286_map_python_recursion.txt |
Q:
programs paralyzing each other on the server (c++ with openMP and python)
I have an urgent problem because my time is running out: I let my calculations process on a server with 8 cores therefore I'm using openMP in my c++ code and it works fine. Of course I'm not the only one who is using the server, so my capaci... | programs paralyzing each other on the server (c++ with openMP and python) | I have an urgent problem because my time is running out: I let my calculations process on a server with 8 cores therefore I'm using openMP in my c++ code and it works fine. Of course I'm not the only one who is using the server, so my capacity is not always 800%CPU.
But it happened now several times that someone who s... | [
"There can be a number of reasons for this, for example:\n\nIncreased failure rate in the branch prediction\nExhausted CPU cache\nFilled up the memory bus\nToo much context switching (this have an effect on many things, including all the previous points)\n\n",
"As Emil Vikström listed, there are several reasons w... | [
5,
0
] | [] | [] | [
"c++",
"openmp",
"python"
] | stackoverflow_0006289668_c++_openmp_python.txt |
Q:
How to create regular expression for domain name?
I need to look if the string has less than 256 characters, and has at least one "." (dot) in it, that's all.
Please help me..
A:
What you asked is
len(s) < 256 and '.' in s
| How to create regular expression for domain name? | I need to look if the string has less than 256 characters, and has at least one "." (dot) in it, that's all.
Please help me..
| [
"What you asked is\nlen(s) < 256 and '.' in s\n\n"
] | [
13
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006342931_python_regex.txt |
Q:
How do you return an object from python to QML?
I'm trying to return a QObject from a Slot. I'm using PySide and QML. My code looks like this:
class myClass(QtCore.QObject):
def __init__(self):
self.object = QtCore.QObject()
QtCore.Slot(result=object)
def myFunc(self):
return self.ob... | How do you return an object from python to QML? | I'm trying to return a QObject from a Slot. I'm using PySide and QML. My code looks like this:
class myClass(QtCore.QObject):
def __init__(self):
self.object = QtCore.QObject()
QtCore.Slot(result=object)
def myFunc(self):
return self.object
When I console.log the return value I get:
QVar... | [
"So, here is something that does what I think you're trying to do. When you click anywhere, the blue area changes green. This is done by changing the color property on the object that is passed by a signal.\n#!/usr/bin/env python\n\nimport sys\nfrom PySide import QtCore\nfrom PySide.QtGui import QApplication\nfrom ... | [
2
] | [] | [] | [
"pyside",
"python",
"qml",
"return",
"signals_slots"
] | stackoverflow_0005267006_pyside_python_qml_return_signals_slots.txt |
Q:
Add custom html between two model fields in Django admin's change_form
Let's say I've two models:
class Book(models.Model):
name = models.CharField(max_length=50)
library = models.ForeignKeyField('Library')
class Library(models.Model):
name = models.CharField(max_length=50)
address = models.Cha... | Add custom html between two model fields in Django admin's change_form | Let's say I've two models:
class Book(models.Model):
name = models.CharField(max_length=50)
library = models.ForeignKeyField('Library')
class Library(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=50)
tel = models.CharField(max_length=50)
Is ther... | [
"models.py:\nclass Library(models.Model):\n name = models.CharField(max_length=50) \n address = models.CharField(max_length=50) \n tel = models.CharField(max_length=50)\n\n def book_count(self):\n return self.book_set.count()\n\nadmin.py:\nclass LibraryAdmin(admin.ModelAdmin): \n fieldsets = ... | [
11,
3,
2
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0006239966_django_django_admin_python.txt |
Q:
establish connection with multiple servers simultaneously using python paramiko package
I want to transfer files from say server A to server B directly. The script performing this operation is residing on some other server say C. How can it be achieved without being saving files temporarily on server C or local sy... | establish connection with multiple servers simultaneously using python paramiko package | I want to transfer files from say server A to server B directly. The script performing this operation is residing on some other server say C. How can it be achieved without being saving files temporarily on server C or local system..
| [
"Create ssh key pairs for each server, use ssh-copy-id to copy public keys from server A to Server B, and from Server C to Server A.\nAll you have to do then is to tell your script to ssh to remote server A and then execute scp to copy files over to Server B.\nEdit: You have to setup your ssh keys without a passphr... | [
1
] | [] | [] | [
"paramiko",
"python"
] | stackoverflow_0006333590_paramiko_python.txt |
Q:
What does this command actually do in django?
What does this actually do, & what is the default superuser account that is created ?
./manage.py runscript -v 2 create_superuser
A:
assuming you have run syncdb, and django.contrib.auth is among your apps, this will create a user that has the 'superuser' bit set. ... | What does this command actually do in django? | What does this actually do, & what is the default superuser account that is created ?
./manage.py runscript -v 2 create_superuser
| [
"assuming you have run syncdb, and django.contrib.auth is among your apps, this will create a user that has the 'superuser' bit set. Such a user implicitly has all permissions, and most usefully, can always log into the admin interface for your project. You might want to do this if you enable auth sometime later ... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006343603_django_python.txt |
Q:
Mongokit - Find Last Added Record
Using Mongokit with Python. Having some trouble working out get the last n number of records. Not sure of the syntax Python wants here exactly, but I have:
record = collection.find(sort = [{'timestamp': DESCENDING}],limit=10)
Which gives me the error:
Traceback (most recent call ... | Mongokit - Find Last Added Record | Using Mongokit with Python. Having some trouble working out get the last n number of records. Not sure of the syntax Python wants here exactly, but I have:
record = collection.find(sort = [{'timestamp': DESCENDING}],limit=10)
Which gives me the error:
Traceback (most recent call last):
File "C:\Python26\lib\site-pac... | [
"You should give it a [(field, direction), ...] list, not a dict.\nSorting specifications must necessarily be ordered; dicts are not ordered.\nNot sure that you need to use a list, try just (field, direction).\n"
] | [
1
] | [] | [] | [
"mongokit",
"python"
] | stackoverflow_0006342982_mongokit_python.txt |
Q:
How to initialize LDA with a set of seed words using gensim package
I have read several papers in which they actually initialize parameteres using a seed set of words for LDA. does anyone know how is this possible in gensim package?
A:
For the sake of completeness, copy&paste from the gensim mailing list reply:
... | How to initialize LDA with a set of seed words using gensim package | I have read several papers in which they actually initialize parameteres using a seed set of words for LDA. does anyone know how is this possible in gensim package?
| [
"For the sake of completeness, copy&paste from the gensim mailing list reply:\n\nSeeding with existing documents was a part of gensim some versions \n back, in the code that was directly ported from LDA-C. It was meant to \n improve convergence (although the final, converged result was the \n same).\nIn recent v... | [
3
] | [] | [] | [
"gensim",
"python"
] | stackoverflow_0005497235_gensim_python.txt |
Q:
Is it possible to perform model methods in a template?
I have a model which has a method called 'has_voted'. It looks like this...
def has_voted(self, user):
# code to find out if user is in a recordset, returns a boolean
Is it possible to perform this method inside a template? Something like object.has_vote(... | Is it possible to perform model methods in a template? | I have a model which has a method called 'has_voted'. It looks like this...
def has_voted(self, user):
# code to find out if user is in a recordset, returns a boolean
Is it possible to perform this method inside a template? Something like object.has_vote(user)?
| [
"You can only call methods with no parameters. So {{ object.has_voted }} would be OK, if the method was defined simply as has_voted(self), but as you've shown it would not be.\nThe best way to pass a parameter to a method is to define a simple template filter.\n@register.filter\ndef has_voted(obj, user):\n retur... | [
2,
0
] | [] | [] | [
"django",
"methods",
"python",
"view"
] | stackoverflow_0006344456_django_methods_python_view.txt |
Q:
using functions to move an object in the GUI
Please I have a problem with Python functions and return.
from graphics import*
win = GraphWin('Me',640,160)
mylist=[]
def move_ob(ob):
ob.move(4,0)
return ob
def circle():
for x in range (10,200,10):
for y in range (10,200,10):
c =Cir... | using functions to move an object in the GUI | Please I have a problem with Python functions and return.
from graphics import*
win = GraphWin('Me',640,160)
mylist=[]
def move_ob(ob):
ob.move(4,0)
return ob
def circle():
for x in range (10,200,10):
for y in range (10,200,10):
c =Circle (Point(x,y),5)
c.draw(win)
... | [
"You are passing in mylist, which is a list. Lists have no idea what move is.\nI assume you want to move all the circles in the list. Therefore, you might want:\nfor circleObject in mylist:\n move_ob(circle)\n\nRather than move_ob(mylist).\n"
] | [
4
] | [] | [] | [
"python",
"python_3.x",
"user_interface"
] | stackoverflow_0006345235_python_python_3.x_user_interface.txt |
Q:
regex not matching
I am write a small python script to gather some data from a database, the only problem is when I export data as XML from mysql it includes a \b character in the XML file. I wrote code to remove it, but then realized I didn't need to do that processing everytime, so I put it in a method and am ca... | regex not matching | I am write a small python script to gather some data from a database, the only problem is when I export data as XML from mysql it includes a \b character in the XML file. I wrote code to remove it, but then realized I didn't need to do that processing everytime, so I put it in a method and am calling it I find a \b in ... | [
"\\b is a flag for the regular expression engine:\n\nMatches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of alphanumeric or underscore characters, so the end of a word is indicated by whitespace or a non-alphanumeric, non-underscore character. Note that \\b is defin... | [
7,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006344709_python_regex.txt |
Q:
Scraping ASP.net website: Need to Page through a Gridview using Python Mechanize
I'm trying to scrape an asp.net page where I need to page through the items a list of items that are in a gridview control. I've never used asp.net but have been searching the Net for pointers but now I've hit a brick wall. The page l... | Scraping ASP.net website: Need to Page through a Gridview using Python Mechanize | I'm trying to scrape an asp.net page where I need to page through the items a list of items that are in a gridview control. I've never used asp.net but have been searching the Net for pointers but now I've hit a brick wall. The page links are of the form:
javascript:__doPostBack('ctl00$ctl00$ctl00$ContentPlaceHolderEve... | [
"Managed to to it by building an xmlhttprequest per the answer here:\nUsing Python and Mechanize to submit form data and authenticate\n"
] | [
1
] | [] | [] | [
"asp.net",
"gridview",
"mechanize",
"python",
"screen_scraping"
] | stackoverflow_0006332558_asp.net_gridview_mechanize_python_screen_scraping.txt |
Q:
What's the best way to initialise and use constants across Python classes?
Here's how I am declaring constants and using them across different Python classes:
# project/constants.py
GOOD = 1
BAD = 2
AWFUL = 3
# project/question.py
from constants import AWFUL, BAD, GOOD
class Question:
def __init__(self):
... | What's the best way to initialise and use constants across Python classes? | Here's how I am declaring constants and using them across different Python classes:
# project/constants.py
GOOD = 1
BAD = 2
AWFUL = 3
# project/question.py
from constants import AWFUL, BAD, GOOD
class Question:
def __init__(self):
...
Is the above a good way to store and use contant values? I realise th... | [
"why not just use\nimport constants\n\ndef use_my_constants():\n print constants.GOOD, constants.BAD, constants.AWFUL\n\nFrom the python zen:\n\nNamespaces are good. Lets do more of those!\n\nEDIT: Except, when you do quote, you should include a reference and check it, because as others have pointed out, it shou... | [
81,
15,
4,
3
] | [] | [] | [
"python"
] | stackoverflow_0006345840_python.txt |
Q:
Translating Perl to Python
I found this Perl script while migrating my SQLite database to mysql
I was wondering (since I don't know Perl) how could one rewrite this in Python?
Bonus points for the shortest (code) answer :)
edit: sorry I meant shortest code, not strictly shortest answer
#! /usr/bin/perl
while ($li... | Translating Perl to Python | I found this Perl script while migrating my SQLite database to mysql
I was wondering (since I don't know Perl) how could one rewrite this in Python?
Bonus points for the shortest (code) answer :)
edit: sorry I meant shortest code, not strictly shortest answer
#! /usr/bin/perl
while ($line = <>){
if (($line !~ /BE... | [
"Here's a pretty literal translation with just the minimum of obvious style changes (putting all code into a function, using string rather than re operations where possible).\nimport re, fileinput\n\ndef main():\n for line in fileinput.input():\n process = False\n for nope in ('BEGIN TRANSACTION','COMMIT',\n... | [
54,
12,
8,
8,
3,
3,
3,
1
] | [] | [] | [
"perl",
"python",
"rewrite"
] | stackoverflow_0001067060_perl_python_rewrite.txt |
Q:
Python--When is timedelta object processed?
I have the following Django model:
created=models.DateTimeField(auto_now_add=True)
I now need a model object method which shows the # of hours since creation. I tried the following:
def hours_live(self):
diff=((datetime.datetime.now - self.created).seconds)/36... | Python--When is timedelta object processed? | I have the following Django model:
created=models.DateTimeField(auto_now_add=True)
I now need a model object method which shows the # of hours since creation. I tried the following:
def hours_live(self):
diff=((datetime.datetime.now - self.created).seconds)/3600
return diff
but it threw a TypeError
u... | [
"datetime.datetime.now is a method. When you call it without parentheses, you are referring to the method itself, and you can't subtract a time from a method. When you call it with parentheses, you are calling the method, getting the return value, and then using that for subtraction.\n",
"In your example, it will... | [
6,
5,
3
] | [] | [] | [
"datetime",
"django",
"python"
] | stackoverflow_0006345686_datetime_django_python.txt |
Q:
Databases for running statistical tests
I am trying to apply knowledge i learnt during statistics courses to real world datasets.
I am looking for some real database/tables. Would be helpful if the link to page added as well . Format is not a constraint - i use python and i can well convert to sqlite .
One exam... | Databases for running statistical tests | I am trying to apply knowledge i learnt during statistics courses to real world datasets.
I am looking for some real database/tables. Would be helpful if the link to page added as well . Format is not a constraint - i use python and i can well convert to sqlite .
One example would be [one medium sized table] of for ... | [
"Well, since your profile says you're from India, I thought some Indian Government statistics would help, so a quick google search yields this site:\nhttp://mospi.nic.in/dwh/index.htm\nClick on 'Tables', and you'll have a list of more data/tables than you could possibly need.\n...these files all seem to be in Micro... | [
1
] | [] | [] | [
"database",
"python"
] | stackoverflow_0006346542_database_python.txt |
Q:
Invalid Request in Google Safe-Browsing Lookup API
I am trying to send a request to the Google Safe browsing Lookup API. It asks the user for a for a url for which he wants to do the look up. However there is some problem with the way I am sending the request because it keeps replying with Error Code 400. Kindly h... | Invalid Request in Google Safe-Browsing Lookup API | I am trying to send a request to the Google Safe browsing Lookup API. It asks the user for a for a url for which he wants to do the look up. However there is some problem with the way I am sending the request because it keeps replying with Error Code 400. Kindly help.
import urllib
import urllib2
from google.appengine.... | [
"You don't seem to be following the protocol for either the GET or POST method, but are doing something inbetween by passing what should be the GET params via POST.\nTry this method:\nimport urllib\nfrom google.appengine.api import urlfetch\n\ndef safe_browsing(url):\n \"\"\"Returns True if url is safe or False ... | [
1
] | [] | [] | [
"google_app_engine",
"python",
"safe_browsing"
] | stackoverflow_0006342782_google_app_engine_python_safe_browsing.txt |
Q:
Seems like python is partial
The following is a function I created, and put it in a file called last_function.py
from tkinter import*
def new_gui(app,sound_file,mixer):
track=mixer.Sound(sound_file)
def track_toggle():
if ballCheckbutton.get()==1:
track.play(loops=-1)
else:
... | Seems like python is partial | The following is a function I created, and put it in a file called last_function.py
from tkinter import*
def new_gui(app,sound_file,mixer):
track=mixer.Sound(sound_file)
def track_toggle():
if ballCheckbutton.get()==1:
track.play(loops=-1)
else:
track.stop()
ball... | [
"\n1> Why can't i remove from tkinter\n import* from the last_function file..\n cause anyway it's got that on the top\n of the file that's calling it\n right.Why do i get an error saying\n IntVar() not defined\n\nThe Python \"import\" follows the same scoping rules as the rest of the Python language. By \"impo... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0006346736_python.txt |
Q:
Neural Networks in Python without using any readymade libraries...i.e., from first principles..help!
I am trying to learn programming in python and am also working against a deadline for setting up a neural network which looks like it's going to feature multidirectional associative memory and recurrent connections... | Neural Networks in Python without using any readymade libraries...i.e., from first principles..help! | I am trying to learn programming in python and am also working against a deadline for setting up a neural network which looks like it's going to feature multidirectional associative memory and recurrent connections among other things. While the mathematics for all these things can be accessed from various texts and sou... | [
"If you're familiar with Matlab, check out the excellent Python libraries numpy, scipy, and matplotlib. Together, they provide the most commonly used subset of Matlab functions.\n",
"You might be interested in Neurolab - neural networks in Python with an API like the Neural Networks Toolbox from MATLAB\n",
"I d... | [
4,
2,
1
] | [] | [] | [
"neural_network",
"python",
"scipy"
] | stackoverflow_0001698017_neural_network_python_scipy.txt |
Q:
Keeping a pipe to a process open
I have an app that reads in stuff from stdin and returns, after a newline, results to stdout
A simple (stupid) example:
$ app
Expand[(x+1)^2]<CR>
x^2 + 2*x + 1
100 - 4<CR>
96
Opening and closing the app requires a lot of initialization and clean-up (its an interface to a Computer ... | Keeping a pipe to a process open | I have an app that reads in stuff from stdin and returns, after a newline, results to stdout
A simple (stupid) example:
$ app
Expand[(x+1)^2]<CR>
x^2 + 2*x + 1
100 - 4<CR>
96
Opening and closing the app requires a lot of initialization and clean-up (its an interface to a Computer Algebra System), so I want to keep thi... | [
"Using subprocess, you can't do this reliably. You might want to look at using the pexpect library. That won't work on Windows - if you're on Windows, try winpexpect.\nAlso, if you're trying to do mathematical stuff in Python, check out SAGE. They do a lot of work on interfacing with other open-source maths softwar... | [
3,
2
] | [] | [] | [
"pipe",
"popen",
"python",
"subprocess"
] | stackoverflow_0006346650_pipe_popen_python_subprocess.txt |
Q:
Duplicate django objects with ManyToManyFields
I use Django and I have some objects with ManyToManyFields. I'd like to duplicate these objects.
I've found 'deepcopy' which works almost perfectly.
>>> e = Equipement.objects.get(pk=568)
>>> ee = deepcopy(e)
>>> ee.connexion.all()
[<Connexion: COMETE - Proxyweb>]
>>>... | Duplicate django objects with ManyToManyFields | I use Django and I have some objects with ManyToManyFields. I'd like to duplicate these objects.
I've found 'deepcopy' which works almost perfectly.
>>> e = Equipement.objects.get(pk=568)
>>> ee = deepcopy(e)
>>> ee.connexion.all()
[<Connexion: COMETE - Proxyweb>]
>>> ee.id=None
>>> ee.save()
>>> ee.connexion.all()
[]
... | [
"Just add them using the old object:\nee = deepcopy(e)\nee.id=None\nee.save()\nee.connexion.add(*e.connexion.all())\n\n"
] | [
6
] | [] | [] | [
"django",
"duplicates",
"manytomanyfield",
"python"
] | stackoverflow_0006346600_django_duplicates_manytomanyfield_python.txt |
Q:
Editing single line in a file using python. Last part of new file is missing
I am trying to edit a single line in a povray file using python.
The file starts out like so:
camera {
angle 38
location <500,0,0>
right x*image_width/image_height
look_at <0,0,0>
rotate <0,0,0>
}
and I want to edit the variables d... | Editing single line in a file using python. Last part of new file is missing | I am trying to edit a single line in a povray file using python.
The file starts out like so:
camera {
angle 38
location <500,0,0>
right x*image_width/image_height
look_at <0,0,0>
rotate <0,0,0>
}
and I want to edit the variables described in the file so it comes out like this:
camera {
angle 38
location <1000... | [
"Either flush or close the temporary file before copying to be certain that all output has been written to disk.\n"
] | [
7
] | [] | [] | [
"file",
"python"
] | stackoverflow_0006347494_file_python.txt |
Q:
Is it possible to import to the global scope from inside a function (Python)?
I am trying to import a module from inside a function and have it be available to my whole file the same way it would be if I imported outside any functions and before all the other code. The reason it is in a function is because I don't... | Is it possible to import to the global scope from inside a function (Python)? | I am trying to import a module from inside a function and have it be available to my whole file the same way it would be if I imported outside any functions and before all the other code. The reason it is in a function is because I don't have much control over the structure of the script. Is this possible without resor... | [
"Seeing your new comments, I want to emphasize that this sounds unnecessary. You're actually modifying the script more by importing within a function than by importing at the top of the script in the normal way. Still, in the spirit of answering the question asked, I'm leaving my previous answer. \n\nI'm honestly n... | [
9,
9
] | [] | [] | [
"global",
"import",
"python"
] | stackoverflow_0006347588_global_import_python.txt |
Q:
Python regex strange behavior
I've discovered something that I can't explain in Python re module.
Compilation of (a*)* or (a*|b)* throws an error:
raise error, v # invalid expression
sre_constants.error: nothing to repeat
I've tested this regexp in javascript and it seems to be ok.
Is it a bug?
A:
Yes, it's ... | Python regex strange behavior | I've discovered something that I can't explain in Python re module.
Compilation of (a*)* or (a*|b)* throws an error:
raise error, v # invalid expression
sre_constants.error: nothing to repeat
I've tested this regexp in javascript and it seems to be ok.
Is it a bug?
| [
"Yes, it's a bug (or at least a misfeature). It's complaining that if a* matches nothing, it doesn't know how to capture 0 or more \"nothings\".\n",
"A bug in Python.\nhttp://bugs.python.org/issue2537\nhttp://bugs.python.org/issue214033\nMaybe a \"bug\" is not the correct word here. Different kind of interpretati... | [
9,
5,
5,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0005869650_python_regex.txt |
Q:
dealing with subprocess that floods stdout
I'm dealing with subprocess that occasionally goes into infinite loop and floods stdout with garbage. I generally need to capture stdout, except for those cases.
This discussion gives a way to limit the amount of time a subprocess takes, but the problem is that for a reas... | dealing with subprocess that floods stdout | I'm dealing with subprocess that occasionally goes into infinite loop and floods stdout with garbage. I generally need to capture stdout, except for those cases.
This discussion gives a way to limit the amount of time a subprocess takes, but the problem is that for a reasonable timeout it can produce GB's of output bef... | [
"If you can't detect when the flooding occurs, chances are nobody else can. Since you do the capturing, you are of course free to limit your capturing, but that requires that you know when the looping has occured.\nPerhaps you can use rate-limiting, if the \"regular\" rate is lower than the one observed when the sp... | [
1,
1
] | [] | [] | [
"python",
"stdout",
"subprocess"
] | stackoverflow_0006347630_python_stdout_subprocess.txt |
Q:
Python icmpv6 client
I'm working on a simple icmpv6 client, and i have some problem with checksum
here is the code, wireshark shows that checksum is not set correctly,
the traceback shows an error like pcs.FieldBoundsError: 'Value must be between 0 and 65535'
import pcs, sys
from socket import *
from pcs.packets... | Python icmpv6 client | I'm working on a simple icmpv6 client, and i have some problem with checksum
here is the code, wireshark shows that checksum is not set correctly,
the traceback shows an error like pcs.FieldBoundsError: 'Value must be between 0 and 65535'
import pcs, sys
from socket import *
from pcs.packets.ethernet import *
from pc... | [
"This seems to be related to a bug in python-pcs that causes incorrect checksum calculation. Clipping the errornous bits should work:\ncs = icmp6.cksum(ip6) & 0xffff\n\n"
] | [
1
] | [] | [] | [
"network_protocols",
"packet_construction_set",
"python"
] | stackoverflow_0006347115_network_protocols_packet_construction_set_python.txt |
Q:
Overwriting XML file
I am trying to parse an XML file using elementtree. The XML file I am trying to read however got exported from MySql and when the XML file is created if I have an entry in the database like: c:cygwin\bin it translates the '\b' as a backspace. Anyway I am trying to delete all the entries of '\b... | Overwriting XML file | I am trying to parse an XML file using elementtree. The XML file I am trying to read however got exported from MySql and when the XML file is created if I have an entry in the database like: c:cygwin\bin it translates the '\b' as a backspace. Anyway I am trying to delete all the entries of '\b' from the XML file so I c... | [
"I figured out the problem, I was using p.match to look for matches of '\\b' when I really needed to be using p.search, p.match only looks from the beginning of the line, search looks for occurences throughout the entire line.\nSolution:\ndef preprocess(file):\n #exporting from MySQL query browser adds a weird\n... | [
1
] | [] | [] | [
"elementtree",
"parsing",
"python",
"xml"
] | stackoverflow_0006347019_elementtree_parsing_python_xml.txt |
Q:
Can I dynamically load an executable on linux?
I wrote a little testing framework that uses 'nm' to inspect shared libraries and look for test functions. I then use Python's ctypes library to dynamically load the shared object and execute the test functions. Is there a way to do this with an executable? When I tri... | Can I dynamically load an executable on linux? | I wrote a little testing framework that uses 'nm' to inspect shared libraries and look for test functions. I then use Python's ctypes library to dynamically load the shared object and execute the test functions. Is there a way to do this with an executable? When I tried the same trick on an executable module Python rep... | [
"If this is your own application you could rearrange the build so your executable is only main() { real_main(); } and real_main() is in libapp.so. Then you could test libapp.so with your existing code.\nIf it's possible to load another executable it probably involves loading ld.so and getting it to do the work. I... | [
3,
1
] | [] | [] | [
"c",
"dynamic_linking",
"linux",
"python"
] | stackoverflow_0006346757_c_dynamic_linking_linux_python.txt |
Q:
Python: retrieve all properties of a class instance that uses the @property annotation
Is there an easy way to retrieve all properties of a class instance that use @property or property methods?
I have seen examples that use vars but that does not work a class like:
class Test(object):
CONSTANT='SKIP ME'
... | Python: retrieve all properties of a class instance that uses the @property annotation | Is there an easy way to retrieve all properties of a class instance that use @property or property methods?
I have seen examples that use vars but that does not work a class like:
class Test(object):
CONSTANT='SKIP ME'
def __init__(self):
self.my = "my"
self.__wrapper = {Test.CONSTANT : "wrapped ... | [
"A simple solution would be this:\ninstance = Test()\ndict((p, getattr(instance, p))\n for p in dir(instance)\n if p not in dir(Test) or isinstance(getattr(Test, p), property))\n\nIt yields: \n{'_Test__wrapper': {'SKIP ME': 'wrapped value'}, 'wrapped_value': 'wrapped value', 'my': 'my'}\n\n",
"property is... | [
4,
4,
1
] | [] | [] | [
"python",
"python_2.7"
] | stackoverflow_0006347651_python_python_2.7.txt |
Q:
TypeError:'int' object is not iterable when I try to iterate through my inner loop?
I am not sure what the problem is with my loop structure. Maybe it's a naming problem since the count variable and SubElement names use the same variable. Any help is appreciated.
from xml.etree import ElementTree as ET
root = ET.... | TypeError:'int' object is not iterable when I try to iterate through my inner loop? | I am not sure what the problem is with my loop structure. Maybe it's a naming problem since the count variable and SubElement names use the same variable. Any help is appreciated.
from xml.etree import ElementTree as ET
root = ET.Element("painter")
root.set('version', '1.0')
linenum = 0
pointnum = 0
smpl_data = [[[20... | [
"You probably want\nfor pointnum in range(linenum):\n\nThat is, all the numbers from zero to one less than linenum\n",
"linenum is not iterable. It's hard to tell what you are trying to do here, but perhaps for pointnum in smpl_data[linenum]: would be what you want?\n"
] | [
3,
1
] | [] | [] | [
"elementtree",
"python",
"xml"
] | stackoverflow_0006347948_elementtree_python_xml.txt |
Q:
How can I change this script to also include a rename functionality?
I have the current script included below that goes into a file with extension .las and replaces certain strings with others (ie.: cat -> kitten, dog -> puppy).
All I want is to add in a functionality into this script that would rename ANY .las fi... | How can I change this script to also include a rename functionality? | I have the current script included below that goes into a file with extension .las and replaces certain strings with others (ie.: cat -> kitten, dog -> puppy).
All I want is to add in a functionality into this script that would rename ANY .las file to a certain name in the current directory when I run the script (ie.: ... | [
"If you want to end up with a single file named animals.las containing the contents of *.las, then you can change the scanFiles function to open animals.las at the start of the loop, write the translated output of each *.las file to animals.las, and then close animals.las:\ndef scanFiles(dir): \n fout = open(\"a... | [
2
] | [] | [] | [
"python",
"rename",
"wildcard"
] | stackoverflow_0006347870_python_rename_wildcard.txt |
Q:
In Python, how can I include (not import) one file within another file, macro style, without changing namespace?
First I do know about 'import'. When I try 'import' it doesn't work. What I'm trying to do is split a single module into two parts, one of which is editable by a group and the other of which is not. ... | In Python, how can I include (not import) one file within another file, macro style, without changing namespace? | First I do know about 'import'. When I try 'import' it doesn't work. What I'm trying to do is split a single module into two parts, one of which is editable by a group and the other of which is not. I want the group to write well-defined 'retrieval functions' without the temptation or ability to edit the backend cod... | [
"This can be done with execfile(), but you should consider using some other mechanism for this instead such as polymorphism or plugins.\n"
] | [
6
] | [] | [] | [
"include",
"macros",
"python"
] | stackoverflow_0006348166_include_macros_python.txt |
Q:
Overlaying a scatter plot on background image and changing axes ranges
I have a set of x,y map coordinates that I want plotted on an background image of the map.
I use the following code to display my map:
import matplotlib.pyplot as plt
im=plt.imread('map.gif')
implot=plt.imshow(im,origin='lower')
Now the ranges... | Overlaying a scatter plot on background image and changing axes ranges | I have a set of x,y map coordinates that I want plotted on an background image of the map.
I use the following code to display my map:
import matplotlib.pyplot as plt
im=plt.imread('map.gif')
implot=plt.imshow(im,origin='lower')
Now the ranges for the x and y axes are the pixel values of the image. In my case, these a... | [
"The following code, from the matplotlib site, shows a plot that goes from -3 to 3, check it out:\n#!/usr/bin/env python\nimport numpy as np\nimport matplotlib.cm as cm\nimport matplotlib.mlab as mlab\nimport matplotlib.pyplot as plt\n\ndelta = 0.025\nx = y = np.arange(-3.0, 3.0, delta)\nX, Y = np.meshgrid(x, y)\nZ... | [
1
] | [] | [] | [
"image",
"matplotlib",
"overlay",
"python"
] | stackoverflow_0006347537_image_matplotlib_overlay_python.txt |
Q:
How does nosetests find tests to run?
I am trying to run all pyunit tests in a directory using nosetests. The problem is that I have 4 tests in this directory and nosetests is only running one of them. If I run the other three tests individually like:
nosetests -v thistestwillrunnow.py
then the tests will run. ... | How does nosetests find tests to run? | I am trying to run all pyunit tests in a directory using nosetests. The problem is that I have 4 tests in this directory and nosetests is only running one of them. If I run the other three tests individually like:
nosetests -v thistestwillrunnow.py
then the tests will run. But I thought just saying:
nosetests
woul... | [
"\"If it looks like a test, it’s a test\" !\nThis is extracted from nose documentation.\nPersonnaly I store my tests files in test sub-directories right in my module's directories like this :\nsrc/module1/test\nsrc/module2/test\nsrc/module2/sub_module/test\n\nAnd it works very well :)\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0006347867_python.txt |
Q:
How to read a digital certificate in a web application? (LAMP)
Is it possible to develop a web page that reads digital certificates available in the browser with Python? For example using pyOpenSSL?
I explain further:
I'd like to develop a web page that prompts the user and asks him to choose one of the digital ce... | How to read a digital certificate in a web application? (LAMP) | Is it possible to develop a web page that reads digital certificates available in the browser with Python? For example using pyOpenSSL?
I explain further:
I'd like to develop a web page that prompts the user and asks him to choose one of the digital certificates available in his browser and then prints the public infor... | [
"While the browser itself has access to certain set of certificates (usually system certificate store + some certificate store, specific to browser), it won't let the remote system access them easily. \nOne way to read certificates located on the client computer is create some helper object (ActiveX control, Java a... | [
3
] | [] | [] | [
"apache",
"cryptography",
"openssl",
"python"
] | stackoverflow_0006348082_apache_cryptography_openssl_python.txt |
Q:
list of python lambda functions w/o partial
I have been trying to generate a list of lambda functions in python using list comprehension. but it didn't work,
for example
fl=[lambda x: x**i for i in range(5)]
i have check the other question, it basically generate the same function based on the reference of i.
so... | list of python lambda functions w/o partial | I have been trying to generate a list of lambda functions in python using list comprehension. but it didn't work,
for example
fl=[lambda x: x**i for i in range(5)]
i have check the other question, it basically generate the same function based on the reference of i.
so I also tried partial.
from functools import par... | [
"You're tripping over Python scopes.\nfl=[lambda x, i=i: x**i for i in range(5)]\n\n",
"You're effectively passing i in by name. \nfl=[lambda x: x**i for i in range(5)]\n\nEvery time lambda is executed, it binds the same i to the function, so when the function is executed (later) it uses the then-current value of... | [
6,
6,
4
] | [] | [] | [
"function",
"lambda",
"list",
"list_comprehension",
"python"
] | stackoverflow_0006348354_function_lambda_list_list_comprehension_python.txt |
Q:
Center Google Map Based on geocoded IP
Basically whenever someones opens up my (Google) map I want it default to their approximate location.
Is there an easy way to do it with Google's API or do I have to write a custom code (this is python based app)?
A:
You can use Google API's built-in ClientLocation object:
... | Center Google Map Based on geocoded IP | Basically whenever someones opens up my (Google) map I want it default to their approximate location.
Is there an easy way to do it with Google's API or do I have to write a custom code (this is python based app)?
| [
"You can use Google API's built-in ClientLocation object:\nif (GBrowserIsCompatible()) \n{ \n var map = new google.maps.Map2(document.getElementById(\"mapdiv\"));\n\n if (google.loader.ClientLocation) \n { \n var center = new google.maps.LatLng(\n google.loader.ClientLocation.lat... | [
8,
3,
0,
0,
0
] | [] | [] | [
"django",
"google_maps",
"javascript",
"python"
] | stackoverflow_0001365722_django_google_maps_javascript_python.txt |
Q:
Python: Create various file objects while reading a file
I am reading a large file containing various <xml>..</xml> elements. Since every XML parser has trouble with that, I would like to produce efficiently new file objects for each <xml>..</xml> block.
I was starting to subclass the file object in Python, but go... | Python: Create various file objects while reading a file | I am reading a large file containing various <xml>..</xml> elements. Since every XML parser has trouble with that, I would like to produce efficiently new file objects for each <xml>..</xml> block.
I was starting to subclass the file object in Python, but got stucked there. I think, I've to intercept each line starting... | [
"While not a direct answer to your question, this may solve your problem anyway: Simply adding another <xml> at the beginning and another </xml> at the end will probably make your XML parser accept the document:\nfrom lxml import etree\ndocument = \"<xml>a</xml> <xml>b</xml>\"\ndocument = \"<xml>\" + document + \"... | [
1
] | [] | [] | [
"file",
"lxml",
"python"
] | stackoverflow_0006348946_file_lxml_python.txt |
Q:
On Windows, how can I install the lowest level global keyboard hook possible?
I'm working on a custom arcade launcher in python on Windows. I want to choose system and game, then launch the emulator - and require a certain key combination to kill the emulator. All of my key hooks work when testing with random ap... | On Windows, how can I install the lowest level global keyboard hook possible? | I'm working on a custom arcade launcher in python on Windows. I want to choose system and game, then launch the emulator - and require a certain key combination to kill the emulator. All of my key hooks work when testing with random applications, but when I actually launch the emulators (e.g. Nestopia), my key hooks ... | [
"You should definitely look at SetWindowsHookEx from user32. These functions allow you to register global keyboard hooks. (Just don't forget to pass them on by calling CallNextHookEx.)\nLink: http://msdn.microsoft.com/en-us/library/ms644990(v=vs.85).aspx\nI have no idea how to do that from python though, sorry.\n",... | [
1,
0
] | [] | [] | [
"hook",
"python",
"windows"
] | stackoverflow_0006340149_hook_python_windows.txt |
Q:
Sorting a dict with tuples as values
I have a dictionary that looks like this:
{'key_info': (rank, raw_data1, raw_data2),
'key_info2': ...}
Basically I need back a list of the keys in sorted order, that is sorted based on the rank field in the tuple.
My code looks something like this right now (diffs is the name... | Sorting a dict with tuples as values | I have a dictionary that looks like this:
{'key_info': (rank, raw_data1, raw_data2),
'key_info2': ...}
Basically I need back a list of the keys in sorted order, that is sorted based on the rank field in the tuple.
My code looks something like this right now (diffs is the name of the dict above):
def _sortRanked(self)... | [
"keys() only gives you keys, not values, so you have to use the keys to retrieve values from the dict if you want to sort on them:\nreturn sorted(self.diffs.keys(), key=lambda x: self.diffs[x], reverse=True)\n\nSince you're sorting on rank, which is the first item in the tuple, you don't need to specify which item ... | [
11,
2,
1,
0
] | [] | [] | [
"dictionary",
"python",
"sorting",
"tuples"
] | stackoverflow_0006349296_dictionary_python_sorting_tuples.txt |
Q:
There is a way not to hard code username & pass when sending mail [python]
i wanna know if it is possible not to hard code my user name and password in a script that copy a file in the operation system and send it via smtp [gmail]
Thank you!
A:
Store your data as environment variables or inside a configuration f... | There is a way not to hard code username & pass when sending mail [python] | i wanna know if it is possible not to hard code my user name and password in a script that copy a file in the operation system and send it via smtp [gmail]
Thank you!
| [
"Store your data as environment variables or inside a configuration file...\n",
"make the script take the username as command line args.\nif you import sys, then sys.argv is the list of all command line args, where the first is the name of the python script itself.\n",
"I bet that best way will be to keep passw... | [
1,
1,
1
] | [] | [] | [
"hardcoded",
"passwords",
"python",
"smtp"
] | stackoverflow_0006348988_hardcoded_passwords_python_smtp.txt |
Q:
ANTLR grammar postfix
I was writing a simple grammar for a small language when I came across an issue. It's throwing a NullPointerException when I try to interpret it. Oh, and this is ANTLRWorks 3.
Also - I specified that the language should be Python, but it still does stuff in Java :( Why?
Here's the input:
prog... | ANTLR grammar postfix | I was writing a simple grammar for a small language when I came across an issue. It's throwing a NullPointerException when I try to interpret it. Oh, and this is ANTLRWorks 3.
Also - I specified that the language should be Python, but it still does stuff in Java :( Why?
Here's the input:
program Test1 =
const t1 : int... | [
"As Kay already mentioned: there is no need to account for operator precedence in post-fix expressions. Post-fix expressions are just a list of one or more operands and operators. Here's how to get your grammar working:\ngrammar lang;\n\noptions {\n language=Python;\n output=AST;\n}\n\ntokens {\n PROGRAM;\n STA... | [
2
] | [] | [] | [
"antlr",
"python"
] | stackoverflow_0006347692_antlr_python.txt |
Q:
renderContents in beautifulsoup (python)
The code I'm trying to get working is:
h = str(heading)
# '<h1>Heading</h1>'
heading.renderContents()
I get this error:
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
print h.renderContents()
AttributeError: 'str' object has no attribute 'render... | renderContents in beautifulsoup (python) | The code I'm trying to get working is:
h = str(heading)
# '<h1>Heading</h1>'
heading.renderContents()
I get this error:
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
print h.renderContents()
AttributeError: 'str' object has no attribute 'renderContents'
Any ideas?
I have a string with htm... | [
"Your error message and your code sample don't line up. You say you're calling:\nheading.renderContents()\n\nBut your error message says you're calling:\nprint h.renderContents()\n\nWhich suggests that perhaps you have a bug in your code, trying to call renderContents() on a string object that doesn't define that m... | [
1
] | [] | [] | [
"beautifulsoup",
"html",
"python"
] | stackoverflow_0006349819_beautifulsoup_html_python.txt |
Q:
Why doesn't my Python Function start when called upon?
Whenever I'm calling my start() function, after it's been declared, I get a error saying it doesn't exist. My complete code is below.
import random
import time
global monsters
monsters = ['Goblin','Orc','Knight','Unicorn','Black Bear','White Dragon','Black Dra... | Why doesn't my Python Function start when called upon? | Whenever I'm calling my start() function, after it's been declared, I get a error saying it doesn't exist. My complete code is below.
import random
import time
global monsters
monsters = ['Goblin','Orc','Knight','Unicorn','Black Bear','White Dragon','Black Dragon','Dark Knight','Undead Corpse']
global player_level
play... | [
"Because the first if statement evaluates to false, so you never have the opportunity to set the command variable.\n",
"Because it's only called from within itself.\n"
] | [
2,
1
] | [] | [] | [
"function",
"python"
] | stackoverflow_0006349833_function_python.txt |
Q:
function print in python shell
Can anyone explain me difference in python shell between output variable through "print" and when I just write variable name to output it?
>>> a = 5
>>> a
5
>>> print a
5
>>> b = 'some text'
>>> b
'some text'
>>> print b
some text
When I do this with text I understand difference but... | function print in python shell | Can anyone explain me difference in python shell between output variable through "print" and when I just write variable name to output it?
>>> a = 5
>>> a
5
>>> print a
5
>>> b = 'some text'
>>> b
'some text'
>>> print b
some text
When I do this with text I understand difference but in int or float - I dont know.
| [
"Just entering an expression (such as a variable name) will actually output the representation of the result as returned by the repr() function, whereas print will convert the result to a string using the str() function.>>> s = \"abc\"\nPrinting repr() will give the same result as entering the expression directly:\... | [
12,
2
] | [] | [] | [
"python"
] | stackoverflow_0006350094_python.txt |
Q:
Documenting Python packages with doxygen
"Special documentation blocks in Python" in http://www.doxygen.nl/manual/docblocks.html gives an example of doxygen usage with Python.
In the corresponding HTML documentation that is generated by doxygen (example output in the web), if one clicks on a package name, then all... | Documenting Python packages with doxygen | "Special documentation blocks in Python" in http://www.doxygen.nl/manual/docblocks.html gives an example of doxygen usage with Python.
In the corresponding HTML documentation that is generated by doxygen (example output in the web), if one clicks on a package name, then all the descriptions, classes and functions conne... | [
"The example in the doxygen documentation was generated with the following config settings:\nPROJECT_NAME = \"Python\"\nOUTPUT_DIRECTORY = pyexample\nGENERATE_LATEX = NO\nGENERATE_MAN = NO\nGENERATE_RTF = NO\nOPTIMIZE_OUTPUT_JAVA = YES\nINPUT = pyexample.py\nQUIET = YES\nJ... | [
8
] | [] | [] | [
"doxygen",
"package",
"python"
] | stackoverflow_0006340571_doxygen_package_python.txt |
Q:
Authentication with Python, Apache, and mod_wsgi
I have been searching vigorously the last week in hopes of finding a solution to my problem. Originally, I had Python configured with CGI on my Windows, Apache, MySQL, and Python server. I understand that CGI is slow and additionally drops HTTP_AUTHORIZATION headers... | Authentication with Python, Apache, and mod_wsgi | I have been searching vigorously the last week in hopes of finding a solution to my problem. Originally, I had Python configured with CGI on my Windows, Apache, MySQL, and Python server. I understand that CGI is slow and additionally drops HTTP_AUTHORIZATION headers before executing the Python environment. I have since... | [
"It's passed in the mapping passed as environ to the main WSGI function.\n"
] | [
1
] | [] | [] | [
"apache",
"authorization",
"http_headers",
"mod_wsgi",
"python"
] | stackoverflow_0006350178_apache_authorization_http_headers_mod_wsgi_python.txt |
Q:
How to plot a 3D patch collection in matplotlib?
I'm trying to make a 3D plot in matplotlib with three circles on it, each centered at the origin and with a radius of 1, pointing in different directions - to illustrate a sphere of radius 1, for example.
In 2D I would make a circle patch collection and add it to th... | How to plot a 3D patch collection in matplotlib? | I'm trying to make a 3D plot in matplotlib with three circles on it, each centered at the origin and with a radius of 1, pointing in different directions - to illustrate a sphere of radius 1, for example.
In 2D I would make a circle patch collection and add it to the axes. In 3D I'm having trouble getting the patches t... | [
"import matplotlib.pyplot as plt\nfrom matplotlib.patches import Circle, PathPatch\nfrom mpl_toolkits.mplot3d import Axes3D \nimport mpl_toolkits.mplot3d.art3d as art3d\n\n\nfig = plt.figure()\nax=fig.gca(projection='3d')\n\nfor i in [\"x\",\"y\",\"z\"]:\n circle = Circle((0, 0), 1)\n ax.add_patch(circle)\n ... | [
17
] | [] | [] | [
"matplotlib",
"mplot3d",
"python"
] | stackoverflow_0006304116_matplotlib_mplot3d_python.txt |
Q:
How to retrieve executed SQL code from SQLAlchemy
I am using SQLAlchemy and would like to log executed SQL code (i.e. the code with all bind parameters already quoted and replaced). In case of psycopg2 it was possible using the query attribute of the Cursor object (see psycopg documentation). In case of MySQLdb it... | How to retrieve executed SQL code from SQLAlchemy | I am using SQLAlchemy and would like to log executed SQL code (i.e. the code with all bind parameters already quoted and replaced). In case of psycopg2 it was possible using the query attribute of the Cursor object (see psycopg documentation). In case of MySQLdb it is possible using the _last_executed attribute of the ... | [
"SQLAlchemy uses the standard Python logging library. To log queries to a file named db.log:\nimport logging\n\nlogging.basicConfig(filename='db.log')\nlogging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)\n\nWhen using Python logging, ensure all echo flags are set to False, to avoid duplicate logging. Now ... | [
25
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0006350411_python_sqlalchemy.txt |
Q:
python create signature X509
I would like to know how can I create a signature X509 using python.
I can not find any good example explaining about how such signature can be generated using python.
The goal is to have something like:
-----BEGIN CERTIFICATE-----
MIICjDCCAfWgAwIBAgIJANG2v68GF4y/MA0GCSqGSIb3DQEBBQUAME... | python create signature X509 | I would like to know how can I create a signature X509 using python.
I can not find any good example explaining about how such signature can be generated using python.
The goal is to have something like:
-----BEGIN CERTIFICATE-----
MIICjDCCAfWgAwIBAgIJANG2v68GF4y/MA0GCSqGSIb3DQEBBQUAME8xCzAJBgNV
BAYTAlVTMRMwEQYDVQQIEwp... | [
"Here is the simplest way\n>>> cmd = \"openssl req -x509 -nodes -days 365 -subj '/C=US/ST=Oregon/L=Portland/CN=www.madboa.com' -newkey rsa:1024 -keyout mycert.pem\"\n>>> from subprocess import Popen, PIPE\n>>> proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)\n>>> print proc.stdout.read()\n-----BEGIN CE... | [
3
] | [] | [] | [
"certificate",
"openssl",
"python",
"x509"
] | stackoverflow_0006350643_certificate_openssl_python_x509.txt |
Q:
python global variable __name__ (a newbie question)
What are the following names when I first start my python shell? They do not look like functions from __builtins__:
>>> dir(__name__)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__get... | python global variable __name__ (a newbie question) | What are the following names when I first start my python shell? They do not look like functions from __builtins__:
>>> dir(__name__)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
'__getslice__', '__gt__', '__... | [
"__name__ is a string and those a string methods. It's the name of the module or '__main__' on the toplevel. Hence this idiom appears often:\nif __name__ == '__main__':\n # this file was called directly, not imported\n main()\n\n",
"dir(__name__) shows the attributes of __name__, and since __name__ is a str... | [
8,
5
] | [] | [] | [
"python"
] | stackoverflow_0006350705_python.txt |
Q:
Excel-like text import in Python: automatically parsing fixed width columns
In Excel, if you import whitespace delineated text in which the columns do not line up perfectly and data may be missing, like
pH pKa/Em n(slope) 1000*chi2 vdw0
CYS-I0014_ >14.0 0.00
... | Excel-like text import in Python: automatically parsing fixed width columns | In Excel, if you import whitespace delineated text in which the columns do not line up perfectly and data may be missing, like
pH pKa/Em n(slope) 1000*chi2 vdw0
CYS-I0014_ >14.0 0.00
LYS+I0013_ 11.827 0.781 0.440 0.18
you are given the option t... | [
"First off, Excel (2003, at home) isn't quite so smart. If your column 1000*chi2 contains spaces, e.g. 1000 * chi2, excel will guess wrong.\nTrivial case: if your data was originally separated by tabs (not spaces), and multiple tabs were used to indicate empty columns, then, at least in TCL, it's easy to split eac... | [
4
] | [] | [] | [
"excel",
"fixed_width",
"parsing",
"python",
"text"
] | stackoverflow_0006348992_excel_fixed_width_parsing_python_text.txt |
Q:
Python regex does not search with group numbering
I am trying out the example given in http://docs.python.org/library/re.html for the group numbering and matching. Very simply, (.+) \1 should match two pieces of identical text separated by a space, and it lists the the as an example. However,
re.search('(.+) \1',... | Python regex does not search with group numbering | I am trying out the example given in http://docs.python.org/library/re.html for the group numbering and matching. Very simply, (.+) \1 should match two pieces of identical text separated by a space, and it lists the the as an example. However,
re.search('(.+) \1','the the')
returns a None.
I am using re version 2.2.1... | [
"'\\1' is '\\x01'. Perhaps you meant '(.+) \\\\1' or r'(.+) \\1'.\n",
"You either need to escape your escapes or use raw strings.\ne.g.\nre.search('(.+) \\\\1', 'the the' )\n\nor\nre.search(r'(.+) \\1', 'the the' )\n\nsee the Raw String Notation section on the same page as the example.\n",
"I would recommend us... | [
5,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006350883_python_regex.txt |
Q:
Where to you monkey patch the Django user model?
I want to monkey patch the user model from Django.
My code:
from django.db import models
from django.contrib.auth.models import User
User.add_to_class('secret_question', models.CharField(max_length="100"))
User.add_to_class('answer', models.CharField(max_length="10... | Where to you monkey patch the Django user model? | I want to monkey patch the user model from Django.
My code:
from django.db import models
from django.contrib.auth.models import User
User.add_to_class('secret_question', models.CharField(max_length="100"))
User.add_to_class('answer', models.CharField(max_length="100"))
User.add_to_class('DOB', models.DateField())
Whe... | [
"Please take a look at Storing additional information about users section of the authentication documentation. It suggests a cleaner way to add additional information to a User object.\n\nIf you'd like to store additional information related to your users, Django provides a method to specify a site-specific related... | [
7,
2
] | [] | [] | [
"django",
"monkeypatching",
"python"
] | stackoverflow_0006350539_django_monkeypatching_python.txt |
Q:
Only calling base class if its not subclassed in Python
I need to write a base class (in this example, class A) that will likely, but not always, be subclassed. I want to call the 'Run' method from the base class only if its not subclassed, else only call the the 'Run' method from the subclasses.
This is what I h... | Only calling base class if its not subclassed in Python | I need to write a base class (in this example, class A) that will likely, but not always, be subclassed. I want to call the 'Run' method from the base class only if its not subclassed, else only call the the 'Run' method from the subclasses.
This is what I have, it seems to work but I'm wondering if there is an easier... | [
"\nI want to call the 'Run' method from the base class only if its not subclassed, else only call the the 'Run' method from the subclasses.\n\nThis is what happens by default, the most specific method is called.\nIf you really don't want the base method to be available from subclasses, you can write something like ... | [
1,
1
] | [] | [] | [
"methods",
"oop",
"python",
"subclass"
] | stackoverflow_0006351076_methods_oop_python_subclass.txt |
Q:
getting following error while scanning constantly database table using reactor in twisted
I am getting the following error after a few hours of successful running.
Traceback (most recent call last):
File "/usr/lib/python2.6/threading.py", line 484, in run
self.__target(*self.__args, **self.__kwargs)
Fi... | getting following error while scanning constantly database table using reactor in twisted | I am getting the following error after a few hours of successful running.
Traceback (most recent call last):
File "/usr/lib/python2.6/threading.py", line 484, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/lib/python2.6/dist-packages/twisted/python/threadpool.py", line 210, in _worker
r... | [
"can anyone tell me why I am getting this error.. because you're doing it wrong.\nrunInteraction runs the supplied function with an argument of a cursor to a transaction which is run in a thread. You shouldn't be calling reactor.callInThread(Scanner().deferExecute).\n\nIt's better to use a twisted.internet.task.Loo... | [
2,
2,
0
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0003393858_python_twisted.txt |
Q:
PyOpenCL can't find include files when installed via "easy_install."
so I've downloaded the nVidia CUDA libraries and put them in the default location:
/usr/local/cuda
When I go to run this:
sudo easy_install pyopencl
It gives me this error:
In file included from src/wrapper/wrap_cl.cpp:1:0:
src/wrapper/wrap_cl.... | PyOpenCL can't find include files when installed via "easy_install." | so I've downloaded the nVidia CUDA libraries and put them in the default location:
/usr/local/cuda
When I go to run this:
sudo easy_install pyopencl
It gives me this error:
In file included from src/wrapper/wrap_cl.cpp:1:0:
src/wrapper/wrap_cl.hpp:20:19: fatal error: CL/cl.h: No such file or directory
I can, however... | [
"Your compiler's include path probably doesn't include /usr/local/cuda/include/. The environment variable LD_LIBRARY_PATH is actually there to tell the compiler/runtime environment where to find shared object files. There are two ways (that know of) to fix this:\n1) Most compilers accept a flag that specifies an ad... | [
3
] | [] | [] | [
"cuda",
"easy_install",
"opencl",
"python"
] | stackoverflow_0006350290_cuda_easy_install_opencl_python.txt |
Q:
Blocking vs. Non Blocking network IO in Python
I have some python code that was written by a developer before me. It sends UDP messages to nodes in a P2P network. I am writing a parallel version of that code. This code sends multiple parallel messages to the P2P network. Unfortunately, the code is consuming too mu... | Blocking vs. Non Blocking network IO in Python | I have some python code that was written by a developer before me. It sends UDP messages to nodes in a P2P network. I am writing a parallel version of that code. This code sends multiple parallel messages to the P2P network. Unfortunately, the code is consuming too much CPU. I am assuming it is because of all the netwo... | [
"Yes.\n"
] | [
7
] | [] | [] | [
"asynchronous",
"parallel_processing",
"polling",
"python",
"twisted"
] | stackoverflow_0006351058_asynchronous_parallel_processing_polling_python_twisted.txt |
Q:
Python strange behavior when called by Popen & writing to stdin
Two (related?) questions here.
I was trying to write a program to start an external process, and then simultaniouly read from stdout and write to stdin. Everything seemed to be working, however the process was not responding to the data sent to its st... | Python strange behavior when called by Popen & writing to stdin | Two (related?) questions here.
I was trying to write a program to start an external process, and then simultaniouly read from stdout and write to stdin. Everything seemed to be working, however the process was not responding to the data sent to its stdin pipe. Do you know why this would be?(1)
This second question is s... | [
"What you're seeing is the expected behaviour of Python 2.x's input() function, which takes a line from sys.stdin (like raw_input()) and then evaluates it as Python code. It's generally a bad idea to use input() in Python 2.x :) In Python 3.x, input() was removed and raw_input() was renamed to input(), which may be... | [
3,
2
] | [] | [] | [
"identifier",
"python",
"stdin",
"stdout"
] | stackoverflow_0006351369_identifier_python_stdin_stdout.txt |
Q:
small language in python
I'm writing what might not even be called a language in python. I currently have several operators: +, -, *, ^, fac, @, !!. fac computes a factorial, @ returns the value of a variable, !! sets a variable. The code is below. How would I go about writing a way to define functions in this sim... | small language in python | I'm writing what might not even be called a language in python. I currently have several operators: +, -, *, ^, fac, @, !!. fac computes a factorial, @ returns the value of a variable, !! sets a variable. The code is below. How would I go about writing a way to define functions in this simple language?
EDIT: i updated ... | [
"Your program is very confused, and it needs to be fixed before it can be modified to support defining functions. I will do this in several steps and as I complete them, I will add them into the answer. This answer will get to be quite long.\nAlso, you obviously haven't decided what your language definition should ... | [
7,
2,
1,
1,
1
] | [] | [] | [
"operators",
"parsing",
"postfix_notation",
"programming_languages",
"python"
] | stackoverflow_0006338440_operators_parsing_postfix_notation_programming_languages_python.txt |
Q:
Python boolean truth tests
Possible Duplicate:
Python Ternary Operator
Does Python have an equivalent of the ternary operator?:
( x < 5 ? 1 : 0 )
Or must I express the same thing with an if-else pair?
A:
You can use a conditional expression:
1 if x < 5 else 0
In code written for very old versions of Python, ... | Python boolean truth tests |
Possible Duplicate:
Python Ternary Operator
Does Python have an equivalent of the ternary operator?:
( x < 5 ? 1 : 0 )
Or must I express the same thing with an if-else pair?
| [
"You can use a conditional expression:\n1 if x < 5 else 0\n\nIn code written for very old versions of Python, you may also see:\nx < 5 and 1 or 0\n\nHowever, the conditional expression form is preferred for Python 2.5 and later.\n",
"Python has:\n1 if x < 5 else 0\n\nor the old style:\nx < 5 and 1 or 0\n\n"
] | [
12,
1
] | [] | [] | [
"boolean",
"python"
] | stackoverflow_0006351566_boolean_python.txt |
Q:
Django: MultiValueField and MultiWidget
Django's documentation doesn't do a very thorough job of explaining how to use MultiValueField and MultiWidget. I've tried dissecting the one implementation and haven't had good results. Would someone mind giving me a quick pointer in the right direction?
My example:
widgets... | Django: MultiValueField and MultiWidget | Django's documentation doesn't do a very thorough job of explaining how to use MultiValueField and MultiWidget. I've tried dissecting the one implementation and haven't had good results. Would someone mind giving me a quick pointer in the right direction?
My example:
widgets.py
from django import forms
class TestMulti... | [
"Please notice that django.forms.MultiValueField is a form field and not a model field (like django.db.models.CharField). Therefore, it is not treated as a model field in your Test model, and was not created in your database. (You can check it with ./manage.py sqlall myapp).\nChange your models.py to:\nfrom django... | [
15
] | [] | [] | [
"django",
"django_admin",
"django_forms",
"python"
] | stackoverflow_0006064121_django_django_admin_django_forms_python.txt |
Q:
Python's super() function
In the below sample, the last 2 lines in the B.Go() method both call the Go() method from class A. Are they functionally identical? Is the only benefit to using super() that I don't have to know the inherited class name?
class A(object):
def Go(self):
print "Calling A.Go()"
... | Python's super() function | In the below sample, the last 2 lines in the B.Go() method both call the Go() method from class A. Are they functionally identical? Is the only benefit to using super() that I don't have to know the inherited class name?
class A(object):
def Go(self):
print "Calling A.Go()"
class B(A):
def Go(self):
... | [
"No, super() does something a direct call to A.Go can't. super(B, self).Go() calls the next method in the method resolution order. It calls the method that would have been called had B not implemented the method at all. In direct linear inheritance this is always A, so there is no real difference (besides the class... | [
14,
4,
2,
1
] | [] | [] | [
"inheritance",
"oop",
"python"
] | stackoverflow_0006351508_inheritance_oop_python.txt |
Q:
Accessing individual objects in a Django template file
I am editing a template to display an attribute of the first member in a list. I am trying to access it like so:
{{ food_list.index(0).id }}
I get an error that says Could not parse the remainder: '(0).id'.
What is the correct way to access an individual memb... | Accessing individual objects in a Django template file | I am editing a template to display an attribute of the first member in a list. I am trying to access it like so:
{{ food_list.index(0).id }}
I get an error that says Could not parse the remainder: '(0).id'.
What is the correct way to access an individual member in a list?
| [
"{{ food_list.0.id }}\n\nAlternatively,\n{% with f=food_list|first %}\n {{ f.id }}\n{% endwith %}\n\n",
"You can't call methods in a template. Either write a template tag for this, or do it in your view. If what you wanted to do was just index the list, then you don't use the index() method for that; just use no... | [
3,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006351756_django_python.txt |
Q:
Django math question
I have the following code in my template:
{{ object.rating.get_percent|floatformat|add:"-100" }}
Which outputs -50
The value of object.rating.get_percent is 50. I want to subtract it from the number 100. So I am expecting 50 in return. Why do I get -50?
A:
You get -50 because "-100" is the ... | Django math question | I have the following code in my template:
{{ object.rating.get_percent|floatformat|add:"-100" }}
Which outputs -50
The value of object.rating.get_percent is 50. I want to subtract it from the number 100. So I am expecting 50 in return. Why do I get -50?
| [
"You get -50 because \"-100\" is the second operand to add. The first operand is the result of object.rating.get_percent|floatformat.\nEssentially your expression is:\n50 + -100\n\nIf you're really desperate to calculate \"100 - x\", you can use the {% widthratio %} tag:\n{% widthratio -100|add:object.rating.get_pe... | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006351826_django_python.txt |
Q:
Turing complete template engines
What template engines / template languages are turing complete? I heard about these so far:
FreeMarker (implemented in java)
MovableTypes template language (in perl)
xslt :-(
Cheetah (in Python)
Smarty (in PHP)
Any others (especially implemented with perl)?
Ps: Don't waste time w... | Turing complete template engines | What template engines / template languages are turing complete? I heard about these so far:
FreeMarker (implemented in java)
MovableTypes template language (in perl)
xslt :-(
Cheetah (in Python)
Smarty (in PHP)
Any others (especially implemented with perl)?
Ps: Don't waste time with clarifying me MVC, and why turing ... | [
"eRuby lets you embed arbitrary Ruby into your templates:\n$ echo \"Hello <%= 'dlrow'.reverse() %> from eRuby\" | erb\nHello world from eRuby\n\n",
"Perl's Template::Toolkit allows for inlining of Perl if the EVAL_PERL flag is set. Within the template, PERL and RAWPERL blocks allow inlining, to the extent (in th... | [
3,
3,
0,
0
] | [] | [] | [
"perl",
"programming_languages",
"python",
"ruby",
"templates"
] | stackoverflow_0006351765_perl_programming_languages_python_ruby_templates.txt |
Q:
What's the most Pythonic way to identify consecutive duplicates in a list?
I've got a list of integers and I want to be able to identify contiguous blocks of duplicates: that is, I want to produce an order-preserving list of duples where each duples contains (int_in_question, number of occurrences).
For example, i... | What's the most Pythonic way to identify consecutive duplicates in a list? | I've got a list of integers and I want to be able to identify contiguous blocks of duplicates: that is, I want to produce an order-preserving list of duples where each duples contains (int_in_question, number of occurrences).
For example, if I have a list like:
[0, 0, 0, 3, 3, 2, 5, 2, 6, 6]
I want the result to be:
[... | [
">>> from itertools import groupby\n>>> L = [0, 0, 0, 3, 3, 2, 5, 2, 6, 6]\n>>> grouped_L = [(k, sum(1 for i in g)) for k,g in groupby(L)]\n>>> # Or (k, len(list(g))), but that creates an intermediate list\n>>> grouped_L\n[(0, 3), (3, 2), (2, 1), (5, 1), (2, 1), (6, 2)]\n\nBatteries included, as they say.\nSuggesti... | [
78
] | [] | [] | [
"duplicates",
"generator",
"list",
"python"
] | stackoverflow_0006352425_duplicates_generator_list_python.txt |
Q:
other than combining the new_title statements,how do i refactor this code using Python3? please help:(
small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on')
def book_title(title):
""" Takes a string and returns a title-case string.
All words EXCEPT for small words are made title case
unless... | other than combining the new_title statements,how do i refactor this code using Python3? please help:( | small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on')
def book_title(title):
""" Takes a string and returns a title-case string.
All words EXCEPT for small words are made title case
unless the string starts with a preposition, in which
case the word is correctly capitalized.
>>> book_ti... | [
"return ' '.join((new[0].upper() + new[1:]) if (ix == 0 or new not in small_words)\n else new for (ix, new) in enumerate(title.lower().split()))\n\n"
] | [
2
] | [] | [] | [
"python",
"refactoring"
] | stackoverflow_0006352394_python_refactoring.txt |
Q:
Which is a better __repr__ for a custom Python class?
It seems there are different ways the __repr__ function can return.
I have a class InfoObj that stores a number of things, some of which I don't particularly want users of the class to set by themselves. I recognize nothing is protected in python and they co... | Which is a better __repr__ for a custom Python class? | It seems there are different ways the __repr__ function can return.
I have a class InfoObj that stores a number of things, some of which I don't particularly want users of the class to set by themselves. I recognize nothing is protected in python and they could just dive in and set it anyway, but seems defining it i... | [
"The __repr__ method is designed to produce the most useful output for the developer, not the enduser, so only you can really answer this question. However, I'd typically go with option B. Option A isn't very useful, and option C is needlessly verbose -- you don't know how your module is imported anyway. Others ... | [
13
] | [] | [] | [
"constructor",
"python",
"repr"
] | stackoverflow_0006352484_constructor_python_repr.txt |
Q:
SQLAlchemy and joins, we have no foreign keys
Assume the following in MySQL:
CREATE TABLE users (
id integer auto_increment primary key,
username varchar(30),
active enum('N','Y'),
created_on int(11),
updated_on int(11),
points int(10),
// other fields
);
CREATE TABLE comments (
id integer auto_in... | SQLAlchemy and joins, we have no foreign keys | Assume the following in MySQL:
CREATE TABLE users (
id integer auto_increment primary key,
username varchar(30),
active enum('N','Y'),
created_on int(11),
updated_on int(11),
points int(10),
// other fields
);
CREATE TABLE comments (
id integer auto_increment primary key,
user_id integer,
forum_id ... | [
"You have two options. You can pass the join condition in join like so: \nj = join(users, comments, onclause=users.c.id == commends.c.user_id)\n\nIf you're defining this in terms of a orm.relationship property, the keyword parameter will be primaryjoin instead of onclause. \nHowever, the approach I Prefer is to j... | [
25
] | [] | [] | [
"foreign_keys",
"join",
"mysql",
"python",
"sqlalchemy"
] | stackoverflow_0006352141_foreign_keys_join_mysql_python_sqlalchemy.txt |
Q:
sharing one def function among multiple urls in django
I have one def function that I would like to use to handle two urls. I need the function to behave slightly differently depending on which url is called. Is there a way to add inputs to the def function from urls.py?
A:
Pass an extra option to the view tha... | sharing one def function among multiple urls in django | I have one def function that I would like to use to handle two urls. I need the function to behave slightly differently depending on which url is called. Is there a way to add inputs to the def function from urls.py?
| [
"Pass an extra option to the view that it can check to see which urlconf it was invoked from.\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006352520_django_python.txt |
Q:
Python string formatting UnicodeEncodingError
I'm writing a Python script that reads tweets and inserts them into MySQL. Depending on the attributes of each tweet, I need to insert different fields. For that reason, I'm building the fields and values section of the query string as I go, using Python string formatt... | Python string formatting UnicodeEncodingError | I'm writing a Python script that reads tweets and inserts them into MySQL. Depending on the attributes of each tweet, I need to insert different fields. For that reason, I'm building the fields and values section of the query string as I go, using Python string formatting for convenience:
values = """%s, %s, '%s','%s',... | [
"Change:\n\"\"\"%s, %s, '%s','%s','%s','%s',%s,'%s','%s','%s'\"\"\"\n\nto:\nu\"\"\"%s, %s, '%s','%s','%s','%s',%s,'%s','%s','%s'\"\"\"\n\nAnd then if you want to encode it to UTF-8, do:\nvalue.encode('utf8')\n\nBut it looks like you're using the wrong approach anyway, see Escape string Python for MySQL\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0006352620_python.txt |
Q:
Difficulty with python urllib2 form-sending: website says I don't have cookies enabled though I should
So, I'm trying to submit a form with urllib/urllib2 which should set some a cookie to log me in. However, the website seems convinced that "cookies are not enabled" though I've told urllib to process cookies.
Thi... | Difficulty with python urllib2 form-sending: website says I don't have cookies enabled though I should | So, I'm trying to submit a form with urllib/urllib2 which should set some a cookie to log me in. However, the website seems convinced that "cookies are not enabled" though I've told urllib to process cookies.
This is what my code looks like:
opener = urllib2.build_opener( urllib2.HTTPCookieProcessor() )
urllib2.install... | [
"import urllib2,urllib,cookielib\n\ncj = cookielib.CookieJar()\nopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))\nurllib2.install_opener( opener )\nparams = urllib.urlencode( { 'username': 'user', 'password': 'pass' } )\n\nf = opener.open( 'http://example.com/login/', params )\ndata = f.read()\nprint... | [
0
] | [] | [] | [
"cookies",
"python",
"urllib",
"urllib2"
] | stackoverflow_0006352303_cookies_python_urllib_urllib2.txt |
Q:
How do I work with the Qt data base in Python?
I'm beginning with PyQt and heard that the Qt comes with a special data base module named QtSQL. The docs of the module, like everything in Qt, cover only C++ usage. In my work, I'll need a data base which can be accessed by more than one software by the time (local n... | How do I work with the Qt data base in Python? | I'm beginning with PyQt and heard that the Qt comes with a special data base module named QtSQL. The docs of the module, like everything in Qt, cover only C++ usage. In my work, I'll need a data base which can be accessed by more than one software by the time (local network). I would like to know if someone works with ... | [
"Yes, PyQt supports QtSql. Note that it's not a database in itself, but rather a unified interface to database libraries:\n\nThe QtSql module contains classes that\n integrate with open-source and\n proprietary SQL databases. It includes\n editable data models for database\n tables that can be used with GUI\n ... | [
2
] | [] | [] | [
"database",
"pyqt",
"python",
"qt",
"qtsql"
] | stackoverflow_0006352180_database_pyqt_python_qt_qtsql.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.