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: python string substitution in sqlite query i'm trying to use an IN statement to return results which match one of a list of strings for example strings = ['string1', 'string2', 'string3'] c.execute('select count(*) from table where foo in ?', strings) i know this is incorrect and doesnt work but i hope that it hi...
python string substitution in sqlite query
i'm trying to use an IN statement to return results which match one of a list of strings for example strings = ['string1', 'string2', 'string3'] c.execute('select count(*) from table where foo in ?', strings) i know this is incorrect and doesnt work but i hope that it highlights what im trying to do...
[ "You can't do that. There are three problems:\n\nYou can't have a table called table unless you use backticks around the table name.\nAn IN clause must have parentheses.\nYou want three parameters, not one.\n\nTry this instead:\nsql = 'SELECT COUNT(*) FROM yourtable WHERE foo IN (?, ?, ?)'\n\nIf the number of strin...
[ 6, 2 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0005205994_python_sqlite.txt
Q: Post comment with Python I would like to post a comment with Python, but I don't really know how to... here is the html source : <form name="addc" method="post"> <textarea id="990" name="comments" value=""></textarea> <input name="i" value="435" type="hidden"> <input name="pseudo" value="3454" type="hidden">...
Post comment with Python
I would like to post a comment with Python, but I don't really know how to... here is the html source : <form name="addc" method="post"> <textarea id="990" name="comments" value=""></textarea> <input name="i" value="435" type="hidden"> <input name="pseudo" value="3454" type="hidden"> <input name="action" value=...
[ "If you're trying to write a script to automatically post comments try this:\nimport urllib\nimport urllib2\n\nurl = 'http://www.someserver.com/somepage.html' # <-- Replace this with the URL of the page you're trying to post to.\nvalues = {'990' : 'comment here'}\n\ndata = urllib.urlencode(values)\nreq = urllib2.Re...
[ 3, 1, 0 ]
[]
[]
[ "comments", "html", "post", "python" ]
stackoverflow_0005205847_comments_html_post_python.txt
Q: can not change color of line using rgb value using cairo in pygtk I am drawing on drawing area using cairo in pygtk. I set color of line using this func: cr.set_source_rgb(203,12,41) but it showing white color instead of this color #CB0C33 it is like red rose color. So please can any one tell me how to change col...
can not change color of line using rgb value using cairo in pygtk
I am drawing on drawing area using cairo in pygtk. I set color of line using this func: cr.set_source_rgb(203,12,41) but it showing white color instead of this color #CB0C33 it is like red rose color. So please can any one tell me how to change color of line to any color using cairo in pygtk. Please help me. thank you...
[ "set_source_rgb expects you to pass floating point values from 0 to 1, where 1 should correspond to FF. Pls, check if the code below would work for you:\ncolor = gtk.gdk.Color('#CB0C33')\ncr.set_source_rgb(float(color.red) / 65535, \n float(color.green) / 65535, \n float(color.blue...
[ 3 ]
[]
[]
[ "cairo", "pygtk", "python" ]
stackoverflow_0005197973_cairo_pygtk_python.txt
Q: Interrupting Select to add another socket to watch in Python I'm implementing peer-to-peer IPC using TCP in a Windows XP application. I'm using the select and socket modules in Python 2.6.6. I have three TCP threads, a reading thread that typically is blocking on select(), a writing thread that is typically wait...
Interrupting Select to add another socket to watch in Python
I'm implementing peer-to-peer IPC using TCP in a Windows XP application. I'm using the select and socket modules in Python 2.6.6. I have three TCP threads, a reading thread that typically is blocking on select(), a writing thread that is typically waiting on an event (the event indicates there is stuff to write to TC...
[ "You could try adding an extra file descriptor to your set that you use as a signaling mechanism. You can then write to that descriptor a dummy value to cause select to exit. For example:\nmy_pipe = os.pipe()\n...\nwhile True:\n ready_fds = select.select(my_read_fds + [my_pipe[0]],\n ...
[ 8, 1 ]
[]
[]
[ "python", "tcp", "winsock" ]
stackoverflow_0004660756_python_tcp_winsock.txt
Q: django unit testing and global fixtures I'm working on a web project in Django, and I'm using the python unittest framework. For every app I have some fixtures. This means, that every app has some identical tables in fixtures. I would like to share fixtures between apps and testcases, because otherwise if I change...
django unit testing and global fixtures
I'm working on a web project in Django, and I'm using the python unittest framework. For every app I have some fixtures. This means, that every app has some identical tables in fixtures. I would like to share fixtures between apps and testcases, because otherwise if I change a model, I will have to change all json fixt...
[ "I would highly recommend looking into Django's Testing architecture. Check out TestCase.fixtures especially; this is far more advanced and Django-specific than unittest.\n", "Do not use static fixtures, it is a bad automated tests pattern. Use dynamic fixtures.\nDjango Dynamic Fixture has options to create globa...
[ 2, 2, 1 ]
[]
[]
[ "django", "python", "unit_testing" ]
stackoverflow_0001270657_django_python_unit_testing.txt
Q: python split string and pick substring I am having a lot of trouble with the list returned by the split function in python. I am probably being incredibly dense. My python code is as follows str = "XXX:YYY:ZZZ" var+=1 ins = str.split(':') print ins When the script runs it returns the following result ['XXX','YYY...
python split string and pick substring
I am having a lot of trouble with the list returned by the split function in python. I am probably being incredibly dense. My python code is as follows str = "XXX:YYY:ZZZ" var+=1 ins = str.split(':') print ins When the script runs it returns the following result ['XXX','YYY','ZZZ'] What i am struggling to do is pull...
[ "Your code will not work in instances where the input you're analyzing has a length <= 1.\nTry checking for that and handling it in your code.\n", "One of the lines you are reading probably has a two '\\n' characters in a row. When that string is read with readlines() and then spit it has no [1] index only a [0] ...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005205982_python.txt
Q: Python API design pattern question I often find I have class instances that are descendants of other class instances, in a tree like fashion. For example say I'm making a CMS platform in Python. I might have a Realm, and under that a Blog, and under that a Post. Each constructor takes it's parent as the first para...
Python API design pattern question
I often find I have class instances that are descendants of other class instances, in a tree like fashion. For example say I'm making a CMS platform in Python. I might have a Realm, and under that a Blog, and under that a Post. Each constructor takes it's parent as the first parameter so it knows what it belongs to. It...
[ "You could use a common base class for the containers featuring an add() method\nclass Container(object):\n def __init__(self, parent=None):\n self.children = []\n self.parent = parent\n def add(self, child)\n child.parent = self\n self.children.append(child)\n return child\...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005205752_python.txt
Q: Compiling pyx files with dependencies in different packages I am having problems compiling cdef-ed types in different packages and I couldn't find an explanation in cython docs. I have this setup.py in the root of my python src tree: from distutils.core import setup from distutils.extension import Extension from C...
Compiling pyx files with dependencies in different packages
I am having problems compiling cdef-ed types in different packages and I couldn't find an explanation in cython docs. I have this setup.py in the root of my python src tree: from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext setup( cmdclass = {'build_ex...
[ "Oh, well, for those having a similar problem, it looks like maybe I found the answer.\nI was expecting python to automatically scan the symbols compiled into the shared library FragIdx.so, instead it looks like this information must be provided explicitly as a .pxd file (which becomes a C header file after Cython ...
[ 12 ]
[]
[]
[ "cython", "python" ]
stackoverflow_0005204906_cython_python.txt
Q: Python cpu temp in system tray Linux I'm using tint2 for a panel and want to show the cpu temp as a system tray icon since there aren't any plugins for tint2 that do that and I'd just like to know how to do this anyway whether there was one or not. The script I have so far is: #! /usr/bin/python import pygtk,os py...
Python cpu temp in system tray Linux
I'm using tint2 for a panel and want to show the cpu temp as a system tray icon since there aren't any plugins for tint2 that do that and I'd just like to know how to do this anyway whether there was one or not. The script I have so far is: #! /usr/bin/python import pygtk,os pygtk.require("2.0") import gtk import egg.t...
[ "you can define a timer via timeout_add_seconds and update your tray icon in the callback. See if an example below would work for you:\nimport gtk, gobject, os\n\nclass CPUTimer:\n def __init__(self, timeout):\n\n self.window = gtk.Window()\n vbox = gtk.VBox()\n self.window.add(vbox)\n ...
[ 3 ]
[ "Look at Python's \"threading\" module. Create a function which runs the command an update gtk.Label's text with new output(t.set_text(str)). And run this function on a thread.\nhttp://docs.python.org/library/threading.html\n" ]
[ -1 ]
[ "linux", "pygtk", "python", "system_tray" ]
stackoverflow_0005206020_linux_pygtk_python_system_tray.txt
Q: Accurate signal delay calculation in Python I'm trying to calculate the lag between two signals in Python using cross correlation. The two signals are almost identical except for a very small timelag. I've tried numpy.correlate and scipy.convolve (alot faster) and both works relatively well but gives a small error...
Accurate signal delay calculation in Python
I'm trying to calculate the lag between two signals in Python using cross correlation. The two signals are almost identical except for a very small timelag. I've tried numpy.correlate and scipy.convolve (alot faster) and both works relatively well but gives a small error. I'm starting to suspect that the error is the r...
[ "Depending on the power spectrum of the two signals you do get a small error due to the fact that the cross correlation is not properly normalised at each lag. Here is a little function that I use; it normallises the overlap region at each lag and I found it gives accurate results:\ndef NormCrossCorrSlow(x1, x2,\n ...
[ 0 ]
[]
[]
[ "correlation", "lag", "python", "signals" ]
stackoverflow_0003825360_correlation_lag_python_signals.txt
Q: Why empty string is on every string? For example: >>> s = 'python' >>> s.index('') 0 >>> s.index('p') 0 A: This is because the substring of length 0 starting at index 0 in 'python' is equal to the empty string: >>> s[0:0] '' Of course every substring of length zero of any string is equal to the empty string. A...
Why empty string is on every string?
For example: >>> s = 'python' >>> s.index('') 0 >>> s.index('p') 0
[ "This is because the substring of length 0 starting at index 0 in 'python' is equal to the empty string:\n>>> s[0:0]\n''\n\nOf course every substring of length zero of any string is equal to the empty string.\n", "You can see \"python\" as \"the empty string, followed by a p, followed by fifteen more empty string...
[ 18, 5 ]
[]
[]
[ "python", "string" ]
stackoverflow_0005206466_python_string.txt
Q: How to write individual bits to a text file in python? Suppose I have a number like 824 and I write it to a text file using python. In the text file, it will take 3 bytes space. However, If i represent it using bits, it has the following representation 0000001100111000 which is 2 bytes (16 bits). I was wondering h...
How to write individual bits to a text file in python?
Suppose I have a number like 824 and I write it to a text file using python. In the text file, it will take 3 bytes space. However, If i represent it using bits, it has the following representation 0000001100111000 which is 2 bytes (16 bits). I was wondering how can I write bits to file in python, not bytes. If I can d...
[ "The struct module is what you want. From your example, 824 = 0000001100111000 binary or 0338 hexadecimal. This is the two bytes 03H and 38H. struct.pack will convert 824 to a string of these two bytes, but you also have to decide little-endian (write the 38H first) or big-endian (write the 03H first).\nExample\...
[ 10, 5, 2 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0005205487_file_io_python.txt
Q: Transfer different chunks of data to client systems using python Well i want to transfer different chunks of data to client machine , by different i mean the data sent could be either code or a particular function , i have used basic socket program in order to transfer the content , but how do i make the client sy...
Transfer different chunks of data to client systems using python
Well i want to transfer different chunks of data to client machine , by different i mean the data sent could be either code or a particular function , i have used basic socket program in order to transfer the content , but how do i make the client system help differentiate between these contents , i am aware of the con...
[ "It sounds like your simply looking to serialize python objects. \nLook at the pickle (and cPickle) module. Pickle is the python serialization format, which will allow you to transfer python objects as strings. Make sure to take note of what can, and can't be pickled as well. \nIf your client needs to differentiate...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0005206423_python.txt
Q: Regex in Python. NOT matches I'll go straight: I have a string like this (but with thousands of lines) Ach-emos_2 Ach. emos_54 Achėmos_18 Ąžuolas_4 Somtehing else_2 and I need to remove lines that does not match a-z and ąčęėįšųūž plus _ plus any integer (3rd and 4th lines match this). And this should be case inse...
Regex in Python. NOT matches
I'll go straight: I have a string like this (but with thousands of lines) Ach-emos_2 Ach. emos_54 Achėmos_18 Ąžuolas_4 Somtehing else_2 and I need to remove lines that does not match a-z and ąčęėįšųūž plus _ plus any integer (3rd and 4th lines match this). And this should be case insensitive. I think regex should be [...
[ "As to making the matching case insensitive, you can use the I or IGNORECASE flags from the re module, for example when compiling your regex:\nregex = re.compile(\"^[a-ząčęėįšųūž]+_\\d+$\", re.I)\n\nAs to removing the lines not matching this regex, you can simply construct a new string consisting of the lines that ...
[ 5, 0, 0 ]
[]
[]
[ "match", "python", "regex" ]
stackoverflow_0005206345_match_python_regex.txt
Q: Is it possible to force cPickle to use breadth-first rather than depth-first recursion? I realise the answer is very likely to be 'no'! Basically, I have a graph (the nodes and edges kind) which represents a grid of squares; each node object contains references to every other node that this node has an edge to, wh...
Is it possible to force cPickle to use breadth-first rather than depth-first recursion?
I realise the answer is very likely to be 'no'! Basically, I have a graph (the nodes and edges kind) which represents a grid of squares; each node object contains references to every other node that this node has an edge to, which seems to mean that when the graph is serialised using cPickle.dump it traverses every nod...
[ "Writing a suitable __getstate__() method does not seem to be that complicated after all. Try something like\nclass Node(object):\n def __getstate__(self):\n state = self.__dict__.copy()\n state.pop(\"neighbours\")\n return state\n\nThis will pickle all attributes of Node instance except fo...
[ 1 ]
[]
[]
[ "pickle", "python", "recursion" ]
stackoverflow_0005206831_pickle_python_recursion.txt
Q: How can I change this Python code to be multiprocess rather than multi threaded? The Python code below connects to lots of servers, grabs some info from each one and returns the results. It currently kicks off a separate thread for each connection. I would like to see how performance is affected by using a separat...
How can I change this Python code to be multiprocess rather than multi threaded?
The Python code below connects to lots of servers, grabs some info from each one and returns the results. It currently kicks off a separate thread for each connection. I would like to see how performance is affected by using a separate process for each connection rather than a thread. Can this code be easily changed to...
[ "Have you considered using a single process and a single thread e.g. by using twisted ?\nThe multi process option may only be reasonably easy when os.fork is available....\n", "As it says in the documentation:\n\nmultiprocessing is a package that supports spawning processes using an API similar to the threading m...
[ 3, 3 ]
[]
[]
[ "multiprocessing", "multithreading", "python" ]
stackoverflow_0005206809_multiprocessing_multithreading_python.txt
Q: Check password hash over query parameter or if condition I want to ask it is better to make a query in mongo db like this: db.users.findOne({'username': 'example', 'password': '5f189664bb2e58d4e2ee879835b13a7e3a790e14'}) Or make the check of the password hash in a if condition like this: user = db.users.findOne({...
Check password hash over query parameter or if condition
I want to ask it is better to make a query in mongo db like this: db.users.findOne({'username': 'example', 'password': '5f189664bb2e58d4e2ee879835b13a7e3a790e14'}) Or make the check of the password hash in a if condition like this: user = db.users.findOne({'username': 'example'}) if user['password'] == passwordHash: ...
[ "It depends on what you want to do if the user is found but the password is wrong.\n\nIf you want to display \"Incorrect username or password\" you can use either method.\nIf you want to display \"Incorrect password\" you need the second method as the first method cannot distinguish between the username being valid...
[ 2 ]
[]
[]
[ "mongodb", "python" ]
stackoverflow_0005207111_mongodb_python.txt
Q: How to Log All IRC data on Channel Using Twisted? I have a somewhat unique request. What I am looking to do is listen on a specific port for all traffic coming through via IRC protocol. I then want to log all of those messages/commands/ect. I do not, however, want to join the channel. I just want to listen and log...
How to Log All IRC data on Channel Using Twisted?
I have a somewhat unique request. What I am looking to do is listen on a specific port for all traffic coming through via IRC protocol. I then want to log all of those messages/commands/ect. I do not, however, want to join the channel. I just want to listen and log. Is there an easy built in way to do this? I have been...
[ "We addressed this issue in a somewhat round about way. We worked off a generic hexdumping proxy server constructed in twisted and then created finer detail parsing algorithms off of that.\n", "I don't think you can do this if you just connect to a server... the servers don't send you messages for channels you ha...
[ 1, 0 ]
[]
[]
[ "irc", "logging", "python", "twisted" ]
stackoverflow_0003128025_irc_logging_python_twisted.txt
Q: Problem with Django-1.3 beta Guys!! I'm really enthusiastic in learning django and learnt a bit on Django-1.2 but then I installed 1.3 version which is ok till I run the server using the command "python manage.py runserver". It's giving a huge error. I can't figure out a way to solve this. And error is given as : ...
Problem with Django-1.3 beta
Guys!! I'm really enthusiastic in learning django and learnt a bit on Django-1.2 but then I installed 1.3 version which is ok till I run the server using the command "python manage.py runserver". It's giving a huge error. I can't figure out a way to solve this. And error is given as : Traceback (most recent call last):...
[ "This can happen if you have two versions installed. Delete django (/usr/local/lib/python2.6/dist-packages/django) Just delete the whole folder. Now reinstall Django 1.3 and it should work.\n", "To avoid problems like that in the future, use virtualenv\n" ]
[ 21, 4 ]
[]
[]
[ "django", "manage.py", "python" ]
stackoverflow_0004883802_django_manage.py_python.txt
Q: How do I catch all possible errors with url fetch (python)? In my application users enter a url and I try to open the link and get the title of the page. But I realized that there can be many different kinds of errors, including unicode characters or newlines in titles and AttributeError and IOError. I first tried...
How do I catch all possible errors with url fetch (python)?
In my application users enter a url and I try to open the link and get the title of the page. But I realized that there can be many different kinds of errors, including unicode characters or newlines in titles and AttributeError and IOError. I first tried to catch each error, but now in case of a url fetch error I want...
[ "You can use except without specifying any type to catch all exceptions.\nFrom the python docs http://docs.python.org/tutorial/errors.html:\nimport sys\n\ntry:\n f = open('myfile.txt')\n s = f.readline()\n i = int(s.strip())\nexcept IOError as (errno, strerror):\n print \"I/O error({0}): {1}\".format(er...
[ 2, 2 ]
[]
[]
[ "google_app_engine", "python", "urlfetch" ]
stackoverflow_0005207508_google_app_engine_python_urlfetch.txt
Q: Python MatPlot bar function arguments I am trying to create a bar graph using the matplot library but I cant figure out what the arguments are for the function. The documentation says bar(left, height), but I don't know how to put in my data [which is a list of numbers called x] in here. It tells me that the heig...
Python MatPlot bar function arguments
I am trying to create a bar graph using the matplot library but I cant figure out what the arguments are for the function. The documentation says bar(left, height), but I don't know how to put in my data [which is a list of numbers called x] in here. It tells me that the height should be a scalar when I put it as a nu...
[ "A simple thing you can do:\nplt.bar(range(len(x)), x)\n\nleft is the left ends of the bars. You're telling it where to place the bars on the horizontal axis. Here's something you can play around with until you get it:\n>>> import matplotlib.pyplot as plt\n>>> plt.bar(range(10), range(20, 10, -1))\n>>> plt.show()...
[ 4, 2 ]
[]
[]
[ "graph", "matplotlib", "python" ]
stackoverflow_0005207646_graph_matplotlib_python.txt
Q: Better keyboard interrupt detection for this threaded Spinner class Ok, I've wrote this class based in a bunch of others Spinner classes that I've googled in Google Code Search. It's working as intended, but I'm looking for a better way to handle KeyboardInterrupt and SystemExit exceptions. Is there better approac...
Better keyboard interrupt detection for this threaded Spinner class
Ok, I've wrote this class based in a bunch of others Spinner classes that I've googled in Google Code Search. It's working as intended, but I'm looking for a better way to handle KeyboardInterrupt and SystemExit exceptions. Is there better approaches? Here's my code: #!/usr/bin/env python import itertools import sys im...
[ "You probably don't need to worry about catching SystemExit as it is raised by sys.exit(). You might want to catch it to clean up some resources just before your program exits.\nThe other way to catch KeyboardInterrupt is to register a signal handler to catch SIGINT. However for your example using try..except makes...
[ 2 ]
[]
[]
[ "exception_handling", "keyboardinterrupt", "python", "spinner" ]
stackoverflow_0005205774_exception_handling_keyboardinterrupt_python_spinner.txt
Q: How To Encode a Flash Parameter in Python I'm trying to generate an embeded flash widget on a page with Python using a dynamic parameter. Here's the code I currently have... <embed src='http://musiclibre.org/dark_player' width='200' height='500' wmode='transparent' flashVars='http://pipes.yahoo.com/pipes/pipe.run?...
How To Encode a Flash Parameter in Python
I'm trying to generate an embeded flash widget on a page with Python using a dynamic parameter. Here's the code I currently have... <embed src='http://musiclibre.org/dark_player' width='200' height='500' wmode='transparent' flashVars='http://pipes.yahoo.com/pipes/pipe.run?_id=39d7e59de5284e033c7019e12f02467b&artist={{q...
[ "The flashvars are encoded as a standard URL query string. You can use Python's urllib.parse module to easily convert your string into this format.\nFrom Flash you can access flashvars using the FlexGlobals.topLevelApplication.parameters dictionary (Application.application.parameters if you are using an older SDK)....
[ 1 ]
[]
[]
[ "encoding", "flash", "python" ]
stackoverflow_0005207934_encoding_flash_python.txt
Q: non-prime factorings with some repeats Let's say we have numbers factors, for example 1260: >>> factors(1260) [2, 2, 3, 3, 5, 7] Which would be best way to do in Python combinations with every subproduct possible from these numbers, ie all factorings, not only prime factoring, with sum of factors less than max_pr...
non-prime factorings with some repeats
Let's say we have numbers factors, for example 1260: >>> factors(1260) [2, 2, 3, 3, 5, 7] Which would be best way to do in Python combinations with every subproduct possible from these numbers, ie all factorings, not only prime factoring, with sum of factors less than max_product? If I do combinations from the prime f...
[ "What you are looking for is more commonly called a divisor. This answers to this question may help you.\n", "from __future__ import print_function\nimport itertools\nimport operator\n\ndef partition(iterable, chain=itertools.chain, map=map):\n # http://code.activestate.com/recipes/576795/\n # In [1]: list(...
[ 1, 1, 1 ]
[]
[]
[ "combinations", "factoring", "math", "python" ]
stackoverflow_0005207430_combinations_factoring_math_python.txt
Q: Customize inline_formset field display of foreign key I have a model called Access that links to two other models. class Access (models.Model): portfolio_id = models.ForeignKey(Portfolio) user_id = models.ForeignKey(User) title = models.CharField(max_length=30, null=True, blank=True) access_rights ...
Customize inline_formset field display of foreign key
I have a model called Access that links to two other models. class Access (models.Model): portfolio_id = models.ForeignKey(Portfolio) user_id = models.ForeignKey(User) title = models.CharField(max_length=30, null=True, blank=True) access_rights = models.PositiveIntegerField(choices=ACCESS_CHOICES) I ha...
[ "Well, if you wanted to type in usernames, a choice field is not the way to go.\nUse a CharField which is a <input type='text'> and override the clean_FOO method to validate the input into a user instance or raise an error message.\nclass UserAccessForm(forms.ModelForm):\n user_id = forms.CharField()\n\n clas...
[ 1 ]
[]
[]
[ "django", "inline_formset", "python" ]
stackoverflow_0005207878_django_inline_formset_python.txt
Q: python ctypes throwing error? so far I've gotten a DLL that wasn't meant for python to work with it, and types return: I just can't pass it arguments because I'm doing it wrong and I don't quite understand the documentation on how I'm supposed to do things. Basically, the function in the DLL I'm testing is named "...
python ctypes throwing error?
so far I've gotten a DLL that wasn't meant for python to work with it, and types return: I just can't pass it arguments because I'm doing it wrong and I don't quite understand the documentation on how I'm supposed to do things. Basically, the function in the DLL I'm testing is named "iptouint". It takes a c_char_p and ...
[ "try simply indicating ctypes the argtypes it takes and the ones it returns:\nnDll = ctypes.WinDLL('ndll.dll')\nnDll.restype = ctypes.c_double\nnDll.argtypes = [ctypes.c_char_p]\n\nresult = nDll.iptouint(\"12.345.67.890\").value\n\nAlthough, consider these points:\n1) if, as the name indicates, this converts an IPv...
[ 2 ]
[]
[]
[ "ctypes", "dll", "python" ]
stackoverflow_0005207783_ctypes_dll_python.txt
Q: Add element to line I have a log file with (space delimited) numbers. The problem is that the file is too big for autoit (1gig file, memory issues) and I've seen some python magic. I want to Add an element after the 3rd Remove elements 4-6 Do this as fast as possible but with respect to memory limits. 1 ...
Add element to line
I have a log file with (space delimited) numbers. The problem is that the file is too big for autoit (1gig file, memory issues) and I've seen some python magic. I want to Add an element after the 3rd Remove elements 4-6 Do this as fast as possible but with respect to memory limits. 1 2 3 4 5 6 7 8 9 1 2 3 A 7...
[ "Assuming Windows, I'd probably grab a copy of gawk and do it with much less hassle than python.\nc:\\gawk '{print $1 \" \" $2 \" \" $3 \" added \" $7 \" \" $8 \" \" $9}' bigfile.log >> outputfile.log\n\nDisclaimer: I don't have a Windows machine around to test this, but it would work on the Linux machine I'm curre...
[ 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005208230_python.txt
Q: preventing newline after wxpython TextCtrl.WriteText() I have a shell-like console for my app, which prompts with ">>>" after every command. The problem is every time I have my shell WriteText(">>> "), it also appends a new line. The user can backspace up to the correct line, but this just looks terrible. Any way ...
preventing newline after wxpython TextCtrl.WriteText()
I have a shell-like console for my app, which prompts with ">>>" after every command. The problem is every time I have my shell WriteText(">>> "), it also appends a new line. The user can backspace up to the correct line, but this just looks terrible. Any way to fix it?
[ "I suspect you are declaring your TextCtrl to be of style wx.TE_PROCESS_ENTER and then binding the EVT_TEXT_ENTER event - only because I ran into the same problem when I tried that.\nMy first instinct was to write a method to process wx.EVT_TEXT_ENTER that would then use the TextCtrl:Remove() method. This method on...
[ 6 ]
[]
[]
[ "python", "textctrl", "wxpython", "wxwidgets" ]
stackoverflow_0005200961_python_textctrl_wxpython_wxwidgets.txt
Q: A row in MySQL doesn't change, even after I update it in mysql if __name__ == "__main__": while True: results = None results = Decay.objects.filter(next_decay_at__lte=datetime.datetime.now()) for r in results: print r.next_decay_at time.sleep(10) For some reason, e...
A row in MySQL doesn't change, even after I update it in mysql
if __name__ == "__main__": while True: results = None results = Decay.objects.filter(next_decay_at__lte=datetime.datetime.now()) for r in results: print r.next_decay_at time.sleep(10) For some reason, even if I update "next_decay_at" in the table, this Decay.objects.fil...
[ "Read about Django's transaction handling.\n", "QuerySet caches the results. To quote the docs:\n\nIn a newly created QuerySet, the cache is empty. The first time a QuerySet is evaluated -- and, hence, a database query happens -- Django saves the query results in the QuerySet's cache and returns the results that ...
[ 0, 0, 0 ]
[]
[]
[ "database", "django", "mysql", "python" ]
stackoverflow_0005060185_database_django_mysql_python.txt
Q: CouchDB - filter latest log per logged instance from a list I could use some help filtering distinct values from a couchdb view. I have a database that stores logs with information about computers. Periodically new logs for a computer are written to the db. A bit simplified i store entries like these: { "name":...
CouchDB - filter latest log per logged instance from a list
I could use some help filtering distinct values from a couchdb view. I have a database that stores logs with information about computers. Periodically new logs for a computer are written to the db. A bit simplified i store entries like these: { "name": "NAS", "os": "Linux", "timestamp": "2011-03-03T16:26:39Z",...
[ "Here is what I do. This is borderline CouchDB abuse however I have had much success.\nUsually, reduce will compute a sum, or a count, or something like that. However, think of reduce as an elimination tournament. Many values go in. Only one comes out. A reduction! Repeat over and over and you have the ultimate win...
[ 6 ]
[]
[]
[ "couchdb", "couchdbkit", "mapreduce", "python" ]
stackoverflow_0005198023_couchdb_couchdbkit_mapreduce_python.txt
Q: Extending auth.User model, proxied fields, and Django admin (Edit: I know that there's a totally separate feature in Django called "Proxy Models". That feature doesn't help me, because I need to be able to add fields to UserProfile.) So I'm starting a new Django app and I'm creating a UserProfile model which is ...
Extending auth.User model, proxied fields, and Django admin
(Edit: I know that there's a totally separate feature in Django called "Proxy Models". That feature doesn't help me, because I need to be able to add fields to UserProfile.) So I'm starting a new Django app and I'm creating a UserProfile model which is a extension of django.contrib.auth.models.User and failed attribu...
[ "Keep it simple. Here's an example of a UserProfile model from a library we use:\nclass UserProfile(models.Model):\n user = models.OneToOneField(User)\n accountcode = models.PositiveIntegerField(null=True, blank=True)\n\nThat's it. Don't bother with the __getattr__ override. Customise the admin interface inst...
[ 2, 0, 0 ]
[]
[]
[ "django", "django_admin", "django_models", "proxy_classes", "python" ]
stackoverflow_0005208060_django_django_admin_django_models_proxy_classes_python.txt
Q: Trying to combine lists with DateTimeField and date object in Django I've got 2 Django query lists with a Title and a Created_At DateTimeField (Articles and Projects), I have another list which is the result of a python function that returns a string Title and a Create_At date object. I want to chain these lists t...
Trying to combine lists with DateTimeField and date object in Django
I've got 2 Django query lists with a Title and a Created_At DateTimeField (Articles and Projects), I have another list which is the result of a python function that returns a string Title and a Create_At date object. I want to chain these lists together so I can combine them and sort the results by their Date fields - ...
[ "Judging by the error message, apparently instance.created is a tuple for one of your chained iterables.\nMy guess is that it's whichever item is the \"result of a python function that returns a string Title and Create_At date object\" that you were talking about, as a DateTimeField wouldn't return a tuple.\nDoes t...
[ 0, 0 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0005208195_django_django_views_python.txt
Q: adieu's openid patch causes a mismatch in django-openid-consumer I've been using the django with openid using the django-openid-consumer middleware, which works generally. However, I was having an issue logging in using an account from Google apps (which would redirect me to my normal gmail account). A google em...
adieu's openid patch causes a mismatch in django-openid-consumer
I've been using the django with openid using the django-openid-consumer middleware, which works generally. However, I was having an issue logging in using an account from Google apps (which would redirect me to my normal gmail account). A google employee recommended installing adieu-python-openid, which supposedly co...
[ "May be patch was written for a previous version of openid? and the one you are using could have changed the model. \n" ]
[ 0 ]
[]
[]
[ "django", "google_openid", "openid", "python" ]
stackoverflow_0005205190_django_google_openid_openid_python.txt
Q: Front end html/css themes for python/django programming Are there some frontend/skeleton-like html templates with a nice web2 flavor ready to be used with python/django? I know it could be any html and probably nothing specifically for python/django, but my question is, maybe the python/django community is using s...
Front end html/css themes for python/django programming
Are there some frontend/skeleton-like html templates with a nice web2 flavor ready to be used with python/django? I know it could be any html and probably nothing specifically for python/django, but my question is, maybe the python/django community is using something in contrib already available in this sense ... somet...
[ "Sounds like you are looking for ways to design the web page, so the answer is in the CSS field.\nI like the YAML CSS framework. Needs a bit of reading, but is very flexible.\n", "Blue print CSS is a another framework which you can use. It very simple than YAML one.\nAnd have a look at YAML builder - this is brow...
[ 0, 0 ]
[]
[]
[ "django", "frontend", "python" ]
stackoverflow_0005203995_django_frontend_python.txt
Q: Performance between Django and raw Python I was wondering what the performance difference is between using plain python files to make web pages and using Django. I was just wondering if there was a significant difference between the two. Thanks A: Django IS plain Python. So the execution time of each like statem...
Performance between Django and raw Python
I was wondering what the performance difference is between using plain python files to make web pages and using Django. I was just wondering if there was a significant difference between the two. Thanks
[ "Django IS plain Python. So the execution time of each like statement or expression will be the same. What needs to be understood, is that many many components are put together to offer several advantages when developing for the web:\n\nRemoval of common tasks into libraries (auth, data access, templating, routing)...
[ 11, 5, 3, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005208158_django_python.txt
Q: Plone External methods help I'm having trouble getting a simple external methods in plone working correctly. In my extensions folder I have a python script named blast_query.py code below: def print_query(self, x): print(x) my external methods looks like: Id: run_blast_query Title: Module Name: blast_query F...
Plone External methods help
I'm having trouble getting a simple external methods in plone working correctly. In my extensions folder I have a python script named blast_query.py code below: def print_query(self, x): print(x) my external methods looks like: Id: run_blast_query Title: Module Name: blast_query Function Name: print_query My pyt...
[ "You should call your external method by id:\ncontext.run_blast_query(context,query)\n\n", "This is a problem with your understanding of python methods.\nI would expect:\ncontext.print_query(context,query)\n\nto return:\nTypeError: print_query() takes exactly 2 arguments (3 given)\n\nRemember, in python, obj.meth...
[ 1, 0, 0 ]
[]
[]
[ "plone", "python", "zope" ]
stackoverflow_0003151909_plone_python_zope.txt
Q: Sending django signals from django-admin command? I have an unsual problem. In my Django application I use signals to send emails. All of signals work except for the one fired from django-admin command - django.core.management.base.NoArgsCommand (which is run through manage.py). I checked my signal in different pl...
Sending django signals from django-admin command?
I have an unsual problem. In my Django application I use signals to send emails. All of signals work except for the one fired from django-admin command - django.core.management.base.NoArgsCommand (which is run through manage.py). I checked my signal in different places, it works except for this place. Here's the code w...
[ "The shortcut is :\nstart = datetime.now() + timedelta(days=4)\nend = start + timedelta(days=1)\nads=Advertisement.objects.filter(visible_till__gte=start).filter(visible_till__lt=end)\n\nCan you post your project structure here? Your code looks good to me.\n", "The only thing I can think of, is that the signal ha...
[ 2, 1 ]
[]
[]
[ "django", "django_manage.py", "django_signals", "python" ]
stackoverflow_0005208588_django_django_manage.py_django_signals_python.txt
Q: merging lists in python Possible Duplicate: Python - merge items of two lists into a list of tuples There are two lists x = [1,2,3,4,5] y = ['a','b','c','d','e'] How can I get the list z = [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')] A: z = zip(x,y) will do your job. >>> x = [1,2,3,4,5] >>> y = ['a','...
merging lists in python
Possible Duplicate: Python - merge items of two lists into a list of tuples There are two lists x = [1,2,3,4,5] y = ['a','b','c','d','e'] How can I get the list z = [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]
[ "z = zip(x,y)\n\nwill do your job.\n>>> x = [1,2,3,4,5]\n>>> y = ['a','b','c','d','e']\n>>> z = zip(x,y)\n>>> z\n[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]\n\n", "Given your input, the builtin function zip(x, y) will provide the output, that you want.\nsee: http://docs.python.org/library/functions.html#zi...
[ 3, 2, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0005209441_list_python.txt
Q: Performing multiple searches of a term in Twitter I have little working knowledge of python. I know that there is something called a Twitter search API, but I'm not really sure what I'm doing. I know what I need to do: I need point data for a class. I thought I would just pull up a map of the world in a GIS applic...
Performing multiple searches of a term in Twitter
I have little working knowledge of python. I know that there is something called a Twitter search API, but I'm not really sure what I'm doing. I know what I need to do: I need point data for a class. I thought I would just pull up a map of the world in a GIS application, select cities that have x population or larger, ...
[ "A tweet itself comes with a geo tag. But it is a new feature and majority tweets do not have it. So it is not possible to search for all tweets containing \"Gaddafi\" from a city given the city name.\nWhat you could do is the reverse, you search for \"Gaddafi\" first (regardless of geo location), using search api....
[ 0 ]
[]
[]
[ "api", "python", "twitter" ]
stackoverflow_0005209003_api_python_twitter.txt
Q: Access Violation with wxPythons CallLater I'm attempting to convert some of my code from Tkinter to wxPython. Currently I'm trying to create a function that continually loops, updating the time. However, I have run into some problems. Whenever I close the program, a window pops up, and gives me the following warni...
Access Violation with wxPythons CallLater
I'm attempting to convert some of my code from Tkinter to wxPython. Currently I'm trying to create a function that continually loops, updating the time. However, I have run into some problems. Whenever I close the program, a window pops up, and gives me the following warning. Access violation at address 1E058497 in mo...
[ "what you can do is:\n(1)\nself.scheduled_call = wx.CallLater(1000, self.tick)\nduring program close, cancel via, xxx.scheduled_call.??????()\nI forgot the exact name of the method, please check wx docs.\nOR if the above is not possible\n(2) set a boolean variable in the instance, that controls the call.\nif self.v...
[ 1 ]
[]
[]
[ "python", "tkinter", "wxpython" ]
stackoverflow_0005208436_python_tkinter_wxpython.txt
Q: What are the advantages/disadvantages of using Jython/IronPython/Pyjamas? EDIT Okay, rookie here so please bear with me. What I'm trying to ask is the following: Is it plausible for a Python-syntax fan to use one of these options while other team members "plain vanilla" version? Is it a matter of personal prefe...
What are the advantages/disadvantages of using Jython/IronPython/Pyjamas?
EDIT Okay, rookie here so please bear with me. What I'm trying to ask is the following: Is it plausible for a Python-syntax fan to use one of these options while other team members "plain vanilla" version? Is it a matter of personal preference, or would it require converting other people to using these technologies ...
[ "You are talking about two different things.\nFirst, Jython and IronPython are Python implementations that you can embed in a Java or C# application to provide scripting capability. This reduces the amount of code that you have to write overall. Or you can look at them as a way to glue together and leverage an exis...
[ 5, 0 ]
[]
[]
[ "ironpython", "jython", "pyjamas", "python" ]
stackoverflow_0005098183_ironpython_jython_pyjamas_python.txt
Q: Problem of setting up a python app Hey guys I'm new to Python, I want to install this python app called mirosubs on my VPS, and I followed the installation guide in this github pages, when I got to the step 8: python manage.py syncdb I got the following error: root@makserver:/usr/local/src/mirosubs# python manag...
Problem of setting up a python app
Hey guys I'm new to Python, I want to install this python app called mirosubs on my VPS, and I followed the installation guide in this github pages, when I got to the step 8: python manage.py syncdb I got the following error: root@makserver:/usr/local/src/mirosubs# python manage.py syncdb Traceback (most recent call ...
[ "The module haystack is trying to import a type called Thumbnail but can't find it. Do a search through the source for Thumbnail and try to determine what's happening.\n" ]
[ 0 ]
[]
[]
[ "django_haystack", "python" ]
stackoverflow_0005209801_django_haystack_python.txt
Q: Finding root/zeros of a function I am trying to find a root of a function by using the bisection method stating that : if f(a)*f(b) < 0 then a root exists, then you repeat with f(a)*f(c)<0 where c = (a+b)/2 but im not sure how to fix the code so it works properly. This is my code but its not working prope...
Finding root/zeros of a function
I am trying to find a root of a function by using the bisection method stating that : if f(a)*f(b) < 0 then a root exists, then you repeat with f(a)*f(c)<0 where c = (a+b)/2 but im not sure how to fix the code so it works properly. This is my code but its not working properly from scipy import * from numpy imp...
[ "I think your one problem is with:\n x = a + c\n\nSince c = (a + b)*.5, you don't need to add in a here...\nUpdate\nYou don't seem to check if fa * fb < 0 to start, and I also don't see where you're narrowing your bounds: you should either reassign a or b to c in your loop and then recalculate c.\nCode It's been...
[ 0, 0, 0, 0 ]
[]
[]
[ "function", "python", "root" ]
stackoverflow_0005208239_function_python_root.txt
Q: XMPP bot status message on GAE GAE XMPP documentation states that is not possible to set status message for an app ( https://code.google.com/appengine/docs/python/xmpp/overview.html#Google_Talk_User_Status ). On other hand, I've vark IM client has status message set. Obviously it is not hosted on GAE, but it is ...
XMPP bot status message on GAE
GAE XMPP documentation states that is not possible to set status message for an app ( https://code.google.com/appengine/docs/python/xmpp/overview.html#Google_Talk_User_Status ). On other hand, I've vark IM client has status message set. Obviously it is not hosted on GAE, but it is possible to set status message for a...
[ "Take a look at https://code.google.com/appengine/docs/python/xmpp/overview.html#Sending_Application_Status\nYou can set the status message through the send_presence method:\nxmpp.send_presence(to_jid, status=\"My app's status\")\n\n" ]
[ 1 ]
[]
[]
[ "bots", "google_app_engine", "python", "xmpp" ]
stackoverflow_0003598901_bots_google_app_engine_python_xmpp.txt
Q: FTP filename encoding Hi I use twisted library to connect to FTP server but I have problem with filename encoding. I receive 'Illusion-N\xf3z.txt' so its not unicode. Is there any FTP command to force specific encoding? Thanks in advance! MK A: There are two possibilities: FTP is not unicode aware. It looks l...
FTP filename encoding
Hi I use twisted library to connect to FTP server but I have problem with filename encoding. I receive 'Illusion-N\xf3z.txt' so its not unicode. Is there any FTP command to force specific encoding? Thanks in advance! MK
[ "There are two possibilities:\n\nFTP is not unicode aware. It looks like the server you're talking to in this example is sending Latin-1 encoded bytes. So you need to decode the bytes using that encoding when you receive them.\nThere is an RFC which updates FTP to be UTF-8-aware. Check the results of the FEAT co...
[ 4, 2 ]
[]
[]
[ "encoding", "ftp", "python", "twisted" ]
stackoverflow_0004966856_encoding_ftp_python_twisted.txt
Q: Showing what Twitter followers are followed by friends in Python/Django I'm building a quick part of my app that looks at a user's followers, and highlights which ones are followed by people the user follows (friends). I'm wondering two things: Is there a more efficient way to do this? Seems like this will run up...
Showing what Twitter followers are followed by friends in Python/Django
I'm building a quick part of my app that looks at a user's followers, and highlights which ones are followed by people the user follows (friends). I'm wondering two things: Is there a more efficient way to do this? Seems like this will run up Twitter's API limits because I need to check friends of every one the user's...
[ "For the second part of your question:\nimport collections\n\nfollowers_that_friends_follow = collections.defaultdict(list)\nfor f in friends:\n ff = api.GetFriendsIDs(f)['ids']\n users = followers_not_friends.intersection(ff)\n for user in users:\n followers_that_friends_follow[user].append(f)\n\nt...
[ 1 ]
[]
[]
[ "django", "python", "twitter" ]
stackoverflow_0005208393_django_python_twitter.txt
Q: How can I confidently set the attributes of dispatched objects using win32com I have been struggling to assign an attribute to an object (or is it an instance) xl=win32com.client.Dispatch('Excel.Application') xl.Visible=0 srce=xl.Workbooks.Open('myexcelfile') srce.CheckCompatibility='False' If I query the srce o...
How can I confidently set the attributes of dispatched objects using win32com
I have been struggling to assign an attribute to an object (or is it an instance) xl=win32com.client.Dispatch('Excel.Application') xl.Visible=0 srce=xl.Workbooks.Open('myexcelfile') srce.CheckCompatibility='False' If I query the srce object about its CheckCompatibility attribute I get a response of 'False' >>> srce.C...
[ "I'm not sure, but I suspect what's happening is that saving the file in XLS form is resetting the value of CheckCompatibility since the default value of that property is True for Excel 97-2003 binary workbooks.\nIn any case, there are multiple reasons why Excel might display a dialog when saving a file, not just t...
[ 6 ]
[]
[]
[ "attributes", "excel", "python", "win32com" ]
stackoverflow_0005208624_attributes_excel_python_win32com.txt
Q: user_id may not be NULL in django i have two model User and Customer I have customer = models.ForeignKey(Customer, related_name='orders') in Customer model, I want both User and Customer form to be saved together and if there is error in one form then both shouldnt be saved. When i created a view to save both it...
user_id may not be NULL in django
i have two model User and Customer I have customer = models.ForeignKey(Customer, related_name='orders') in Customer model, I want both User and Customer form to be saved together and if there is error in one form then both shouldnt be saved. When i created a view to save both it has given me error that mainsiteapp_cu...
[ "Customer.user = u\nif customerform.is_valid():\n c = customerform.save(commit=False)\n\nYou're setting the model's class variable user here. Instead you want to set the customer's user property like c.user = u.\n", "You just need to check if both userform and customerform are valid using an and statement\ndef...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005209862_python.txt
Q: Handle Excel Message Box from Within Python using Win32com I am trying to process some files that were supposed to be xls files but it turns out they are something else (according to some help I received on the python-excel board these are Web Archive files or (Single File Web Page (*.mht, *.mhtml) ). I can open ...
Handle Excel Message Box from Within Python using Win32com
I am trying to process some files that were supposed to be xls files but it turns out they are something else (according to some help I received on the python-excel board these are Web Archive files or (Single File Web Page (*.mht, *.mhtml) ). I can open the files with Excel but I get a message that has to be dismisse...
[ "Please see my answer to your other question on this issue.\nThe reason it doesn't display a dialog box for the second call to SaveAs(...) is that the file format is not changing on the second call, the file format only changes on the first call.\nWhat you want is to add\n>>> xl.DisplayAlerts = False\n\nbefore call...
[ 8 ]
[]
[]
[ "excel", "messagebox", "python", "win32com" ]
stackoverflow_0005207955_excel_messagebox_python_win32com.txt
Q: Django aggregation query on related one-to-many objects Here is my simplified model: class Item(models.Model): pass class TrackingPoint(models.Model): item = models.ForeignKey(Item) created = models.DateField() data = models.IntegerField() class Meta: unique_together = ('item', 'creat...
Django aggregation query on related one-to-many objects
Here is my simplified model: class Item(models.Model): pass class TrackingPoint(models.Model): item = models.ForeignKey(Item) created = models.DateField() data = models.IntegerField() class Meta: unique_together = ('item', 'created') In many parts of my application I need to retrieve a se...
[ "Here's a single query that will provide (TrackingPoint, Item)-pairs:\nTrackingPoint.objects.annotate(max=Max('item__trackingpoint__created')).filter(max=F('created')).select_related('item').order_by('created')\n\nYou would have to query for items without TrackingPoints separately.\n", "This isn't directly answer...
[ 7, 1 ]
[]
[]
[ "django", "django_aggregation", "django_orm", "orm", "python" ]
stackoverflow_0002839145_django_django_aggregation_django_orm_orm_python.txt
Q: Python C-API and Numpy: core dump on import_array //testNumpy.c #include<Python.h> #include<numpy/arrayobject.h> #include<stdio.h> int main(){ printf("import_array\n");fflush(stdout); import_array(); printf("import_array done\n");fflush(stdout); } $ gcc -I/usr/include/python2.6 -lpython2.6 testNumpy.c...
Python C-API and Numpy: core dump on import_array
//testNumpy.c #include<Python.h> #include<numpy/arrayobject.h> #include<stdio.h> int main(){ printf("import_array\n");fflush(stdout); import_array(); printf("import_array done\n");fflush(stdout); } $ gcc -I/usr/include/python2.6 -lpython2.6 testNumpy.c&&./a.out import_array Segmentation fault (core dumped)...
[ "For starters, you did not initialize Python properly. Call Py_Initialize() before trying to initialize NumPy.\n" ]
[ 4 ]
[]
[]
[ "coredump", "numpy", "python", "python_c_api" ]
stackoverflow_0005210090_coredump_numpy_python_python_c_api.txt
Q: What's the best way to handle source-like data files in a web application? I have about 30 MB of textual data that is core to the algorithms I use in my web application. On the one hand, the data is part of the algorithm and changes to the data can cause an entire algorithm to fail. This is why I keep the data in ...
What's the best way to handle source-like data files in a web application?
I have about 30 MB of textual data that is core to the algorithms I use in my web application. On the one hand, the data is part of the algorithm and changes to the data can cause an entire algorithm to fail. This is why I keep the data in text files in my source control, and all changes are auto-tested (pre-commit). I...
[ "Okay, here's an idea:\n\nShip all the data as is done now.\nHave the installation script install it in the appropriate databases.\nLet users modify this database and give them a button \"restore to original\" that simply reinstalls from the text file.\n\nAlternatively, this route may be easier, esp. when upgrading...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005210318_python.txt
Q: Django creating relation one-to-many I started learning Django recently, and can't find answer for a simple question. I have 2 tables: Client and Addres. ------------------ CLIENT | ------------------ ID | NAME | ADDRES_REF | ------------------ ------------------ ADDRES | ------------------ ID | NAME | CITY | COL...
Django creating relation one-to-many
I started learning Django recently, and can't find answer for a simple question. I have 2 tables: Client and Addres. ------------------ CLIENT | ------------------ ID | NAME | ADDRES_REF | ------------------ ------------------ ADDRES | ------------------ ID | NAME | CITY | COLLECTION | ------------------ The relation...
[ "This could be helpfull - One to many. It's an official documentation, so nothing special... \nI'm not sure if I understood question correctly, but what if you will define collection field as foreign key to Client? Then you should be able to do something like\naddress = Address.objects.get(collection=123)\n\n", "...
[ 3, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005210310_django_python.txt
Q: Is there a framework agnostic captcha module for Python? I want to add captcha support to some forms, I'm using a very lightweight Python framework, bottle, and I don't want to use something provided by an online service, like recaptcha. Is there something already available in this direction, or is messing around ...
Is there a framework agnostic captcha module for Python?
I want to add captcha support to some forms, I'm using a very lightweight Python framework, bottle, and I don't want to use something provided by an online service, like recaptcha. Is there something already available in this direction, or is messing around with PIL the only solution?
[ "Take a look at SkimpyGimpy, it's a python package that let's you generate CAPTCHA images and audio files. This is the package most framework-specific captcha generators that do not use re-captcha rely on.\nIt's a bit primitive, you may want to look at the source of collective.captcha as an example of how to use Sk...
[ 2, 1 ]
[]
[]
[ "captcha", "python" ]
stackoverflow_0005209945_captcha_python.txt
Q: CUPP (pentest) on google app engine Do you see any limitations for cupp (http://www.securityfocus.com/tools/7320) running on GAE? A: I see a few problems right off: You'll need to create a web interface to the script GAE does not allow long running tasks and this looks like it could take a while. You'd need t...
CUPP (pentest) on google app engine
Do you see any limitations for cupp (http://www.securityfocus.com/tools/7320) running on GAE?
[ "I see a few problems right off:\n\nYou'll need to create a web interface to the script\nGAE does not allow long running tasks and this looks like it could take a while. You'd need to recode it to break the work up into chunks.\nOutbound FTP (for fetching word lists) is not supported on GAE\nLocal file write acces...
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005206838_google_app_engine_python.txt
Q: PyGTK custom ComboBox behavior I'm trying to create a custom ComboBox that behaves like the one in here: http://chir.ag/projects/name-that-color/ I've got two problems right now: I can't seem to find a way to have a scrollbar on the side; the gtk.rc_parse_string function should do that, since the ComboBox widget ...
PyGTK custom ComboBox behavior
I'm trying to create a custom ComboBox that behaves like the one in here: http://chir.ag/projects/name-that-color/ I've got two problems right now: I can't seem to find a way to have a scrollbar on the side; the gtk.rc_parse_string function should do that, since the ComboBox widget has a "appears-as-list" style proper...
[ "The problem was the self.show_all() line. Also, you can't have a list AND a wrap_width != 1\n" ]
[ 1 ]
[]
[]
[ "coding_style", "combobox", "gtk", "list", "python" ]
stackoverflow_0005172916_coding_style_combobox_gtk_list_python.txt
Q: Moving a QGraphicsItem around a central point in PyQt4 I'm using Python 2.7 and PyQt4. I am trying to have a half-circle object that is a QGraphicsItem. I want to be able to move it using the mouse, by clicking and dragging. I can create the object and move it around with the mouse by setting the flag ItemIsMovabl...
Moving a QGraphicsItem around a central point in PyQt4
I'm using Python 2.7 and PyQt4. I am trying to have a half-circle object that is a QGraphicsItem. I want to be able to move it using the mouse, by clicking and dragging. I can create the object and move it around with the mouse by setting the flag ItemIsMovable. Now the half-circle moves around freely but I want it to ...
[ "you can use QGraphicsItem::mouseMoveEvent event to track item's movements within the scene and correct its position once it's moved off the restricted area. Pls, check if an example below would work for you: \nimport sys\nfrom PyQt4 import QtGui, QtCore\n\nclass TestEclipseItem(QtGui.QGraphicsEllipseItem):\n de...
[ 2 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qgraphicsitem", "qt" ]
stackoverflow_0005207305_pyqt_pyqt4_python_qgraphicsitem_qt.txt
Q: Facebook Authentication from PHP-SDK to Python I'm "translating" a simple app I made with PHP to Python in order to use it in Google App Engine. In PHP I have the session check and the redirection with this code: $fbuser = null; $fb = null; //Start Facebook $fb = new Facebook(array( 'appId...
Facebook Authentication from PHP-SDK to Python
I'm "translating" a simple app I made with PHP to Python in order to use it in Google App Engine. In PHP I have the session check and the redirection with this code: $fbuser = null; $fb = null; //Start Facebook $fb = new Facebook(array( 'appId' => $appId, 'secret' => $s...
[ "I think this example from the SDK git repository will give you a hint.\n" ]
[ 0 ]
[]
[]
[ "authentication", "facebook", "google_app_engine", "php", "python" ]
stackoverflow_0005209783_authentication_facebook_google_app_engine_php_python.txt
Q: Sending object C from class A to class B I can't figure out how to design classes in my system. In classA I create object selenium (it simulates user actions at website). In this ClassA I create another objects like SearchScreen, Payment_Screen and Summary_Screen. # -*- coding: utf-8 -*- from selenium import selen...
Sending object C from class A to class B
I can't figure out how to design classes in my system. In classA I create object selenium (it simulates user actions at website). In this ClassA I create another objects like SearchScreen, Payment_Screen and Summary_Screen. # -*- coding: utf-8 -*- from selenium import selenium import unittest, time, re class OurSiteTe...
[ "If SearchScreen/PaymentScreen/SummaryScreen only performs test logic, it looks to me like you might as well just put that logic in utility methods of OurSiteTestCases.\nPossible design for the test_buy_coffee method (depending on what you actually do in SearchScreen et al):\ndef test_buy_coffee(self):\n\n sel =...
[ 3, 3, 1 ]
[]
[]
[ "class_design", "design_patterns", "python" ]
stackoverflow_0005165990_class_design_design_patterns_python.txt
Q: Python and multiprocessing... how to call a function in the main process? I would like to implement an async callback style function in python... This is what I came up with but I am not sure how to actually return to the main process and call the function. funcs = {} def runCallback(uniqueId): ''' I wan...
Python and multiprocessing... how to call a function in the main process?
I would like to implement an async callback style function in python... This is what I came up with but I am not sure how to actually return to the main process and call the function. funcs = {} def runCallback(uniqueId): ''' I want this to be run in the main process. ''' funcs[uniqueId]() def someF...
[ "To do exactly what you're trying to do, you're going to need to set up a signal handler in the parent process to run the callback (or just remove the callback function that the child runs if it doesn't need access to any of the parent process's memory), and have the child process send a signal, but if your logic g...
[ 4, 4 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0005208786_multiprocessing_python.txt
Q: Any Naive Bayesian Classifier in python? I have tried the Orange Framework for Naive Bayesian classification. The methods are extremely unintuitive, and the documentation is extremely unorganized. Does anyone here have another framework to recommend? I use mostly NaiveBayesian for now. I was thinking of using nl...
Any Naive Bayesian Classifier in python?
I have tried the Orange Framework for Naive Bayesian classification. The methods are extremely unintuitive, and the documentation is extremely unorganized. Does anyone here have another framework to recommend? I use mostly NaiveBayesian for now. I was thinking of using nltk's NaiveClassification but then they don't...
[ "The scikit-learn has an implementation of Gaussian naive Bayesian classifier. In general, the goal of this library is to provide a good trade off between code that is easy to read and use, and efficiency. Hopefully it should be a good library to learn of the algorithms work.\n", "This might be a good place to st...
[ 25, 13, 9, 3, 2, 0 ]
[]
[]
[ "machine_learning", "naivebayes", "python" ]
stackoverflow_0002580062_machine_learning_naivebayes_python.txt
Q: Can the python image module be extended? Can the python Image module be extended ? Basically its a class I think and I want to have added a numpy array representation of the image. If I know how to extend it, then I can add all other extensions I wish to add to it too I think, but I don't know how to build up on e...
Can the python image module be extended?
Can the python Image module be extended ? Basically its a class I think and I want to have added a numpy array representation of the image. If I know how to extend it, then I can add all other extensions I wish to add to it too I think, but I don't know how to build up on existing classes.
[ "You \"extend\" classes by subclassing them, as in\nclass MiniMath:\n def add(self, a, b):\n return a + b\n\nclass MoreMath(MiniMath):\n def sub(self, a, b):\n return a - b\n\nmm = MoreMath()\nprint mm.add(1, 2) # 3\nprint mm.sub(1, 2) # -1\n\nI suggest you read the Python tutorial first though....
[ 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0005210729_class_python.txt
Q: How to load a database of countries in a web application I am new to web application development, so sorry in advance if this question is too basic. The following are the details of the question: A] Platform being used -- google app engine with python, django. B] Tutorial link being used -- http://code.google.c...
How to load a database of countries in a web application
I am new to web application development, so sorry in advance if this question is too basic. The following are the details of the question: A] Platform being used -- google app engine with python, django. B] Tutorial link being used -- http://code.google.com/appengine/articles/djangoforms.html C] Question: In the app...
[ "Set the countries as a constant list:\nCOUNTRIES=['United States', 'England'...]\n\nIn your model:\ncountry=db.StringProperty(verbose_name='Country',required=False, choices=set(COUNTRIES))\n\nNow when you load your model form the select will be auto-populated from your countries list. \n" ]
[ 2 ]
[ "Just use \n<select>\n <option></option>\n</select>\n\nThanks\nJean\n" ]
[ -1 ]
[ "google_app_engine", "python" ]
stackoverflow_0005211516_google_app_engine_python.txt
Q: Solutions for freezing a pyqt4 application in Windows? Is there a workable and proven way to freeze a pyqt4 application in windows? I heard that there are some issues for py2exe. A: I used py2exe for a PyQt4 project at work but ended up switching to PyInstaller. py2exe worked great for the most part. I remember ...
Solutions for freezing a pyqt4 application in Windows?
Is there a workable and proven way to freeze a pyqt4 application in windows? I heard that there are some issues for py2exe.
[ "I used py2exe for a PyQt4 project at work but ended up switching to PyInstaller.\npy2exe worked great for the most part. I remember having to manually tell it to include the sip libraries in my setup.py file along with some others depending on the program. PyInstaller seems to handle this better in my opinion, alt...
[ 4 ]
[]
[]
[ "pyqt", "pyqt4", "python", "windows" ]
stackoverflow_0005202483_pyqt_pyqt4_python_windows.txt
Q: XPath: Select Current and Next Node's text by Current Node Attributes First of all, this is a spawn from my previous question. I have posted this again because I was advised to do so by the person whose answer I accepted in the original post as he felt that the question was not properly defined before. Here goes a...
XPath: Select Current and Next Node's text by Current Node Attributes
First of all, this is a spawn from my previous question. I have posted this again because I was advised to do so by the person whose answer I accepted in the original post as he felt that the question was not properly defined before. Here goes attempt 2: I am trying to get information out of this webpage. For clarity, ...
[ "The required single XPath expression to select the relevant data for all courses is quite messy, so here I am taking another approach, which can be used (if necessary at all) to produce that single XPath expression:\nThis simple XSLT transformation:\n<xsl:stylesheet version=\"1.0\"\n xmlns:xsl=\"http://www.w3.org/...
[ 2, 0 ]
[]
[]
[ "python", "scrapy", "xpath", "xslt" ]
stackoverflow_0005208843_python_scrapy_xpath_xslt.txt
Q: Setting up Pyramid Web Framework | FCGI on Shared Hosting How can I create a simple FCGI program in my ~/public_html that will be executed that will dispatch web requests to my pyramid website? In django, using the code below works fine for me: #!/usr/local/bin/python2.6 import sys import os sys.path.append('/ho...
Setting up Pyramid Web Framework | FCGI on Shared Hosting
How can I create a simple FCGI program in my ~/public_html that will be executed that will dispatch web requests to my pyramid website? In django, using the code below works fine for me: #!/usr/local/bin/python2.6 import sys import os sys.path.append('/home/username/local/lib/python2.6/site-packages') os.environ['DJ...
[ "I've not used FastCGI myself but the guide for hooking up a Paster-based WSGI app into FastCGI should be the same (ie Pylons, TurboGears, Pyramid, all use Paster for WSGI).\nThe guide that I found that seems to make sense to me is at: http://turbogears.org/2.1/docs/main/Deployment/FastCGI.html\nThe key to hooking ...
[ 1 ]
[]
[]
[ "fastcgi", "pyramid", "python" ]
stackoverflow_0005062923_fastcgi_pyramid_python.txt
Q: python class design (staticmethod vs method) What's the nicer way for methods that don't need any passed information (object instance or class) because for example they just do a simple conversion. @staticmethod or method ? class Foo(object): def __init__(self, trees): self.money = Foo.trees2money(tree...
python class design (staticmethod vs method)
What's the nicer way for methods that don't need any passed information (object instance or class) because for example they just do a simple conversion. @staticmethod or method ? class Foo(object): def __init__(self, trees): self.money = Foo.trees2money(trees) @staticmethod def trees2money(trees): ...
[ "The choice of the type of method depends on other factors.\nYou have two cases. The first case is when the method has to be part of the class interface - e.g. it has to be called by users, or it has to be overridable in subclasses, or it uses the information in self, or it's likely that in a future version of the ...
[ 8, 2, 0 ]
[]
[]
[ "oop", "python", "static_methods" ]
stackoverflow_0005212071_oop_python_static_methods.txt
Q: With Python, GAE and Tipfy, unable to pass a db.key as parameter for image retrieval Ok, so I'm playing around with tipfy, making a simple photo-gallery. I have a working solution using webbapp, this is my template, browse.htm, which stays the same in both examples: {% for pic in photo_list %} <tr> <td><img src=...
With Python, GAE and Tipfy, unable to pass a db.key as parameter for image retrieval
Ok, so I'm playing around with tipfy, making a simple photo-gallery. I have a working solution using webbapp, this is my template, browse.htm, which stays the same in both examples: {% for pic in photo_list %} <tr> <td><img src='getPic?img_id={{ pic.key }} '></img></td> <td>{{ pic.description }}</td> <td>{{ pic.d...
[ "So, I managed to get it to work, the solution was to change the template from\n{% for pic in photo_list %}\n <tr>\n <td><img src='getPic?img_id={{ pic.key }} '></img></td>\n\nTo\n{% for pic in photo_list %}\n <tr>\n  <td><img src='getPic?img_id={{ pic.key() }} '></img></td>\n\nAnoyone care to comment on why thi...
[ 1 ]
[]
[]
[ "google_app_engine", "python", "tipfy" ]
stackoverflow_0005209988_google_app_engine_python_tipfy.txt
Q: words in the list in Python How can I get a one word school from the list ['s', 'c', 'h', 'o', 'o', 'l']? Thanks! A: str.join(iterable) Return a string which is the concatenation of the strings in the iterable iterable. A TypeError will be raised if there are any non-string values in seq, including bytes objects...
words in the list in Python
How can I get a one word school from the list ['s', 'c', 'h', 'o', 'o', 'l']? Thanks!
[ "\nstr.join(iterable)\nReturn a string which is the concatenation of the strings in the iterable iterable. A TypeError will be raised if there are any non-string values in seq, including bytes objects. The separator between elements is the string providing this method.\n\nI.e. ''.join(parts)\nAs indicated in the de...
[ 9, 2, 1, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0005209304_list_python.txt
Q: Python comparing two CSV files when order of rows doesn't matter I have some code that creates a CSV file. The order of the rows it writes to the file can vary. I am writing a test to make sure the CSV file is what I expect. All I need to do is check that all rows are present and all fields equal. I have the code ...
Python comparing two CSV files when order of rows doesn't matter
I have some code that creates a CSV file. The order of the rows it writes to the file can vary. I am writing a test to make sure the CSV file is what I expect. All I need to do is check that all rows are present and all fields equal. I have the code below, but am not sure how to get it to work so it doesn't care about ...
[ "If you don't care about repeated rows:\nset(csv1) == set(csv2)\n\nelse:\nsorted(csv1) == sorted(csv2)\n\n", "If they'll fit in memory, just cast to lists and sort them.\n" ]
[ 6, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0005212444_csv_python.txt
Q: Do you know Python libs to send / receive files using Bittorent? I have bigs files to move to a lot of servers. For now we use rsync, but I would like to experiment with bittorent. I'm studing the code of Deluge, a Python bittorent client but it uses twisted and is utterly complex. Do you know anything hight level...
Do you know Python libs to send / receive files using Bittorent?
I have bigs files to move to a lot of servers. For now we use rsync, but I would like to experiment with bittorent. I'm studing the code of Deluge, a Python bittorent client but it uses twisted and is utterly complex. Do you know anything hight level? EDIT: I just read that Facebook does code deployment using Bittorent...
[ "I definitely recommend libtorrent-rasterbar. It's a C++ library with Python bindings. The same one that powers Deluge, Transmission, Miro and many other bittorrent clients.\nIn contrast to the other libtorrent (the one that is part of rTorrent project), this one is under active development and supports all modern ...
[ 6, 2 ]
[]
[]
[ "bittorrent", "python" ]
stackoverflow_0004750432_bittorrent_python.txt
Q: One element of a tuple dict-key matching in Python If I have a dict such as: foo = {('foo', 45):5, ('bar', 34):3} How can I check against part of that tuple? if 'foo' in foo: #should be true pass if 45 in foo: #also should be true Or some other syntax. A: >>> foo = {('foo', 45): 5, ('bar', 34): 3} >>> ...
One element of a tuple dict-key matching in Python
If I have a dict such as: foo = {('foo', 45):5, ('bar', 34):3} How can I check against part of that tuple? if 'foo' in foo: #should be true pass if 45 in foo: #also should be true Or some other syntax.
[ ">>> foo = {('foo', 45): 5, ('bar', 34): 3} \n>>> any(t1 == \"foo\" for (t1, t2) in foo)\nTrue \n>>> any(t2 == 45 for (t1, t2) in foo)\nTrue\n\nIf you don't know where the value is to be found you can just check the whole pair:\n>>> any(45 in pair for pair in foo)\nTrue\n\nYou can also a generators approach (...
[ 7, 1, 0 ]
[]
[]
[ "dictionary", "python", "tuples" ]
stackoverflow_0005212668_dictionary_python_tuples.txt
Q: What is wrong with this redirect? (Google App Engine - Python) In SubmitHandler I get the submitted url: url = self.request.get("url").rstrip().lstrip() and check if its length is zero and if it is zero i redirect to /urlparseerror: if len(url) == 0: logging.info("""***len(url) is --zero--: %s***"...
What is wrong with this redirect? (Google App Engine - Python)
In SubmitHandler I get the submitted url: url = self.request.get("url").rstrip().lstrip() and check if its length is zero and if it is zero i redirect to /urlparseerror: if len(url) == 0: logging.info("""***len(url) is --zero--: %s***""" % len(url)) self.redirect("/urlparseerror") but for some...
[ "redirect() will not end the execution of the rest of your code. So if after the snippet you have posted, your code goes on to return some other kind of response your redirect will be ignored. If this is the case, stick a return in to cause the response to be returned.\nif len(url) == 0:\n logging.info(\"\"\"***...
[ 6 ]
[]
[]
[ "google_app_engine", "python", "redirect" ]
stackoverflow_0005212584_google_app_engine_python_redirect.txt
Q: Python application decompiler I have a website that offers files to people; this site is related to a SAT decoder based on Linux. Some people developed "plugins" written in Python that access my site and get those files directly from the decoder without visiting the site. I know I could block them by using JavaScr...
Python application decompiler
I have a website that offers files to people; this site is related to a SAT decoder based on Linux. Some people developed "plugins" written in Python that access my site and get those files directly from the decoder without visiting the site. I know I could block them by using JavaScript methods on the website but I wo...
[ "Exploring and decompiling python bytecode\n" ]
[ 1 ]
[]
[]
[ "decompiling", "python" ]
stackoverflow_0005212725_decompiling_python.txt
Q: What is the meaning of EmailProperty, PhoneNumberProperty etc... gae-datastore properties Possible Duplicate: How does EmailProperty differ from StringProperty? In EmailProperty docs: Neither the property class nor the value class perform validation of email addresses, they just store the value. So why t...
What is the meaning of EmailProperty, PhoneNumberProperty etc... gae-datastore properties
Possible Duplicate: How does EmailProperty differ from StringProperty? In EmailProperty docs: Neither the property class nor the value class perform validation of email addresses, they just store the value. So why to have it instead of StringProperty
[ "It purely for semantics.\nIt's handy if you want to write functions that iterate over the properties of a Model.\nI would guess the idea is to encourage everyone to write nice semantic custom properties for their models and leading by example.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0005211839_google_app_engine_google_cloud_datastore_python.txt
Q: Calculate percentage of a csv column in python I have this csv file about logged hours by users that looks roughly like this, but it's much larger (more users and projects): User,Project,Hours User1,ProjectA,5 User1,ProjectB,10 User2,ProjectA,7 User2,ProjectB,12 I have some code done that for now p...
Calculate percentage of a csv column in python
I have this csv file about logged hours by users that looks roughly like this, but it's much larger (more users and projects): User,Project,Hours User1,ProjectA,5 User1,ProjectB,10 User2,ProjectA,7 User2,ProjectB,12 I have some code done that for now prints total logged hours for all users. It also prin...
[ "import csv\nimport collections\n\nwith open(<...>) as data_file:\n total_hours = collections.defaultdict(int)\n for row in csv.DictReader(data_file):\n total_hours[row['User']] += int(row['Hours'])\n\nOr you could just read the data into a dictionary user -> project -> time and use that:\nimport funct...
[ 1 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0005213045_csv_python.txt
Q: Detect Window's Default Media Player I'm trying to detect Window's default media player path so that I can access it from my Python/wxPython program. My specific need is to make a list of all media files and play it using the player. A: Based on the comments above, it looks like you decided to go in another dir...
Detect Window's Default Media Player
I'm trying to detect Window's default media player path so that I can access it from my Python/wxPython program. My specific need is to make a list of all media files and play it using the player.
[ "Based on the comments above, it looks like you decided to go in another direction with this. Your question made me curious though so I did some hunting around anyway.\nFile associations are stored in the Windows Registry. The way to access Windows Registry information via python is to use the _winreg module (avail...
[ 2 ]
[]
[]
[ "media", "python", "wxpython" ]
stackoverflow_0004700492_media_python_wxpython.txt
Q: What is an elegant way to solve this max and min problem in Ruby or Python? The following can be done by step by step, somewhat clumsy way, but I wonder if there are elegant method to do it. There is a page: http://www.mariowiki.com/Mario_Kart_Wii, where there are 2 tables... there is Mario - 6 2 2 3 ...
What is an elegant way to solve this max and min problem in Ruby or Python?
The following can be done by step by step, somewhat clumsy way, but I wonder if there are elegant method to do it. There is a page: http://www.mariowiki.com/Mario_Kart_Wii, where there are 2 tables... there is Mario - 6 2 2 3 - - Luigi 2 6 - - - - - Diddy Kong - - 3 - 3 - 5 ...
[ "There are two parts to your problem. Parsing the HTML, and doing the analysis. Parsing the HTML is a tedious job and I suspect there's not a whole lot that you can do to make it elegant. The analysis is not hard, but there are some ways to do this in Python that I think might be considered elegant. I'm going to di...
[ 8, 3, 3 ]
[]
[]
[ "python", "ruby" ]
stackoverflow_0005210873_python_ruby.txt
Q: How can I create an unbuffered I/O multiplexer in Python? I want a console python script that will receive input on stdin and immediately write it out to stdout and stderr simultaneously. This should be unbuffered both on input and output. How would I do this? I assume it's pretty basic, once you know the trick. ...
How can I create an unbuffered I/O multiplexer in Python?
I want a console python script that will receive input on stdin and immediately write it out to stdout and stderr simultaneously. This should be unbuffered both on input and output. How would I do this? I assume it's pretty basic, once you know the trick.
[ "look at this \nDisable output buffering\n" ]
[ 1 ]
[]
[]
[ "io", "python", "unbuffered" ]
stackoverflow_0005213098_io_python_unbuffered.txt
Q: Latest eclipse/pydev shows python package names instead of module names in editor window tabs I just updated to the latest Eclipse classic plus PyDev, and instead of showing the module name (without the .py extension) in the editor window tabs, it shows the python package name (equivalent to the parent folder name...
Latest eclipse/pydev shows python package names instead of module names in editor window tabs
I just updated to the latest Eclipse classic plus PyDev, and instead of showing the module name (without the .py extension) in the editor window tabs, it shows the python package name (equivalent to the parent folder name). Does anyone know if this is as per design, and if there's any workaround? It appears there's no...
[ "You go to Eclipse Preferences -> Pydev -> Editor -> Editor caption/icons -> Django modules handling -> Show as regular module\n", "The little icon in the window tab, which precedes the tab name, shows whether the file is a model (M), view (V), etc. This is actually a PyDev django feature; they show \"icon + app...
[ 2, 1 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0004779358_eclipse_pydev_python.txt
Q: Python forward-declaration of functions inside classes I am getting my head around Python for the first time and I am stuck here: class A: def __init__(self): a = foo("baa") class B(A): b = foo("boo") def foo(string): return string At this point I load the above file (named classes) and this...
Python forward-declaration of functions inside classes
I am getting my head around Python for the first time and I am stuck here: class A: def __init__(self): a = foo("baa") class B(A): b = foo("boo") def foo(string): return string At this point I load the above file (named classes) and this happens: $ python Python 2.6.1 (r261:67515, Jun 24 2010, 21...
[ "First, in class B, the function foo() is called before being declared. A does not have this problem because foo() is only called when the class is instantiated--after the function foo is defined.\nFor your second question, y.a will not work because you did not say self.a = foo('stirng'). a = foo('stirng') only cre...
[ 6, 1, 1 ]
[]
[]
[ "class_design", "forward_declaration", "python" ]
stackoverflow_0005213166_class_design_forward_declaration_python.txt
Q: How to get a list of character positions in Python? I'm trying to write a function to sanitize unicode input in a web application, and I'm currently trying to reproduce the PHP function at the end of this page : http://www.iamcal.com/understanding-bidirectional-text/ I'm looking for an equivalent of PHP's preg_mat...
How to get a list of character positions in Python?
I'm trying to write a function to sanitize unicode input in a web application, and I'm currently trying to reproduce the PHP function at the end of this page : http://www.iamcal.com/understanding-bidirectional-text/ I'm looking for an equivalent of PHP's preg_match_all in python. RE function findall returns matches wit...
[ "Try:\ntext = 'abcdefa'\npattern = re.compile('a|c')\n[(m.group(), m.start()) for m in pattern.finditer(text)]\n\n", "I don't know of a way to get re.findall to do this for you, but the following should work:\n\nUse re.findall to find all the matching strings.\nUse str.index to find the associate index of all str...
[ 15, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005213727_python_regex.txt
Q: Reasons for this disparity in execution speed? I wrote a quick Python script to compare two files, each containing unordered hashes, in order to verify that both files are identical aside from order. Then I rewrote it in Ruby for educational purposes. The Python implementation takes seconds, while the Ruby impleme...
Reasons for this disparity in execution speed?
I wrote a quick Python script to compare two files, each containing unordered hashes, in order to verify that both files are identical aside from order. Then I rewrote it in Ruby for educational purposes. The Python implementation takes seconds, while the Ruby implementation takes around 4 minutes. I have a feeling thi...
[ "It could be because dicts in Python are much faster than hashes in Ruby\nI've just run a quick test, building a hash of 12345678 item in Ruby1.8.7 took 3 times as long as Python. Ruby1.9 was about twice as long as Python.\nHere is how I tested\npython \n$ time python -c \"d={}\nfor i in xrange(12345678):d[i]=1\"\n...
[ 5, 5, 2, 0, 0, 0, 0, 0 ]
[]
[]
[ "python", "ruby" ]
stackoverflow_0001863724_python_ruby.txt
Q: Polling a folder, best way to keep memory and speed unaffected? I want to create a python script that polls a folder that a java server will fill with images when a user transfers them, however I want this script to be almost as invisible as possible in terms of noticeable effects. Keep in mind that this computer...
Polling a folder, best way to keep memory and speed unaffected?
I want to create a python script that polls a folder that a java server will fill with images when a user transfers them, however I want this script to be almost as invisible as possible in terms of noticeable effects. Keep in mind that this computer has many servers on it, and management of memory and speed are thing...
[ "If your server is Linux, the best and cleanest way to do this is with the system service inotify, which is designed just for your needs. Python has a lib as a part of the twisted network programming framework, which is loosely coupled, so you can use it while keeping it simple. Just check-out this example:\nhttp:/...
[ 3 ]
[]
[]
[ "file", "memory_management", "optimization", "polling", "python" ]
stackoverflow_0005213836_file_memory_management_optimization_polling_python.txt
Q: Setting an ASIHTTPRequest post to a SimpleHTTPServer Python server? I am working on a project (that i will not be releasing to the app store - just for fun) that will upload an image via an HTTP Post request from my iPhone to a server that I have running the Python script SimpleHTTPServer(http://ubuntuguide.net/ht...
Setting an ASIHTTPRequest post to a SimpleHTTPServer Python server?
I am working on a project (that i will not be releasing to the app store - just for fun) that will upload an image via an HTTP Post request from my iPhone to a server that I have running the Python script SimpleHTTPServer(http://ubuntuguide.net/http-server-support-uploading-files-from-windows-in-ubuntu). I have succes...
[ "As @SorinA. mentions, you should supply a file path as the first argument to setFile:withFileName:andContentType:forKey:. In your example, you're supplying a UIImage object instead.\nThe simplest fix, however, might be to just use setData:withFileName:andContentType:forKey:. You just need to convert your UIImage o...
[ 2, 1, 0, 0 ]
[]
[]
[ "asihttprequest", "iphone", "python" ]
stackoverflow_0005113601_asihttprequest_iphone_python.txt
Q: Which performance have cPython sets in comparison to lists? I have just found these performance notes for cPython lists: Time needed for python lists to .... ... get or set an individual item: O(1) ... append an item to the list: worst O(n^2), but usually O(1) ... insert an item: O(n), where n is the number of el...
Which performance have cPython sets in comparison to lists?
I have just found these performance notes for cPython lists: Time needed for python lists to .... ... get or set an individual item: O(1) ... append an item to the list: worst O(n^2), but usually O(1) ... insert an item: O(n), where n is the number of elements after the inserted one ... remove an item: O(n) Now I wou...
[ "AFAIK, the Python \"specification\" does not impose specific data structures for implementation of lists, dictionaries or sets, so this can't be answered \"officially\". If you're only concerned about CPython (the reference implementation), then we can throw in some un-official complexities. You might want to re...
[ 1 ]
[]
[]
[ "cpython", "python" ]
stackoverflow_0005214078_cpython_python.txt
Q: SWIG with C++ templates: undefined symbol C++ Templates and SWIG aren't playing nicely together for me. When I try to import my module I get the error ImportError: ./_simple.so: undefined symbol: _Z9double_itIiET_S0_ I am using SWIG 1.3. Here is a simple example showing the problem: //file: simple.h template <typ...
SWIG with C++ templates: undefined symbol
C++ Templates and SWIG aren't playing nicely together for me. When I try to import my module I get the error ImportError: ./_simple.so: undefined symbol: _Z9double_itIiET_S0_ I am using SWIG 1.3. Here is a simple example showing the problem: //file: simple.h template <typename T> T double_it (T a); //file: simple.cc ...
[ "Typically templates are defined in a header file instead of in a cc file. With the setup you have, the compiler cannot find / compile the implementation of the template. \nYou will need to change the organization of the code so that the template implementation is available:\n//file: simple.hh\ntemplate <typename T...
[ 3 ]
[]
[]
[ "c++", "python", "swig" ]
stackoverflow_0005214009_c++_python_swig.txt
Q: RegEx Tokenizer to split a text into words, digits and punctuation marks What I want to do is to split a text into his ultimate elements. For example: from nltk.tokenize import * txt = "A sample sentences with digits like 2.119,99 or 2,99 are awesome." regexp_tokenize(txt, pattern='(?:(?!\d)\w)+|\S+') ['A','sample...
RegEx Tokenizer to split a text into words, digits and punctuation marks
What I want to do is to split a text into his ultimate elements. For example: from nltk.tokenize import * txt = "A sample sentences with digits like 2.119,99 or 2,99 are awesome." regexp_tokenize(txt, pattern='(?:(?!\d)\w)+|\S+') ['A','sample','sentences','with','digits','like','2.199,99','or','2,99','are','awesome','....
[ "I created a pattern to try to include periods and commas occurring inside words, numbers. Hope this helps:\ntxt = \"Today it's 07.May 2011. Or 2.999.\"\nregexp_tokenize(txt, pattern=r'\\w+([.,]\\w+)*|\\S+')\n['Today', 'it', \"'s\", '07.May', '2011', '.', 'Or', '2.999', '.']\n\n" ]
[ 8 ]
[]
[]
[ "nltk", "python", "regex", "tokenize" ]
stackoverflow_0005214177_nltk_python_regex_tokenize.txt
Q: Converting a string that represents a list, into an actual list object I have a string that represents a list: "[22, 33, 36, 41, 46, 49, 56, 72, 85, 92, 95, 98, 107, 118, 120, 123, 124, 126, 127, 130, 149, 157, 161, 171, 174, 177, 187, 195, 225, 302, 316, 359, 360, 363, 396, 479, 486, 491]" I would like to turn t...
Converting a string that represents a list, into an actual list object
I have a string that represents a list: "[22, 33, 36, 41, 46, 49, 56, 72, 85, 92, 95, 98, 107, 118, 120, 123, 124, 126, 127, 130, 149, 157, 161, 171, 174, 177, 187, 195, 225, 302, 316, 359, 360, 363, 396, 479, 486, 491]" I would like to turn that litteral string into an actual list. I suppose to could regex out the nu...
[ "Use ast.literal_eval.\n>>> import ast\n>>> i = ast.literal_eval('[22, 33, 36, 41, 46, 49, 56]')\n>>> i[3]\n41\n\n", "Yet another way:\nimport json\nx=json.loads(\"[22, 33, 36, 41, 46, 49, 56, 72, 85, 92, 95, 98, 107, 118, 120, 123, 124, 126, 127, 130, 149, 157, 161, 171, 174, 177, 187, 195, 225, 302, 316, 359, 3...
[ 12, 4, 2, 1, 0 ]
[]
[]
[ "list", "python", "string", "type_conversion" ]
stackoverflow_0005214344_list_python_string_type_conversion.txt
Q: PyQt QProgressBar not working correctly due to Python docstring comment length? Using Python 3.1 and PyQt, I am trying to get a QProgressBar to show that a task is working by having the bars slide across the widget. I found that can be done by setting the minimum and maximum values to 0. I got it to work properly,...
PyQt QProgressBar not working correctly due to Python docstring comment length?
Using Python 3.1 and PyQt, I am trying to get a QProgressBar to show that a task is working by having the bars slide across the widget. I found that can be done by setting the minimum and maximum values to 0. I got it to work properly, but then when integrating it into my program, the bars will only show up in the firs...
[ "I've seen the same thing happen and managed to fix it by resizing the window slightly.\nIt sounds crazy, but it worked for me. I'd be interested to know if it makes things work for you too. I noticed the bar work as expected during runtime once the window had been resized and after a couple of minutes of trial and...
[ 0 ]
[]
[]
[ "pyqt", "python", "qprogressbar" ]
stackoverflow_0005213114_pyqt_python_qprogressbar.txt
Q: In python. class variable is static..is I want to use different instance. is there any solution? In python, I want to make a class variable static so I can to use it from a different instance. is there any solution? A: I don't follow your question exactly, but it seems to me you're asking how to make instance va...
In python. class variable is static..is I want to use different instance. is there any solution?
In python, I want to make a class variable static so I can to use it from a different instance. is there any solution?
[ "I don't follow your question exactly, but it seems to me you're asking how to make instance variables in Python. The answer is to set them inside a method, preferably __init__() using the self reference.\nclass Foo(object):\n classVar = 0 #this is a class variable. It is shared between all instances\n def __...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0005214665_python.txt
Q: Emacs: Distinguish between Python 2.x and 3.x in emacs I use Emacs and am currently working on projects that use different versions of Python (2.x and 3.x) and both have different sets of documentation and different interactive shells. I want to be able to distinguish between these versions in Emacs (so I read th...
Emacs: Distinguish between Python 2.x and 3.x in emacs
I use Emacs and am currently working on projects that use different versions of Python (2.x and 3.x) and both have different sets of documentation and different interactive shells. I want to be able to distinguish between these versions in Emacs (so I read the right documentation with pylookup and also setup the corre...
[ "See this older question: Both Python 2 and 3 in Emacs\n" ]
[ 1 ]
[]
[]
[ "emacs", "python", "versions" ]
stackoverflow_0005214399_emacs_python_versions.txt
Q: Python refuses text.replace() in one environment I've been mocking about with the following bit of dirty support-code for a pylons app, which works fine in a python-shell, a separate python file, or when running in paster. Now, we've put the application on-line through mod_wsgi and apache and this specific piece o...
Python refuses text.replace() in one environment
I've been mocking about with the following bit of dirty support-code for a pylons app, which works fine in a python-shell, a separate python file, or when running in paster. Now, we've put the application on-line through mod_wsgi and apache and this specific piece of code stopped working completely. First off, the code...
[ "Add some print statments and examine the Apache logs:\ndef fixStyle(self, text):\n print \"text:\", text\n print \"STYLEDEF\", STYLEDEF\n t = text.replace('<p>', '<p style=\"%s\">' % (STYLEDEF,))\n print \"t:\", t\n\n", "I have no idea concerning what is your problem, but I find the repetition of rep...
[ 0, 0, 0 ]
[]
[]
[ "apache", "pylons", "python", "replace" ]
stackoverflow_0005195626_apache_pylons_python_replace.txt
Q: Cluto like library for Python I like Cluto as a data clustering software a lot. But its library binding is available only in C. Is there any python library which is similar to Cluto? A: I've not tried any of them, but there are a few things which say they do clustering in Python: scipy.cluster (numpy and scipy ...
Cluto like library for Python
I like Cluto as a data clustering software a lot. But its library binding is available only in C. Is there any python library which is similar to Cluto?
[ "I've not tried any of them, but there are a few things which say they do clustering in Python:\n\nscipy.cluster (numpy and scipy are the two mainstays of serious numerical computation in Python)\nPycluster\nhcluster (looks like it's not been updated in a couple of years)\n\nIf none of those do the trick, you could...
[ 1 ]
[]
[]
[ "cluster_analysis", "cluto", "python" ]
stackoverflow_0005214044_cluster_analysis_cluto_python.txt
Q: Getting numbers into a column in Python I have a bunch of numbers that are tab-delimited with new line characters that looks something like this: 104 109 105 110 126 119 97 103\n 114 129 119 130 122 106 117 128\n and so on. How can I use python to write all...
Getting numbers into a column in Python
I have a bunch of numbers that are tab-delimited with new line characters that looks something like this: 104 109 105 110 126 119 97 103\n 114 129 119 130 122 106 117 128\n and so on. How can I use python to write all these numbers to a file in one column? i.e. ...
[ "The easiest way to do this is probably to use sed. But if you must use Python, you need to replace all tab characters with newlines. Try something like this:\nwith open('input_file', 'rb') as infile:\n with open('output_file', 'wb') as outfile:\n for line in infile:\n outfile.write(line.replac...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005214814_python.txt
Q: how could I pass a collection of the arguments that a function needed? For example, I have a function: def foo(a, b, c): pass Now I have a dict: d = {'a': 1, 'b': 2, 'c': 3} I have to write something like: foo(d['a'], d['b'], d['c']) I'd like to know, could I just pass a collection of the arguments(like d)...
how could I pass a collection of the arguments that a function needed?
For example, I have a function: def foo(a, b, c): pass Now I have a dict: d = {'a': 1, 'b': 2, 'c': 3} I have to write something like: foo(d['a'], d['b'], d['c']) I'd like to know, could I just pass a collection of the arguments(like d) to the function?
[ "Sure, you can pass a dict as kwargs:\ndef foo(a, b, c):\n print a, b, c\n\nd = {'a': 1, 'b': 2, 'c': 3}\nfoo(**d)\n\nOutput:\n1 2 3\n\n", "Use the dictionary unpacking operator (**):\nfoo(**d)\n\n", "foo(**d) should work.\nSee http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists\n" ]
[ 9, 5, 3 ]
[]
[]
[ "python" ]
stackoverflow_0005214910_python.txt
Q: Django: follow relations backwards Hey, I have models like this: class Galleries(models.Model): creation_date = models.DateTimeField() name = models.CharField(max_length=255, unique=True) gallery_type = models.ForeignKey(Categories) class Categories(models.Model): handle = models.CharField(max_length=255,...
Django: follow relations backwards
Hey, I have models like this: class Galleries(models.Model): creation_date = models.DateTimeField() name = models.CharField(max_length=255, unique=True) gallery_type = models.ForeignKey(Categories) class Categories(models.Model): handle = models.CharField(max_length=255, unique=True) class Values(models.Model...
[ "galleries = Galleries.objects.get(id=1)\nvalues = galleries.gallery_type.values_set.filter(language='language')\n\nInterestingly, you used the exact wording that the docs use to refer to the related field lookups. I always found the definition strange to the gut, maybe because they put it in quotes. \n\nFOLLOWING...
[ 5, 1 ]
[]
[]
[ "django", "orm", "python" ]
stackoverflow_0005212463_django_orm_python.txt
Q: How to get the right variable referenced In the code below I am trying to get the second 'while' statement (while digit_check) to receive the new date from the earlier while_count statement. But it seems to be picking up the original assignment for the user_date variable from the first assignment line. How can I ...
How to get the right variable referenced
In the code below I am trying to get the second 'while' statement (while digit_check) to receive the new date from the earlier while_count statement. But it seems to be picking up the original assignment for the user_date variable from the first assignment line. How can I get the new variable assignment to pass to the...
[ "One problem is that you aren't recalculating digit_check here:\nwhile digit_check != True :\n user_date = raw_input('Not right - try again')\n\nThis will just go into an infinite loop.\nI'd suggest that instead of writing a huge function with many loops and lots of assignments, instead you refactor your code int...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005214103_python.txt
Q: wsgi + Django: SOAPpy(pyXML) modules Import Error In the command line the code works perfect, but throw import error when use django + mod_python or wsgi +apache The message is: ImportError at /test2/ DLL load failed: The specified module could not be found. C:\Python26\lib\site-packages\django\core\handlers\bas...
wsgi + Django: SOAPpy(pyXML) modules Import Error
In the command line the code works perfect, but throw import error when use django + mod_python or wsgi +apache The message is: ImportError at /test2/ DLL load failed: The specified module could not be found. C:\Python26\lib\site-packages\django\core\handlers\base.py in get_response D:\dgwww\mytest\views.py in test2...
[ "The problem solved.\nI down load PyXML 0.8.4 for Python 2.6 win32 from\nhttp://www.somethinkodd.com/oddthinking/2009/10/31/windows-installer-for-pyxml-0-8-4-for-python-2-6-x/\nand copy the files to python's site_packages\n" ]
[ 0 ]
[]
[]
[ "django", "django_wsgi", "python", "soappy" ]
stackoverflow_0005191995_django_django_wsgi_python_soappy.txt
Q: MATLAB for Python programmers I've used MATLAB on and off before, but I need to develop a good understanding of it now, and the language I'm most familiar with is Python. Care to describe a MATLAB language feature, idiom, best practice or philosophy as compared to Python? There's a terrific amount of buzz for and ...
MATLAB for Python programmers
I've used MATLAB on and off before, but I need to develop a good understanding of it now, and the language I'm most familiar with is Python. Care to describe a MATLAB language feature, idiom, best practice or philosophy as compared to Python? There's a terrific amount of buzz for and resources pertaining to going the o...
[ "The documentation is one of the strong points of MATLAB. If you need to get into MATLAB, one of the best places to start is the \"Getting Started\" section. Some of it will be too basic for you, which is a lot better than if it was too advanced, but it will show you the most important aspects of the language.\nOne...
[ 7, 6, 3, 2, 1, 0 ]
[]
[]
[ "matlab", "python" ]
stackoverflow_0003852362_matlab_python.txt