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: change file descriptor for socket in python I'm trying to manually create the file descriptor associated with a socket in python and then loaded directly into memory with mmap. Create a file into memory with mmap is simple, but I can not find a way to associate the file with a socket. Thanks for your responses. T...
change file descriptor for socket in python
I'm trying to manually create the file descriptor associated with a socket in python and then loaded directly into memory with mmap. Create a file into memory with mmap is simple, but I can not find a way to associate the file with a socket. Thanks for your responses. The problem I have is I can not make more of a num...
[ "Why do you want to load this into memory using mmap? If you are on a unix variant, you can create a unix socket which is a file descriptor which can be used just like any other socket. A socket and a memory-mapped file are two distinct entities - it is probably not a good idea to try and mix them.\nPerhaps it woul...
[ 1, 0 ]
[]
[]
[ "file_descriptor", "python", "sockets" ]
stackoverflow_0002922548_file_descriptor_python_sockets.txt
Q: What are simple instructions for creating a Python package structure and egg? I just completed my first (minor) Python project, and my boss wants me to package it nicely so that it can be distributed and called from other programs easily. He suggested I look into eggs. I've been googling and reading, but I'm just ...
What are simple instructions for creating a Python package structure and egg?
I just completed my first (minor) Python project, and my boss wants me to package it nicely so that it can be distributed and called from other programs easily. He suggested I look into eggs. I've been googling and reading, but I'm just getting confused. Most of the sites I'm looking at explain how to use Python eggs t...
[ "All you need is read this: The Hitchhiker's Guide to Packaging \nor install PasteScript using pip or easy_install, then\npaster create your_package_name\n\nand you'll get a template for your python package\n", "You should hold to the standard packaging of distutils. Quoting James Bennett:\n\nPlease, for the love...
[ 30, 3, 2 ]
[]
[]
[ "egg", "package", "python" ]
stackoverflow_0002922498_egg_package_python.txt
Q: Python MySQLdb LOAD LOCAL INFILE problems The problem is a simple one. When I execute the following I get different results depending on whether I run it from the MySQL console and from inside a Python Script using MySQLdb: LOAD DATA LOCAL INFILE '/tmp/source.csv' INTO TABLE test FIELDS TERMINATED BY '|' IGNORE ...
Python MySQLdb LOAD LOCAL INFILE problems
The problem is a simple one. When I execute the following I get different results depending on whether I run it from the MySQL console and from inside a Python Script using MySQLdb: LOAD DATA LOCAL INFILE '/tmp/source.csv' INTO TABLE test FIELDS TERMINATED BY '|' IGNORE 1 LINES; Console gives the following results: ...
[ "After loading the data, execute\nSELECT @@warning_count;\n\ncheck if greater than 0.\nIf it is than execute\nSHOW WARNINGS;\n\nand dump the result (returns 3 columns: Level, Code, Message) or throw an exception.\nYou can execute both statements exactly like every other select * from ... query.\n" ]
[ 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0002922535_mysql_python.txt
Q: Python time objects with more than 24 hours I have a time out of Linux that is in hh:mm:sec, but the hh can be greater than 24 hours. So if the time is 1 day 12 hours, it would be 36:00:00. Is there a way to take this format and easily make a time object? What I would really like to do is take the the required t...
Python time objects with more than 24 hours
I have a time out of Linux that is in hh:mm:sec, but the hh can be greater than 24 hours. So if the time is 1 day 12 hours, it would be 36:00:00. Is there a way to take this format and easily make a time object? What I would really like to do is take the the required time i.e. 36:00:00, and the time that it has been ...
[ "timedelta is indeed what you want. Here is a more complete example that does what you asked.\n>>> import datetime\n>>> a = datetime.timedelta(hours=36)\n>>> b = datetime.timedelta(hours=4, minutes=46, seconds=23)\n>>> c = a - b\n>>> print c\n1 day, 7:13:37\n\n", "What you need is the timedelta object: http://do...
[ 16, 10 ]
[]
[]
[ "python", "time", "timedelta" ]
stackoverflow_0002922735_python_time_timedelta.txt
Q: How do I do this in Python (File Manipulation)? I have a bunch of HTML files in HTML folder. Those HTML files have unicode characters which I solved by using filter(lambda x: x in string.printable, line). Now how do I write the changes back to the original file? What is the best way of doing it? Each HTML file is ...
How do I do this in Python (File Manipulation)?
I have a bunch of HTML files in HTML folder. Those HTML files have unicode characters which I solved by using filter(lambda x: x in string.printable, line). Now how do I write the changes back to the original file? What is the best way of doing it? Each HTML file is of 30 kb in size. 1 import os, string 2 3 for ...
[ "Use the fileinput module. It allows you to read and write to the same file in place:\nimport fileinput,sys,os\nfiles=[os.path.join('HTML',filename) for filename in os.listdir(\"HTML/\")]\nfor line in fileinput.input(files, inplace=True): \n line = filter(lambda x: x in string.printable, line)\n sys.stdout...
[ 3, 2, 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0002923310_file_io_python.txt
Q: Parse large XML file w/ script or use BioPython API? Hey guys this is my first question on here. I'm trying to make a local copy of the UniprotKB in SQL. The UniprotKB is 2.1GB, and it comes in XML and a special text format used by SwissProt Here are my options: 1) Use a SAX parser (XML) - I chose Ruby, and Nokogi...
Parse large XML file w/ script or use BioPython API?
Hey guys this is my first question on here. I'm trying to make a local copy of the UniprotKB in SQL. The UniprotKB is 2.1GB, and it comes in XML and a special text format used by SwissProt Here are my options: 1) Use a SAX parser (XML) - I chose Ruby, and Nokogiri. I started writing the parser, but my initial reaction:...
[ "Switched to PostgrelSQL for convenience purposes. Some of the issues were resolved by downloading the NCBI taxonomy information (which I did not know was necessary, should have been more clear in the documentation), so I ended up using the Swiss parser from BioPython because it fits so nicely with BioSQL. \n" ]
[ 0 ]
[]
[]
[ "bioinformatics", "python", "xml" ]
stackoverflow_0002915442_bioinformatics_python_xml.txt
Q: How can I connect to a mail server using SMTP over SSL using Python? So I have been having a hard time sending email from my school's email address. It is SSL and I could only find this code online by Matt Butcher that works with SSL: import smtplib, socket __version__ = "1.00" __all__ = ['SMTPSSLException', 'SM...
How can I connect to a mail server using SMTP over SSL using Python?
So I have been having a hard time sending email from my school's email address. It is SSL and I could only find this code online by Matt Butcher that works with SSL: import smtplib, socket __version__ = "1.00" __all__ = ['SMTPSSLException', 'SMTP_SSL'] SSMTP_PORT = 465 class SMTPSSLException(smtplib.SMTPException):...
[ "That code you've found seems to be for an older version, considering the deprecation warning. Maybe you can get by with the stdlib: There is a SMTP_SSL class as of Python 2.6, and as of at least 2.4 there is a starttls method on the plaintext SMTP class.\n" ]
[ 1 ]
[]
[]
[ "email", "python", "smtp", "ssl" ]
stackoverflow_0002923561_email_python_smtp_ssl.txt
Q: How to store wiki sites (vcs) as a personal project I am trying to write a wiki with the help of django. I'm a beginner when it comes to web development. I am at the (early) point where I need to decide how to store the wiki sites. I have three approaches in mind and would like to know your suggestion. Flat files ...
How to store wiki sites (vcs)
as a personal project I am trying to write a wiki with the help of django. I'm a beginner when it comes to web development. I am at the (early) point where I need to decide how to store the wiki sites. I have three approaches in mind and would like to know your suggestion. Flat files I considered a flat file approach w...
[ "In none of your choices have you considered whether you wish to be able to search your wiki. If this is a consideration, having the 'live' copy of each page in a database with full text search would be hugely beneficial. For this reason, I would personally go with storing the pages in a database every time - oth...
[ 2, 0 ]
[]
[]
[ "database", "django", "python", "version_control", "wiki" ]
stackoverflow_0002893303_database_django_python_version_control_wiki.txt
Q: Howto install distribute for Python 3 I am trying to install distribute using ActivePython 3.1.2 on Windows. Running python distribute_setup.py as described on the cheese shop give me: No setuptools distribution found running install Traceback (most recent call last): File "setup.py", line 177, in script...
Howto install distribute for Python 3
I am trying to install distribute using ActivePython 3.1.2 on Windows. Running python distribute_setup.py as described on the cheese shop give me: No setuptools distribution found running install Traceback (most recent call last): File "setup.py", line 177, in scripts = scripts, File "C:\Dev\Python_x86\3.1\...
[ "So apparently the python.org version of Python3 is different from the ActiveState version of Python3. (You should file a bug to someone (I'm not sure to whom))\nThe fix I have (I'm not sure of all the repercussions)\nDownload:\nhttp://pypi.python.org/packages/source/d/distribute/distribute-0.6.12.tar.gz#md5=5a52e9...
[ 3, 3 ]
[]
[]
[ "distribute", "python", "python_3.x", "pywin32", "setuptools" ]
stackoverflow_0002831231_distribute_python_python_3.x_pywin32_setuptools.txt
Q: What does the star and doublestar operator mean in a function call? What does the * operator mean in Python, such as in code like zip(*x) or f(**k)? How is it handled internally in the interpreter? Does it affect performance at all? Is it fast or slow? When is it useful and when is it not? Should it be used in a ...
What does the star and doublestar operator mean in a function call?
What does the * operator mean in Python, such as in code like zip(*x) or f(**k)? How is it handled internally in the interpreter? Does it affect performance at all? Is it fast or slow? When is it useful and when is it not? Should it be used in a function declaration or in a call?
[ "The single star * unpacks the sequence/collection into positional arguments, so you can do this:\ndef sum(a, b):\n return a + b\n\nvalues = (1, 2)\n\ns = sum(*values)\n\nThis will unpack the tuple so that it actually executes as:\ns = sum(1, 2)\n\nThe double star ** does the same, only using a dictionary and th...
[ 1135, 25, 22, 19 ]
[]
[]
[ "argument_unpacking", "iterable_unpacking", "parameter_passing", "python", "syntax" ]
stackoverflow_0002921847_argument_unpacking_iterable_unpacking_parameter_passing_python_syntax.txt
Q: how to create plots (non-flash) with mouse-over info boxes on the fly for the web? I'm thinking about creating a tool to visualize scientific data on a website. For this, the user enters some query string and out comes a simple (x,y)-plot (similar to this) I know that using Matplotlib, one can generate graphics on...
how to create plots (non-flash) with mouse-over info boxes on the fly for the web?
I'm thinking about creating a tool to visualize scientific data on a website. For this, the user enters some query string and out comes a simple (x,y)-plot (similar to this) I know that using Matplotlib, one can generate graphics on the fly for python. However, this doesn't solve the need for some custom java-script co...
[ "If you need dynamic elements without flash or Java applet then JavaScript is the best choice. To create plots you could use HTML5 canvas element.\nCapturing mouse events is JS is trivial... \n" ]
[ 0 ]
[]
[]
[ "html", "javascript", "plot", "python" ]
stackoverflow_0002924051_html_javascript_plot_python.txt
Q: Building a survey to put in a WordPress website using Python/Django So I've been given a task to build a survey to get data regarding time slot preferences of prospective students for a particular course. I know there are really quick solutions to this like Google Forms, SurveyMonkey, but since it's not unusually ...
Building a survey to put in a WordPress website using Python/Django
So I've been given a task to build a survey to get data regarding time slot preferences of prospective students for a particular course. I know there are really quick solutions to this like Google Forms, SurveyMonkey, but since it's not unusually hard, I want to implement the survey myself in a totally new language as ...
[ "The Django book is a good starting point, together with the documentation on the Django site itself.\nIntegrating it into Wordpress could be more complicated, if you need tight integration I would not use a different language.\nAnd in general I would never say that learing a new and different language is a waste ...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002924413_django_python.txt
Q: don't show on panel I am trying to write a simple aplication (a continuously changing label on a window on the upper left side of the screen) and I don't want it to be seen on panel but only on system tray.Because it will run for a long time. How can I do that? Thanks. PS: I am using python and pyqt on Linux. I tr...
don't show on panel
I am trying to write a simple aplication (a continuously changing label on a window on the upper left side of the screen) and I don't want it to be seen on panel but only on system tray.Because it will run for a long time. How can I do that? Thanks. PS: I am using python and pyqt on Linux. I tried SplashScreen but when...
[ "I found the solution. I set the window flag as \"Qt.Popup\". Now there in no window on the panel. \n" ]
[ 1 ]
[]
[]
[ "pyqt", "python", "qt" ]
stackoverflow_0002916245_pyqt_python_qt.txt
Q: IP address of domain on shared host I have domain on a shared hosting provider. How do I find the direct IP address of my domain using Python? Is it possible to post to a script on my domain using the IP address and not the website itself? Thanks. A: I guess the IP should be static so do you really need to look ...
IP address of domain on shared host
I have domain on a shared hosting provider. How do I find the direct IP address of my domain using Python? Is it possible to post to a script on my domain using the IP address and not the website itself? Thanks.
[ "\nI guess the IP should be static so do you really need to look it up more than once?\nYou need to specify the domain name so that the webserver knows which host configuration to use if you don't have a dedicated IP or your host is the default for that webserver\n\n", "import socket\nsocket.gethostbyname(\"www.s...
[ 0, 0, 0 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0002924736_cgi_python.txt
Q: Python unicode problem I'm receiving some data from a ZODB (Zope Object Database). I receive a mybrains object. Then I do: o = mybrains.getObject() and I receive a "Person" object in my project. Then, I can do b = o.name and doing print b on my class I get: José Carlos and print b.name.__class__ <type 'unicode...
Python unicode problem
I'm receiving some data from a ZODB (Zope Object Database). I receive a mybrains object. Then I do: o = mybrains.getObject() and I receive a "Person" object in my project. Then, I can do b = o.name and doing print b on my class I get: José Carlos and print b.name.__class__ <type 'unicode'> I have a lot of "Person"...
[ "\nUnicodeEncodeError: 'ascii' codec\n\nwrite is trying to encode the string using the ascii codec (which doesn't have a way of encoding accented characters like é or à.\nInstead use\nimport codecs\nwith codecs.open(\"/tmp/test.txt\",'w',encoding='utf-8') as f: \n f.write(all.decode('utf-8'))\n\nor choose some...
[ 3, 0 ]
[]
[]
[ "file_io", "python", "unicode" ]
stackoverflow_0002924792_file_io_python_unicode.txt
Q: Python Four steps setup with progressBars I'm having a problem with the code below. When I run it the progress bar will pulse for around 10 secs as meant to and then move on to downloading and will show the progress but when finished it will not move on to the next step it just locks up. import sys import time imp...
Python Four steps setup with progressBars
I'm having a problem with the code below. When I run it the progress bar will pulse for around 10 secs as meant to and then move on to downloading and will show the progress but when finished it will not move on to the next step it just locks up. import sys import time import pygtk import gtk import gobject import thre...
[ "Don't ever do this:\nwhile gtk.events_pending():\n gtk.main_iteration()\n\nUnless you really know what you are doing. And if you really do, do it like this:\ndef refresh_gui(delay=0.0001, wait=0.0001):\n \"\"\"Use up all the events waiting to be run\n\n :param delay: Time to wait before using events\n :...
[ 1 ]
[]
[]
[ "multithreading", "progress_bar", "pygtk", "python" ]
stackoverflow_0002844902_multithreading_progress_bar_pygtk_python.txt
Q: Python matching some characters into a string I'm trying to extract/match data from a string using regular expression but I don't seem to get it. I wan't to extract from the following string the i386 (The text between the last - and .iso): /xubuntu/daily/current/lucid-alternate-i386.iso This should also work in c...
Python matching some characters into a string
I'm trying to extract/match data from a string using regular expression but I don't seem to get it. I wan't to extract from the following string the i386 (The text between the last - and .iso): /xubuntu/daily/current/lucid-alternate-i386.iso This should also work in case of: /xubuntu/daily/current/lucid-alternate-amd6...
[ "You could also use split in this case (instead of regex):\n>>> str = \"/xubuntu/daily/current/lucid-alternate-i386.iso\"\n>>> str.split(\".iso\")[0].split(\"-\")[-1]\n'i386'\n\nsplit gives you a list of elements on which your string got 'split'. Then using Python's slicing syntax you can get to the appropriate par...
[ 3, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002925306_python_regex.txt
Q: Is Python appropriate for algorithms focused on scientific computing? My interests in programming lie mainly in algorithms, and lately I have seen many reputable researchers write a lot of their code in python. How easy and convenient is python for scientific computing? Does it have a library of algorithms that co...
Is Python appropriate for algorithms focused on scientific computing?
My interests in programming lie mainly in algorithms, and lately I have seen many reputable researchers write a lot of their code in python. How easy and convenient is python for scientific computing? Does it have a library of algorithms that compares to matlab's? Is Python a scripting language or does it compile? Is i...
[ "\nHow easy and convenient is python for scientific computing?\n\nScipy/NumPy.\n\nDoes it have a library of algorithms that compares to matlab's?\n\nYes.\n\nIs Python a scripting language or does it compile?\n\nInterpreted.\n\nIs it a great language for prototyping an algorithm?\n\nYes.\n\nHow long would it take me...
[ 16, 14, 11, 8, 4, 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002917974_python.txt
Q: Draw and move a point over an image in python Hi all I have to do a little script in Python. In this script I have a variable (that represents a coordinate) that is continuously updated to a new value. So I have to draw a red point over a image and update the point position every time the variable that contains th...
Draw and move a point over an image in python
Hi all I have to do a little script in Python. In this script I have a variable (that represents a coordinate) that is continuously updated to a new value. So I have to draw a red point over a image and update the point position every time the variable that contains the coordinate is updated. I tried to explain what I ...
[ "Your on the right track using a PhotoImage in a Label but instead of creating a new Label each loop, just create the label once and update its position in the loop.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002920775_python.txt
Q: Images not loading in QWebview in PyQt4 in py2exe I have an application that displays some HTML in a QWebview, which references images on the local file system. This works fine directly running the python. When compiling via py2exe, the images no longer load. Google doesn't seem to know the answer, any ideas? A: ...
Images not loading in QWebview in PyQt4 in py2exe
I have an application that displays some HTML in a QWebview, which references images on the local file system. This works fine directly running the python. When compiling via py2exe, the images no longer load. Google doesn't seem to know the answer, any ideas?
[ "Only png support is native, jpg (and others) is supplied via plugins.\nDon't recall the exact paths (and I don't know your platform) but search for the PyQt plugins folder and:\n\nCopy the plugins folder to: $yourprogram/PyQt4/plugins (along with qt.conf)\nEdit qt.conf, and change prefix to $yourprogram/PyQt4\n\nY...
[ 2 ]
[]
[]
[ "py2exe", "pyqt4", "python", "qwebview" ]
stackoverflow_0002924781_py2exe_pyqt4_python_qwebview.txt
Q: Integer array in Python How I can define array of integer numbers in Python code Say if this code is ok. or no pos = [int] len = 99 for i in range (0,99): pos[i]=7 A: Why not just: pos = [7] * 99 This is the most pythonic, in my opinion. A: import array pos = array.array('l', 7 * [99]) The array modul...
Integer array in Python
How I can define array of integer numbers in Python code Say if this code is ok. or no pos = [int] len = 99 for i in range (0,99): pos[i]=7
[ "Why not just:\npos = [7] * 99\n\nThis is the most pythonic, in my opinion.\n", "import array\n\npos = array.array('l', 7 * [99])\n\nThe array module of Python's standard library is the only way to make an array that comes with Python (the third-party module numpy offers other ways, but needs do be downloaded and...
[ 11, 5, 4, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002901847_python.txt
Q: Elegant Disjunctive Normal Form in Django Let's say I've defined this model: class Identifier(models.Model): user = models.ForeignKey(User) key = models.CharField(max_length=64) value = models.CharField(max_length=255) Each user will have multiple identifiers, each with a key and a value. I am 100% s...
Elegant Disjunctive Normal Form in Django
Let's say I've defined this model: class Identifier(models.Model): user = models.ForeignKey(User) key = models.CharField(max_length=64) value = models.CharField(max_length=255) Each user will have multiple identifiers, each with a key and a value. I am 100% sure I want to keep the design like this, there ...
[ "def get_users_by_identifiers(**kwargs):\n q = reduce(operator.or_, Q(identifier__key=k, identifier__value=v)\n for (k, v) in kwargs.iteritems())\n return User.objects.filter(q)\n\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002925991_django_python.txt
Q: Obtain Latitude and Longitude from a GeoTIFF File Using GDAL in Python, how do you get the latitude and longitude of a GeoTIFF file? GeoTIFF's do not appear to store any coordinate information. Instead, they store the XY Origin coordinates. However, the XY coordinates do not provide the latitude and longitude of...
Obtain Latitude and Longitude from a GeoTIFF File
Using GDAL in Python, how do you get the latitude and longitude of a GeoTIFF file? GeoTIFF's do not appear to store any coordinate information. Instead, they store the XY Origin coordinates. However, the XY coordinates do not provide the latitude and longitude of the top left corner and bottom left corner. It appears...
[ "To get the coordinates of the corners of your geotiff do the following:\nfrom osgeo import gdal\nds = gdal.Open('path/to/file')\nwidth = ds.RasterXSize\nheight = ds.RasterYSize\ngt = ds.GetGeoTransform()\nminx = gt[0]\nminy = gt[3] + width*gt[4] + height*gt[5] \nmaxx = gt[0] + width*gt[1] + height*gt[2]\nmaxy = gt...
[ 102, 19 ]
[]
[]
[ "gdal", "geolocation", "math", "python", "tiff" ]
stackoverflow_0002922532_gdal_geolocation_math_python_tiff.txt
Q: Display folder contents on webpage using Python I wanted to know if there was a way I can get my python script located on a shared web hosting provider to read the contents of a folder on my desktop and list out the contents? Can this be done using tempfiles? A: Server-side web scripts have no access to the clie...
Display folder contents on webpage using Python
I wanted to know if there was a way I can get my python script located on a shared web hosting provider to read the contents of a folder on my desktop and list out the contents? Can this be done using tempfiles?
[ "Server-side web scripts have no access to the client other than through requests. If you can somehow break through the browser's protection settings to get JavaScript, Java, or Flash to read the contents of the client then you stand a fighting chance. But doing so will make many people angry and is generally consi...
[ 1, 0 ]
[]
[]
[ "python", "temporary_files", "web_applications" ]
stackoverflow_0002926106_python_temporary_files_web_applications.txt
Q: Python access webcam and audio input Can a python script on my server access the webcam and audio input of a user as easily and as well as a Flash plugin can? A: No: the "plugin" you mention runs in the user's browser, your server-side script (Python or otherwise) runs on the server, a completely different propo...
Python access webcam and audio input
Can a python script on my server access the webcam and audio input of a user as easily and as well as a Flash plugin can?
[ "No: the \"plugin\" you mention runs in the user's browser, your server-side script (Python or otherwise) runs on the server, a completely different proposition. This relates to your other recent question about a server-side script accessing information on your desktop: your client machine tends to be very protect...
[ 2, 0, 0 ]
[]
[]
[ "python", "streaming", "webcam" ]
stackoverflow_0002926220_python_streaming_webcam.txt
Q: Running iPython from the OSX terminal So I'm going through the matplotlib documentation and prepared to use the iPython interactive Python shell with ipython -pylab. However I get this: Az's MBP:~ Az$ ipython -pylab -bash: ipython: command not found Did I fail to install iPython? I used easy_install as advised. A...
Running iPython from the OSX terminal
So I'm going through the matplotlib documentation and prepared to use the iPython interactive Python shell with ipython -pylab. However I get this: Az's MBP:~ Az$ ipython -pylab -bash: ipython: command not found Did I fail to install iPython? I used easy_install as advised. Any ideas? Update Found it in /opt/local/Lib...
[ "\nDid I fail to install iPython?\n\nNo, but it looks like you installed it with (darwinports or) macports -- I imagine that's where your installation of easy_install comes from, since Apple's own system Python doesn't include extensions such as easy_install, and /opt/local/... is where macports puts things.\nIf yo...
[ 4, 0 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0002926053_macos_python.txt
Q: How can I refer to class variable in a function without referring to its class in Python? I have a following class: class Foo: CONSTANT = 1 def some_fn(self): a = Foo.CONSTANT # do something How can I refer to Foo.CONSTANT without referring to Foo, or refer to Foo in a generic way? (I don...
How can I refer to class variable in a function without referring to its class in Python?
I have a following class: class Foo: CONSTANT = 1 def some_fn(self): a = Foo.CONSTANT # do something How can I refer to Foo.CONSTANT without referring to Foo, or refer to Foo in a generic way? (I don't want to change all references to it when renaming a class)
[ "Within a method of class Foo or any subclass thereof, self.CONSTANT will refer to the value defined for that class attribute in class Foo (unless it's overridden in a subclass or in the instance itself -- if you assign self.CONSTANT=23, it's the instance attribute that's created with that value, and it overrides t...
[ 4, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002926327_python.txt
Q: Which logging library to use for cross-language (Java, C++, Python) system I have a system where a central Java controller launches analysis processes, which may be written in C++, Java, or Python (mostly they are C++). All these processes currently run on the same server. What are you suggestions to Create a cen...
Which logging library to use for cross-language (Java, C++, Python) system
I have a system where a central Java controller launches analysis processes, which may be written in C++, Java, or Python (mostly they are C++). All these processes currently run on the same server. What are you suggestions to Create a central log to which all processes can write to What if in the future I push some p...
[ "I'd recommend using the platform's native logger which is syslog on Posix and Event Log on Windows.\nFor C++, you can use the native calls on the platform.\nI know Python comes with syscall wrapper on Posix and there are wrappers for Event Log in the PyWin32 extension. I assume that someone has created Java wrapp...
[ 5, 1, 1 ]
[]
[]
[ "c++", "java", "logging", "python" ]
stackoverflow_0002885822_c++_java_logging_python.txt
Q: standard geographic tilizing/binning method? I'm trying to learn and understand more about mapping and displaying values on a map. (GIS) At the moment I'M looking to take some values and apply those values to a tile or bin on a map. Ideally I'd like the tile sizes to be uniform, like 100 meters, 500 meters, etc. I...
standard geographic tilizing/binning method?
I'm trying to learn and understand more about mapping and displaying values on a map. (GIS) At the moment I'M looking to take some values and apply those values to a tile or bin on a map. Ideally I'd like the tile sizes to be uniform, like 100 meters, 500 meters, etc. Is there a standard method for creating uniform til...
[ "It sounds like you want to be working with geospatial raster image formats, where the color of a pixel represents the value for that tile. \nThe size of a tile (and whether it's uniform) will depend on the projection of your raster.\nGDAL is a library for working with geospatial raster formats.\n" ]
[ 1 ]
[]
[]
[ "geodjango", "gis", "mapping", "python", "tiling" ]
stackoverflow_0002921586_geodjango_gis_mapping_python_tiling.txt
Q: problem with list return type? my list has value such as m=[['na','1','2']['ka','31','45']['ra','3','5'] d=0 r=2 t=m[d][r] print t # this is givin number i.e 2 Now when I use this value u=[] u=m[t] I am getting an err msg saying type error list does take str values... i want to use like this how can i ...
problem with list return type?
my list has value such as m=[['na','1','2']['ka','31','45']['ra','3','5'] d=0 r=2 t=m[d][r] print t # this is givin number i.e 2 Now when I use this value u=[] u=m[t] I am getting an err msg saying type error list does take str values... i want to use like this how can i convert that t into a integer?? plea...
[ "Your problem is that you can't index into a list using a string. To convert t to an integer use int:\nu=m[int(t)]\n\n", "Use int(t) as the index, not t itself, since t is a string and to index a variable you need an integer, not a string, as the error message is telling you.\n" ]
[ 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0002926788_python.txt
Q: Taking file name from list and opening it? I have list similar to this: m=[['qw','wew','23','C:/xyz/s.wav'],['qw','wew','23','C:/xyz/s2.wav'],['qw','wew','23','C:/xyz/s1.wav']] Now I want to these files win=wave.open(m[0][3],'rb') It is giving error how can I use this in this way... I want to take the files name...
Taking file name from list and opening it?
I have list similar to this: m=[['qw','wew','23','C:/xyz/s.wav'],['qw','wew','23','C:/xyz/s2.wav'],['qw','wew','23','C:/xyz/s1.wav']] Now I want to these files win=wave.open(m[0][3],'rb') It is giving error how can I use this in this way... I want to take the files name from the list Please suggest???
[ "do this:\nm = [['qw','wew','23','C:/xyz/s.wav'],['qw','wew','23','C:/xyz/s2.wav'],['qw','wew','23','C:/xyz/s1.wav']]\nfname = m[0][3]\nprint 'fname is', repr(fname)\nwin = wave.open(fname, 'rb')\n\nand show us (using copy/paste into an edit of your question) everything that is printed, especially\n(1) the result o...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0002926866_python.txt
Q: Sort by an object's type I have code that statically registers (type, handler_function) pairs at module load time, resulting in a dict like this: HANDLERS = { str: HandleStr, int: HandleInt, ParentClass: HandleCustomParent, ChildClass: HandleCustomChild } def HandleObject(obj): for data_type in sorted...
Sort by an object's type
I have code that statically registers (type, handler_function) pairs at module load time, resulting in a dict like this: HANDLERS = { str: HandleStr, int: HandleInt, ParentClass: HandleCustomParent, ChildClass: HandleCustomChild } def HandleObject(obj): for data_type in sorted(HANDLERS.keys(), ???): if...
[ "If you know you're always dealing with new-style classes:\ndef numberofancestors(klass):\n return len(klass.mro())\n\nor, if you worry there may be old-style classes in the mix:\nimport inspect\n\ndef numberofancestors(klass):\n return len(inspect.getmro(klass))\n\nand then, in either case,\nsorted(HANDLERS,...
[ 5, 1, 0 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0002926522_python_sorting.txt
Q: Django get old url In django views,From the request how would we know from which page this view was called def password_change(request): if request.method == 'POST': u=request.user u.set_password(request.POST.get('new_password')) u.save() post_change_redirect= //Need old link here ...
Django get old url
In django views,From the request how would we know from which page this view was called def password_change(request): if request.method == 'POST': u=request.user u.set_password(request.POST.get('new_password')) u.save() post_change_redirect= //Need old link here return HttpResponseRed...
[ "try request.path\n", "Normally a variable in the query string (accessible via request.GET) is used to instruct the view where to redirect to.\n", "request.path\n\nwill return the full path (not including the domain). \ne.g. /music/bands/the_beatles/\n" ]
[ 1, 1, 0 ]
[]
[]
[ "django", "django_models", "django_views", "python" ]
stackoverflow_0002927031_django_django_models_django_views_python.txt
Q: Setting attributes of a class during construction from **kwargs Python noob here, Currently I'm working with SQLAlchemy, and I have this: from __init__ import Base from sqlalchemy.schema import Column, ForeignKey from sqlalchemy.types import Integer, String from sqlalchemy.orm import relationship class User(Base)...
Setting attributes of a class during construction from **kwargs
Python noob here, Currently I'm working with SQLAlchemy, and I have this: from __init__ import Base from sqlalchemy.schema import Column, ForeignKey from sqlalchemy.types import Integer, String from sqlalchemy.orm import relationship class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=Tr...
[ "My suggestion would be to not simplify it any further. You risk stepping on important object structures if you assign arbitrary attributes.\nThe one simplification I would do is to drop .keys() when you use it on a dict; both containment checking and iteration already use the keys.\n...\nOn second thought, you cou...
[ 2, 2, 1 ]
[]
[]
[ "class", "class_attributes", "python", "sqlalchemy" ]
stackoverflow_0002926593_class_class_attributes_python_sqlalchemy.txt
Q: Authentication using cookie key with asynchronous callback I need to write authentication function with asynchronous callback from remote Auth API. Simple authentication with login is working well, but authorization with cookie key, does not work. It should checks if in cookies present key "lp_login", fetch API ur...
Authentication using cookie key with asynchronous callback
I need to write authentication function with asynchronous callback from remote Auth API. Simple authentication with login is working well, but authorization with cookie key, does not work. It should checks if in cookies present key "lp_login", fetch API url like async and execute on_response function. The code almost w...
[ "It seems you cross-posted this on the tornado mailing list here\nOne of the problems you are running into is that you can't start the async call inside of get_current_user, you can only start an async call from something that happens inside of get or post.\nI've not tested it, but i think this should get you close...
[ 3 ]
[]
[]
[ "asynchronous", "authentication", "python", "tornado" ]
stackoverflow_0002848907_asynchronous_authentication_python_tornado.txt
Q: How do you call function after client finishes download from tornado web server? I would like to be able to run some cleanup functions if and only if the client successfully completes the download of a file I'm serving using Tornado. I installed the firefox throttle tool and had it slow the connection down to dial...
How do you call function after client finishes download from tornado web server?
I would like to be able to run some cleanup functions if and only if the client successfully completes the download of a file I'm serving using Tornado. I installed the firefox throttle tool and had it slow the connection down to dialup speed and installed this handler to generate a bunch of rubbish random text: class ...
[ "I believe you are looking for something that runs in the on_connection_close request handler method which you can override.\nKeep in mind that if you are running behind nginx, tornado will respond to nginx immediately, and nginx will slowly respond to the client.\nAlso, keep in mind that adding @tornado.web.asynch...
[ 1 ]
[]
[]
[ "python", "tornado" ]
stackoverflow_0002896082_python_tornado.txt
Q: Is there a way to convert code to a string and vice versa in Python? The original question was: Is there a way to declare macros in Python as they are declared in C: #define OBJWITHSIZE(_x) (sizeof _x)/(sizeof _x[0]) Here's what I'm trying to find out: Is there a way to avoid code duplication in Python? In one pa...
Is there a way to convert code to a string and vice versa in Python?
The original question was: Is there a way to declare macros in Python as they are declared in C: #define OBJWITHSIZE(_x) (sizeof _x)/(sizeof _x[0]) Here's what I'm trying to find out: Is there a way to avoid code duplication in Python? In one part of a program I'm writing, I have a function: def replaceProgramFilesPat...
[ "Answering the new question.\nIn your first python file (called, for example, first.py):\nimport os\n\ndef replaceProgramFilesPath(filenameBr):\n new_path = os.environ.get(\"PROGRAMFILES\") + chr(92)\n return filenameBr.replace(\"<ProgramFilesPath>\", new_path)\n\nIn the second python file (called, for example, s...
[ 3, 2, 2, 2, 2, 0, 0 ]
[]
[]
[ "macros", "python" ]
stackoverflow_0002925174_macros_python.txt
Q: Python: Problem importing pycurl I am working on OpenSolaris(2009.06) OS. i recently installed the pycurl libraires using the following command: $> python setup.py install --curl-config=/usr/local/bin/curl-config the installation went perfectly fine. However now when i am trying to import the pycurl library in my...
Python: Problem importing pycurl
I am working on OpenSolaris(2009.06) OS. i recently installed the pycurl libraires using the following command: $> python setup.py install --curl-config=/usr/local/bin/curl-config the installation went perfectly fine. However now when i am trying to import the pycurl library in my python program, an error is being rep...
[ "Sounds like your loader doesn't know where to find the cURL library. See your OS documentation for how to specify locations to search.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0002927738_python.txt
Q: Downloading from links in an rss feed I am trying to create a directory with news articles collected from an rss feed, meaning that whenever there is a link to an article within the rss feed, I would like for it to be downloaded in a directory with the title of the specific article as the filename as as a text fil...
Downloading from links in an rss feed
I am trying to create a directory with news articles collected from an rss feed, meaning that whenever there is a link to an article within the rss feed, I would like for it to be downloaded in a directory with the title of the specific article as the filename as as a text file. Is that something Python can help me do ...
[ "You can parse RSS feeds with feedparser and download files with urllib2. If you need to parse HTML use BeautifulSoup. If you have any problems with those, post more specific questions.\n", "Of course. BeautifulSoup, lxml, urllib2, urlgrabber.\n" ]
[ 2, 1 ]
[]
[]
[ "python", "rss" ]
stackoverflow_0002927543_python_rss.txt
Q: Running a batch file with parameters in Python OR F# I searched the site, but I didn't see anything quite matching what I was looking for. I created a stand-alone application that uses a web service I created. To run the client I use: C:/scriptsdirecotry> "run-client.bat" param1 param2 param3 param4 How would I g...
Running a batch file with parameters in Python OR F#
I searched the site, but I didn't see anything quite matching what I was looking for. I created a stand-alone application that uses a web service I created. To run the client I use: C:/scriptsdirecotry> "run-client.bat" param1 param2 param3 param4 How would I go about coding this in Python or F#. It seems like it shou...
[ "Python is similar.\nimport os\nos.system(\"run-client.bat param1 param2\")\n\nIf you need asynchronous behavior or redirected standard streams.\nfrom subprocess import *\np = Popen(['run-client.bat', param1, param2], stdout=PIPE, stderr=PIPE)\noutput, errors = p.communicate()\np.wait() # wait for process to termin...
[ 14, 8, 2 ]
[]
[]
[ "batch_file", "f#", "python", "web_services", "windows" ]
stackoverflow_0002916758_batch_file_f#_python_web_services_windows.txt
Q: Issue in exec method I am a having two python files file1.py and file2.py. I am using exec() to get the method/Variables defined in the file2.py. file1.py have a class as given below class one: def __init__(self): self.HOOK = None exec(file2.py) self.HOOK = Generate ...
Issue in exec method
I am a having two python files file1.py and file2.py. I am using exec() to get the method/Variables defined in the file2.py. file1.py have a class as given below class one: def __init__(self): self.HOOK = None exec(file2.py) self.HOOK = Generate ### call the hook m...
[ "Try this:\n# file1.py\nfrom file2 import Generate\n\nclass one:\n def __init__(self):\n self.HOOK = Generate\n ### call the hook method ####\n self.HOOK()\n\nIn your second file:\n# file2.py\ndef Generate():\n # do 1\n # do 2\n hello()\n\ndef hello()\n print \"hello\"\n\n", "From ...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002927005_python.txt
Q: Starting Tornado Web I'm quite new to using Tornado Web as a web server, and am having a little difficulty keeping it running. I normally use Django and Nginx, and am used to start/stop/restarting the server. However with Tornado I'm having trouble telling it to "run" without directly executing my main python file...
Starting Tornado Web
I'm quite new to using Tornado Web as a web server, and am having a little difficulty keeping it running. I normally use Django and Nginx, and am used to start/stop/restarting the server. However with Tornado I'm having trouble telling it to "run" without directly executing my main python file for the site, ie "python ...
[ "A better way to do it is using supervisord as it is also written in python\n", "No, there is not a way to have nginx spawn your tornado instance.\nTypically you would use an external framework like daemontools or a system init script to run the tornado process.\n" ]
[ 3, 2 ]
[]
[]
[ "python", "tornado", "ubuntu" ]
stackoverflow_0002864420_python_tornado_ubuntu.txt
Q: Different work of the script in Windows and in FreeBSD I'm writing some script, that works with web-servers. So, I have the following code: client = suds.client.Client(WSDLfile) client.service.Login('mylogin', 'mypass') print client.options.transport.cookiejar ####### sessnum = str(client.options.transport.cookiej...
Different work of the script in Windows and in FreeBSD
I'm writing some script, that works with web-servers. So, I have the following code: client = suds.client.Client(WSDLfile) client.service.Login('mylogin', 'mypass') print client.options.transport.cookiejar ####### sessnum = str(client.options.transport.cookiejar).split(' ')[1] client = suds.client.Client( WSDLfile, hea...
[ "AFAIK client.options.transport.cookiejar is an iterable so what happens on each system when you have:\nfor c in client.options.transport.cookiejar:\n print client.options.transport.cookiejar\n\nFailing that, what if in your Windows system you don't have cookies allowed? That may stop the session from being sav...
[ 2 ]
[]
[]
[ "cookies", "python", "suds" ]
stackoverflow_0002904098_cookies_python_suds.txt
Q: Python finding n consecutive numbers in a list I want to know how to find if there is a certain amount of consecutive numbers in a row in my list e.g. For example if I am looking for two 1's then: list = [1, 1, 1, 4, 6] #original list list = ["true", "true", 1, 4, 6] #after my function has been through the list. ...
Python finding n consecutive numbers in a list
I want to know how to find if there is a certain amount of consecutive numbers in a row in my list e.g. For example if I am looking for two 1's then: list = [1, 1, 1, 4, 6] #original list list = ["true", "true", 1, 4, 6] #after my function has been through the list. If I am looking for three 1's then: list = [1, 1, 1,...
[ "It is a bad idea to assign to list. Use a different name.\nTo find the largest number of consecutive equal values you can use itertools.groupby\n>>> import itertools\n>>> l = [1, 1, 1, 4, 6]\n>>> max(len(list(v)) for g,v in itertools.groupby(l)) \n3\n\nTo search only for consecutive 1s:\n>>> max(len(list(v)) for g...
[ 11, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002927213_python.txt
Q: Encrypt text using a number Project Euler I have recently begun to solve some of the Project Euler riddles. I found the discussion forum in the site a bit frustrating (most of the discussions are closed and poorly-threaded), So I have decided to publish my Python solutions on launchpad for discussion. The problem ...
Encrypt text using a number
Project Euler I have recently begun to solve some of the Project Euler riddles. I found the discussion forum in the site a bit frustrating (most of the discussions are closed and poorly-threaded), So I have decided to publish my Python solutions on launchpad for discussion. The problem is that it seems quite unethical ...
[ "It sounds like people will have to write their own decryption utility, or use something off-the-shelf, or use off-the-shelf components to decrypt your posts.\nPBKDF2 is a standardized algorithm for password-based key derivation, defined in PKCS #5. Basically, you can tune \"iterations\" parameter so that deriving ...
[ 4, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "algorithm", "encryption", "python" ]
stackoverflow_0002925781_algorithm_encryption_python.txt
Q: directory and file related doubts? i have a directory with around 1000 files....i want to run a same code for each of these file... my code requires the file name to be inputted. i have written code to copy the information of one into other in other format... please suggest a method to copy all 1000 files one by o...
directory and file related doubts?
i have a directory with around 1000 files....i want to run a same code for each of these file... my code requires the file name to be inputted. i have written code to copy the information of one into other in other format... please suggest a method to copy all 1000 files one by one without need to change the file name ...
[ "Why not just use an iterator over the list of files in the directory? I would post some example code but I do get the feeling that you're getting everyone else here to do your whole job for you.\n", "You could take a look at the glob module as well. It's this easy: \nimport glob\nlist_of_files = glob.glob('C:/be...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002928324_python.txt
Q: Python - from file to data structure? I have large file comprising ~100,000 lines. Each line corresponds to a cluster and each entry within each line is a reference i.d. for another file (protein structure in this case), e.g. 1hgn 1dju 3nmj 8kfn 9opu 7gfb 4bui I need to read in the file as a list of lists where ...
Python - from file to data structure?
I have large file comprising ~100,000 lines. Each line corresponds to a cluster and each entry within each line is a reference i.d. for another file (protein structure in this case), e.g. 1hgn 1dju 3nmj 8kfn 9opu 7gfb 4bui I need to read in the file as a list of lists where each line is a sublist, thus preserving the...
[ "Super simple:\nwith open('myfile', 'r') as f:\n data = [line.split() for line in f]\n\n", "You'll want to investigate the str.split() method.\n>>> '1hgn 1dju 3nmj 8kfn'.split()\n['1hgn', '1dju', '3nmj', '8kfn']\n\n" ]
[ 13, 6 ]
[]
[]
[ "python", "string" ]
stackoverflow_0002928883_python_string.txt
Q: How to print unsorted dictionary in python? I have this dict in python; d={} d['b']='beta' d['g']='gamma' d['a']='alpha' when i print the dict; for k,v in d.items(): print k i get this; a b g it seems like python sorts the dict automatically! how can i get the original unsorted list? Gath A: Dicts don't w...
How to print unsorted dictionary in python?
I have this dict in python; d={} d['b']='beta' d['g']='gamma' d['a']='alpha' when i print the dict; for k,v in d.items(): print k i get this; a b g it seems like python sorts the dict automatically! how can i get the original unsorted list? Gath
[ "Dicts don't work like that:\n\nCPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.\n\nYou could use a list with 2-tuples instead:\nd = [('b', 'beta'), ('g', 'g...
[ 11, 11, 6, 2, 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0002928686_dictionary_python.txt
Q: Inspiration and influence of the else clause of loop statements? Python loop statements may have an else clause which is executed if and only if the loop is not terminated by a break. In other words, when the condition becomes False (with while) or when the iterator is exhausted (with for). Does this loop-else con...
Inspiration and influence of the else clause of loop statements?
Python loop statements may have an else clause which is executed if and only if the loop is not terminated by a break. In other words, when the condition becomes False (with while) or when the iterator is exhausted (with for). Does this loop-else construct originate from another language (either theoretical or actually...
[ "A similar feature is found in Common Lisp's LOOP macro, described here by Peter Seibel:\n\n...LOOP provides two keywords, initially and finally, that introduce code to be run outside the loop's main body.\nAfter the initially or finally, these clauses consist of all the Lisp forms up to the start of the next loop ...
[ 4, 2 ]
[]
[]
[ "history", "if_statement", "loops", "python" ]
stackoverflow_0002924485_history_if_statement_loops_python.txt
Q: Potential Django Bug In QuerySet.query? Disclaimer: I'm still learning Django, so I might be missing something here, but I can't see what it would be... I'm running Python 2.6.1 and Django 1.2.1. (InteractiveConsole) >>> from myproject.myapp.models import * >>> qs = Identifier.objects.filter(Q(key="a") | Q(key="b"...
Potential Django Bug In QuerySet.query?
Disclaimer: I'm still learning Django, so I might be missing something here, but I can't see what it would be... I'm running Python 2.6.1 and Django 1.2.1. (InteractiveConsole) >>> from myproject.myapp.models import * >>> qs = Identifier.objects.filter(Q(key="a") | Q(key="b")) >>> print qs.query SELECT `app_identifier`...
[ "Ok, I just figured it out. It's not a bug. Browsing the source of django/db/models/sql/query.py:\n160 def __str__(self):\n161 \"\"\"\n162 Returns the query as a string of SQL with the parameter values\n163 substituted in.\n164 \n165 Parameter values won't necessarily be quoted...
[ 11 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002926483_django_python.txt
Q: Doubling binary digits How to double a number of binary digits in an integer? For example, if bin(x)="1001" then bin(y) must be "11000011". Is there any smart and fast algorithm ? UPDATE: Here is an elegant solution: ''.join([''.join(i) for i in zip(X,X)]) where X is bin(int_x)[2:] However, I am interested in a ...
Doubling binary digits
How to double a number of binary digits in an integer? For example, if bin(x)="1001" then bin(y) must be "11000011". Is there any smart and fast algorithm ? UPDATE: Here is an elegant solution: ''.join([''.join(i) for i in zip(X,X)]) where X is bin(int_x)[2:] However, I am interested in a more faster way and for the ...
[ "Here's one way that should be reasonably fast: convert your number to a binary string, then reinterpret the result as being in base 4. Now to make sure that all the '1's are doubled properly, multiply the result by 3.\n>>> x = 9\n>>> bin(x)\n'0b1001'\n>>> y = int(bin(x)[2:], 4)*3\n>>> bin(y)\n'0b11000011'\n\n", ...
[ 20, 16, 11, 4, 1, 0, 0 ]
[]
[]
[ "algorithm", "binary", "math", "python" ]
stackoverflow_0002928886_algorithm_binary_math_python.txt
Q: OpenGL GL_LINE_STRIP gives error 1281 (Invalid value) after glEnd I have no idea what is wrong with the simple code. The function is for use with python and ctypes. extern "C" void add_lines(bool antialias,GLdouble coordinates[][2],int array_size,GLdouble w,GLdouble r,GLdouble g, GLdouble b,GLdouble a){ glDisa...
OpenGL GL_LINE_STRIP gives error 1281 (Invalid value) after glEnd
I have no idea what is wrong with the simple code. The function is for use with python and ctypes. extern "C" void add_lines(bool antialias,GLdouble coordinates[][2],int array_size,GLdouble w,GLdouble r,GLdouble g, GLdouble b,GLdouble a){ glDisable(GL_TEXTURE_2D); if (antialias){ glEnable(GL_LINE_SMOOTH...
[ "glGetError() is sticky: once the error gets set by some function, it will stay at that error value until you call glGetError(). So, the error is likely being caused elsewhere. Check the value of glGetError() on function entry, and then after each function call to find out where it's being set.\n", "Are you sur...
[ 4, 0 ]
[]
[]
[ "c++", "ctypes", "opengl", "python" ]
stackoverflow_0002929598_c++_ctypes_opengl_python.txt
Q: Django 1.2: Dates in admin forms don't work with Locales (I10N=True) I have an application in Django 1.2. Language is selectable (I18N and Locale = True) When I select the english lang. in the site, the admin works OK. But when I change to any other language this is what happens with date inputs (spanish example):...
Django 1.2: Dates in admin forms don't work with Locales (I10N=True)
I have an application in Django 1.2. Language is selectable (I18N and Locale = True) When I select the english lang. in the site, the admin works OK. But when I change to any other language this is what happens with date inputs (spanish example): Correctly, the input accepts the spanish format %d/%m/%Y (Even selecting ...
[ "Adding this to your settings should solve the part you call \"the real problem\":\nDATE_INPUT_FORMATS = ( \n '%d/%m/%Y', '%d/%m/%y', # '25/10/2006', '25/10/06'\n '%Y-%m-%d', '%y-%m-%d', # '2006-10-25', '06-10-25'\n)\n\nDATETIME_INPUT_FORMATS = (\n '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59'\...
[ 2 ]
[]
[]
[ "date", "django", "django_admin", "python" ]
stackoverflow_0002929388_date_django_django_admin_python.txt
Q: HTTP basic authentication using sockets in python How to connect to a server using basic http auth thru sockets in python .I don't want to use urllib/urllib2 etc as my program does some low level socket I/O operations A: Probably the easiest place to start is using makefile() to get a simpler file-like interface...
HTTP basic authentication using sockets in python
How to connect to a server using basic http auth thru sockets in python .I don't want to use urllib/urllib2 etc as my program does some low level socket I/O operations
[ "Probably the easiest place to start is using makefile() to get a simpler file-like interface to the socket.\nimport socket, base64\n\nhost= 'www.example.com'\npath= '/'\nusername= 'fred'\npassword= 'bloggs'\ntoken= base64.encodestring('%s:%s' % (username, password)).strip()\n\nlines= [\n 'GET %s HTTP/1.1' % pat...
[ 5, 2 ]
[]
[]
[ "basic_authentication", "networking", "python", "sockets" ]
stackoverflow_0002929532_basic_authentication_networking_python_sockets.txt
Q: Cross platform /dev/null in Python I'm using the following code to hide stderr on Linux/OSX for a Python library I do not control that writes to stderr by default: f = open("/dev/null","w") zookeeper.set_log_stream(f) Is there an easy cross platform alternative to /dev/null? Ideally it would not consume memory s...
Cross platform /dev/null in Python
I'm using the following code to hide stderr on Linux/OSX for a Python library I do not control that writes to stderr by default: f = open("/dev/null","w") zookeeper.set_log_stream(f) Is there an easy cross platform alternative to /dev/null? Ideally it would not consume memory since this is a long running process.
[ "How about os.devnull ?\nimport os\nf = open(os.devnull,\"w\")\nzookeeper.set_log_stream(f)\n\n", "class Devnull(object):\n def write(self, *_): pass\n\nzookeeper.set_log_stream(Devnull())\n\nOpening os.devnull is fine too of course, but this way every output operation occurs (as a noop) \"in process\" -- no c...
[ 170, 48, 7, 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002929899_python.txt
Q: command line arg? This is a module named XYZ. def func(x) ..... ..... if __name__=="__main__": print func(sys.argv[1]) Now I have imported this module in another code and want to use the func. How can i use it? import XYZ After this, where to give the argument, and syntax on how to call it, please? A: imp...
command line arg?
This is a module named XYZ. def func(x) ..... ..... if __name__=="__main__": print func(sys.argv[1]) Now I have imported this module in another code and want to use the func. How can i use it? import XYZ After this, where to give the argument, and syntax on how to call it, please?
[ "import XYZ\nprint XYZ.func(foo)\n\n", "import XYZ\nXYZ.func('blah')\n\nor\nimport XYZ\nXYZ.func(sys.argv[1])\n\n", "The following will bring the name func into your current namespace so you can use it directly without the module prefix:\nfrom XYZ import func\nfunc(sys.argv[1])\n\nYou can also import the module...
[ 4, 2, 1 ]
[]
[]
[ "import", "module", "python", "syntax" ]
stackoverflow_0002929550_import_module_python_syntax.txt
Q: How to debug ctypes call of c++ dll? in my python project I call a c++ dll using ctypes library. That c++ dll consists on a wrapper dll that calls methods of a c# com interop dll. Sometimes I have a COM exception. I like to see what it corresponds exactlly but I don't know how to do it? How can I attach the c++ de...
How to debug ctypes call of c++ dll?
in my python project I call a c++ dll using ctypes library. That c++ dll consists on a wrapper dll that calls methods of a c# com interop dll. Sometimes I have a COM exception. I like to see what it corresponds exactlly but I don't know how to do it? How can I attach the c++ debugger to this situation? Thanks in advanc...
[ "I don't know about your direct question, but maybe you could get around it by using comtypes to go straight from COM to Python instead sticking C++ in between.\nThen all you have to do is:\n>>> from comtypes import client, COMError\n>>> myclassinst = client.CreateObject('MyCOMClass.MyCOMClass')\n>>> try:\n... ...
[ 0 ]
[]
[]
[ "c#", "c++", "dll", "python" ]
stackoverflow_0002929970_c#_c++_dll_python.txt
Q: Ruby GTK fails without display (Python is OK) it seems that Ruby GTK apps are unable to run in nongraphical environment.. while python apps are able to. oversimplified examples (even without the gtk main loop), demonstrating this behavior: gtktest.py: #! /usr/bin/python import gtk print('the end') gtktest.rb: #! ...
Ruby GTK fails without display (Python is OK)
it seems that Ruby GTK apps are unable to run in nongraphical environment.. while python apps are able to. oversimplified examples (even without the gtk main loop), demonstrating this behavior: gtktest.py: #! /usr/bin/python import gtk print('the end') gtktest.rb: #! /usr/bin/ruby require "gtk2" puts('the end') X win...
[ "Yes you can, setup Xvfb.\n" ]
[ 2 ]
[]
[]
[ "gtk", "gtk2", "python", "ruby" ]
stackoverflow_0002929774_gtk_gtk2_python_ruby.txt
Q: ctypes and PySide I'm building an app with PySide, there's some image manipulation that needs to be done and using Python code for this is way too slow. Therefore I hacked out a .dll file that will do it for me. The function definition is as follows: extern "C" { QRectF get_image_slant(QImage *img, float slanta...
ctypes and PySide
I'm building an app with PySide, there's some image manipulation that needs to be done and using Python code for this is way too slow. Therefore I hacked out a .dll file that will do it for me. The function definition is as follows: extern "C" { QRectF get_image_slant(QImage *img, float slantangle, float offset) { ...
[ "Since ctypes for C++ isn't working very well, I would recommend using PySide's own wrapper - Shiboken. They actually use it to wrap the Qt libs themselves. Since your code deals with Qt object, this seems like the perfect choice for you.\n" ]
[ 1 ]
[]
[]
[ "ctypes", "pyside", "python", "qt4" ]
stackoverflow_0002930154_ctypes_pyside_python_qt4.txt
Q: Reading numeric Excel data as text using xlrd in Python I am trying to read in an Excel file using xlrd, and I am wondering if there is a way to ignore the cell formatting used in Excel file, and just import all data as text? Here is the code I am using for far: import xlrd xls_file = 'xltest.xls' xls_workbook = ...
Reading numeric Excel data as text using xlrd in Python
I am trying to read in an Excel file using xlrd, and I am wondering if there is a way to ignore the cell formatting used in Excel file, and just import all data as text? Here is the code I am using for far: import xlrd xls_file = 'xltest.xls' xls_workbook = xlrd.open_workbook(xls_file) xls_sheet = xls_workbook.sheet_b...
[ "That's because integer values in Excel are imported as floats in Python. Thus, sheet.cell(r,c).value returns a float. Try converting the values to integers but first make sure those values were integers in Excel to begin with:\ncell = sheet.cell(r,c)\ncell_value = cell.value\nif cell.ctype in (2,3) and int(cell_va...
[ 24, 4 ]
[]
[]
[ "csv", "excel", "python", "xlrd", "xls" ]
stackoverflow_0002739989_csv_excel_python_xlrd_xls.txt
Q: how do I instrospect appengine's datastore models? in order to dynamically create a form, i have to find the property types of a model's properties at runtime. appengine docs says that Model.properties() will return a dictionary of properties name and their class type. when i use this method in my code, only the n...
how do I instrospect appengine's datastore models?
in order to dynamically create a form, i have to find the property types of a model's properties at runtime. appengine docs says that Model.properties() will return a dictionary of properties name and their class type. when i use this method in my code, only the name is returned and the classtype value is always empty....
[ "Model.kind()\nE.g., for a model like this:\nclass LargeTextList(db.Model):\n large_text_list = db.ListProperty(item_type=db.Text)\n\nmy_model_instance.kind() returns LargeTextList.\n\nEdit (thanks to OP for clarification):\nThe property information you seek is there, but you'll need to escape to see it, e.g. in...
[ 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002930352_google_app_engine_google_cloud_datastore_python.txt
Q: Python point lookup (coordinate binning?) Greetings, I am trying to bin an array of points (x, y) into an array of boxes [(x0, y0), (x1, y0), (x0, y1), (x1, y1)] (tuples are the corner points) So far I have the following routine: def isInside(self, point, x0, x1, y0, y1): pr1 = getProduct(point, (x0, y0), (x1,...
Python point lookup (coordinate binning?)
Greetings, I am trying to bin an array of points (x, y) into an array of boxes [(x0, y0), (x1, y0), (x0, y1), (x1, y1)] (tuples are the corner points) So far I have the following routine: def isInside(self, point, x0, x1, y0, y1): pr1 = getProduct(point, (x0, y0), (x1, y0)) if pr1 >= 0: pr2 = getProduct...
[ "If I understand your problem correctly then the following should work assuming that your points are also 2-tuples.\ndef in_bin(point, lower_corner, upper_corner):\n \"\"\"\n lower_corner is a 2-tuple - the coords of the lower left hand corner of the\n bin.\n upper_corner is a 2-tuple - the coords of th...
[ 2, 1, 1, 1, 1, 1, 1, 0 ]
[]
[]
[ "geometry", "numpy", "python" ]
stackoverflow_0002903878_geometry_numpy_python.txt
Q: Start local PHP script w/ local Python script The Python program I'm writing needs to start a local PHP script outside of Python's process. The program also needs to pass params to the PHP script. So far this seems to start the script: os.system( path_to_script_here param param ) However, I'm pretty certain that...
Start local PHP script w/ local Python script
The Python program I'm writing needs to start a local PHP script outside of Python's process. The program also needs to pass params to the PHP script. So far this seems to start the script: os.system( path_to_script_here param param ) However, I'm pretty certain that Python remains running until the PHP script is com...
[ "See: How to start a background process in Python?\n" ]
[ 2 ]
[]
[]
[ "os.system", "php", "python" ]
stackoverflow_0002931061_os.system_php_python.txt
Q: Fastest way to find the rotation of a vector I have two 2D vectors, say u and v, defined by cartesian coordinates. Imagine that vectors are needles of a clock. I'm looking for the fastest way to find out, using python, if v is after or before u (or in other words find out in wich half plane is v, regarding to posi...
Fastest way to find the rotation of a vector
I have two 2D vectors, say u and v, defined by cartesian coordinates. Imagine that vectors are needles of a clock. I'm looking for the fastest way to find out, using python, if v is after or before u (or in other words find out in wich half plane is v, regarding to position of u). For the purpose of the problem if vect...
[ "def after(u, v):\n # return sign of cross product\n return u[0]*v[1]<u[1]*v[0]\n\ndon't know if it's fast, but it is terse\n", "General idea: Rotate the x-axis to coincide with v and check that the new y coordinate of u is positive. \n", "So you want to know what side of the line representing vector u th...
[ 13, 0, 0, 0 ]
[]
[]
[ "math", "optimization", "python" ]
stackoverflow_0002930942_math_optimization_python.txt
Q: How do i make my web browser made in wx.python to parse pages(ex.Google.ro) Can somebody help me? please i really need to parse at least google. i need to parse url page. i've made a web browser and this web browser doesn't parse pages. It's made in wxpython. A: Have you looked at BeautifulSoup? http://www.cru...
How do i make my web browser made in wx.python to parse pages(ex.Google.ro)
Can somebody help me? please i really need to parse at least google. i need to parse url page. i've made a web browser and this web browser doesn't parse pages. It's made in wxpython.
[ "Have you looked at BeautifulSoup? http://www.crummy.com/software/BeautifulSoup/\n" ]
[ 1 ]
[]
[]
[ "parsing", "python", "wxpython", "wxwidgets" ]
stackoverflow_0002930985_parsing_python_wxpython_wxwidgets.txt
Q: Tkinter Label bound to StringVar is one click behind when updating The problem I'm running into here is that, when I click on the different file names in the Listbox, the Label changes value one click behind whatever I'm currently clicking on. What am I missing here? import Tkinter as tk class TkTest: def ...
Tkinter Label bound to StringVar is one click behind when updating
The problem I'm running into here is that, when I click on the different file names in the Listbox, the Label changes value one click behind whatever I'm currently clicking on. What am I missing here? import Tkinter as tk class TkTest: def __init__(self, master): self.fraMain = tk.Frame(master) ...
[ "The problem has to do with the fundamental design of Tk. The short version is, bindings on specific widgets fire before the default class bindings for a widget. It is in the class bindings that the selection of a listbox is changed. This is exactly what you observe -- you are seeing the selection before the curren...
[ 4 ]
[]
[]
[ "label", "listbox", "python", "refresh", "tkinter" ]
stackoverflow_0002931053_label_listbox_python_refresh_tkinter.txt
Q: JavaScript cookie value can't be retrieved in Django I am trying to build a web site in both English and Bulgarian using the Django framework. My idea is the user should click on a button, the page will reload and the language will be changed. This is how I am trying to do it: In my html I hava a the button tag <b...
JavaScript cookie value can't be retrieved in Django
I am trying to build a web site in both English and Bulgarian using the Django framework. My idea is the user should click on a button, the page will reload and the language will be changed. This is how I am trying to do it: In my html I hava a the button tag <button id='btn' onclick="changeLanguage();" type="button"> ...
[ "The session is not the same as a cookie. \nSessions are an internal Django database table, the key to which is stored in a cookie. However the rest of the data apart from the key is stored in the database.\nIf you want to access an actual cookie that's been set by the client, you need to use the request.COOKIES di...
[ 10 ]
[]
[]
[ "cookies", "django", "javascript", "python" ]
stackoverflow_0002931324_cookies_django_javascript_python.txt
Q: Pickling an unbound method in Python 3 I would like to pickle an unbound method in Python 3.x. I'm getting this error: >>> class A: ... def m(self): ... pass >>> import pickle >>> pickle.dumps(A.m) Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> pickle.dumps(A.m) File...
Pickling an unbound method in Python 3
I would like to pickle an unbound method in Python 3.x. I'm getting this error: >>> class A: ... def m(self): ... pass >>> import pickle >>> pickle.dumps(A.m) Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> pickle.dumps(A.m) File "C:\Python31\lib\pickle.py", line 1358, in ...
[ "This cannot be done directly because in Python 3 unbound method type is gone: it is just a function:\n>>> print (type (A.m))\n<class 'function'>\n\nPython functions are not bound to a class, so it is impossible to tell what class A.m belongs to just by looking at the expression result.\nDepending on what exactly y...
[ 7 ]
[]
[]
[ "methods", "pickle", "python", "python_3.x" ]
stackoverflow_0002930792_methods_pickle_python_python_3.x.txt
Q: Having a Python package install itself under a different name I'm developing a package called garlicsim. (Website.) The package is intended for Python 2.X, but I am also offerring Python 3 support on a different fork called garlicsim_py3.(1) So both of these packages live side by side on PyPI, and Python 3 users i...
Having a Python package install itself under a different name
I'm developing a package called garlicsim. (Website.) The package is intended for Python 2.X, but I am also offerring Python 3 support on a different fork called garlicsim_py3.(1) So both of these packages live side by side on PyPI, and Python 3 users install garlicsim_py3, and Python 2 users install garlicsim. The pro...
[ "Eventually I decided not to do it, and just have the two projects have the same package name even though they have a different PyPI name.\n" ]
[ 1 ]
[]
[]
[ "packaging", "python", "python_3.x", "setuptools" ]
stackoverflow_0002923704_packaging_python_python_3.x_setuptools.txt
Q: Trying to figure out URL dispatcher for sluggale URLs like stackoverflow I'm using the Tornado framework (Python). I have the sluggable URLs working. But I have 3 different entries in the URL dispatcher. I was wondering if someone could help me transform it into one line. This is what I have: (r"/post/([0-9]+...
Trying to figure out URL dispatcher for sluggale URLs like stackoverflow
I'm using the Tornado framework (Python). I have the sluggable URLs working. But I have 3 different entries in the URL dispatcher. I was wondering if someone could help me transform it into one line. This is what I have: (r"/post/([0-9]+)/[a-zA-Z0-9\-]+", SpotHandler), (r"/post/([0-9]+)/", SpotHandler), (r"/post/(...
[ "r\"/post/([0-9]+)(?:/[a-zA-Z_-]+|/)?\"\n\n", "(r\"/post/([0-9]+)/?[a-zA-Z_]*\", SpotHandler),\n\"?\" means previous thing can be there but need not be.\n\"*\" means zero or more\n" ]
[ 2, 1 ]
[]
[]
[ "python", "slug", "tornado" ]
stackoverflow_0002932098_python_slug_tornado.txt
Q: decorating a function and adding functionalities preserving the number of argument I'd like to decorate a function, using a pattern like this: def deco(func): def wrap(*a,**kw): print "do something" return func(*a,**kw) return wrap The problem is that if the function decorated has a protot...
decorating a function and adding functionalities preserving the number of argument
I'd like to decorate a function, using a pattern like this: def deco(func): def wrap(*a,**kw): print "do something" return func(*a,**kw) return wrap The problem is that if the function decorated has a prototype like that: def function(a,b,c): return When decorated, the prototype is destroyed b...
[ "You're wrong when you state that \"calling function(1,2,3,4) wouldn't result in an exception\". Check it out:\n>>> def deco(f):\n... def w(*a, **k):\n... print 'do something'\n... return f(*a, **k)\n... return w\n... \n>>> def f(a, b, c): return\n... \n>>> f(1, 2, 3, 4)\nTraceback (most recent call la...
[ 4, 3, 3, 0 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0002932356_decorator_python.txt
Q: How do I use a string as a keyword argument? Specifically, I'm trying to use a string to arbitrairly filter the ORM. I've tried exec and eval solutions, but I'm running into walls. The code below doesn't work, but it's the best way I know how to explain where I'm trying to go from gblocks.models import Image f =...
How do I use a string as a keyword argument?
Specifically, I'm trying to use a string to arbitrairly filter the ORM. I've tried exec and eval solutions, but I'm running into walls. The code below doesn't work, but it's the best way I know how to explain where I'm trying to go from gblocks.models import Image f = 'image__endswith="jpg"' # Would be scripted in an...
[ "d = Image.objects.filter(**{'image__endswith': \"jpg\"})\n\n", "You'd need to split out the value from the keyword, then set up a dict using the keyword as the key, and the value as the value. You could then use the double-asterisk function paramater with the dict.\nSo...\nkeyword, sep, value = f.partition('=')\...
[ 110, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002932648_python.txt
Q: How do i call a method by a string name using python? I have the following class; class myStringMethod(): def __init__(self): self.func_list= [('func1','print_func1()'),('func2','print_func2()')] def print_func1(self, name): print name def print_func2(self, name): print name ...
How do i call a method by a string name using python?
I have the following class; class myStringMethod(): def __init__(self): self.func_list= [('func1','print_func1()'),('func2','print_func2()')] def print_func1(self, name): print name def print_func2(self, name): print name def call_func_by_name(self): for func in self.f...
[ "your self.func_list should be:\nself.func_list= [('func1','print_func1'),('func2','print_func2')]\n\nAnd the way your code is written it will, of course, print 'Func Name'. I guess you probably meant to pass func[0] there.\nWorking example:\n>>> class myStringMethod():\n def __init__(self):\n self.func_l...
[ 3, 0 ]
[]
[]
[ "function", "python" ]
stackoverflow_0002930196_function_python.txt
Q: Is cropping of jpeg images using the PIL lossless? A simple questions really. If you crop a jpeg image using the Python Imaging Library, is the resulting image recompressed, or is it lossless? A: Generally not. There is a python wrapper for the lossless jpeg library. Cropping might be essentially lossless if you...
Is cropping of jpeg images using the PIL lossless?
A simple questions really. If you crop a jpeg image using the Python Imaging Library, is the resulting image recompressed, or is it lossless?
[ "Generally not. There is a python wrapper for the lossless jpeg library.\nCropping might be essentially lossless if you remove entire 8x8 pixel blocks\n" ]
[ 5 ]
[]
[]
[ "crop", "jpeg", "lossless", "python", "python_imaging_library" ]
stackoverflow_0002933084_crop_jpeg_lossless_python_python_imaging_library.txt
Q: Email notifications of exceptions happening in a Python app? UPDATE: This is a Django web app Hi folks, I want to set up email notifications when there is an error happening in my application. In ruby, there is a very elegant solution called ExceptionNotifier, which wraps around the exception handler and uses the ...
Email notifications of exceptions happening in a Python app?
UPDATE: This is a Django web app Hi folks, I want to set up email notifications when there is an error happening in my application. In ruby, there is a very elegant solution called ExceptionNotifier, which wraps around the exception handler and uses the built-in mailer to send an email. What is the best way of doing th...
[ "(I'm guessing you're talking about a web app here, because ExceptionNotifier is a Rails plugin...)\nA Python web app using which framework? I know there's Django-hoptoad, which is actually a step above the ExecptionNotifier of Ruby, using ThoughtBot's Hoptoad.\nBut that's just a guess that you're using Django, whi...
[ 3 ]
[]
[]
[ "debugging", "email", "exception", "exception_handling", "python" ]
stackoverflow_0002933392_debugging_email_exception_exception_handling_python.txt
Q: Possible to call single-parameter Python function without using parentheses? The Python documentation specifies that is is legal to omit the parentheses if a function only takes a single parameter, but myfunction "Hello!" generates a syntax error. So, what's the deal? EDIT: The statement that I read only applies...
Possible to call single-parameter Python function without using parentheses?
The Python documentation specifies that is is legal to omit the parentheses if a function only takes a single parameter, but myfunction "Hello!" generates a syntax error. So, what's the deal? EDIT: The statement that I read only applies to generator expressions: The parentheses can be omitted on calls with only one ...
[ "For your edit:\nIf you write down a generator expression, like stuff = (f(x) for x in items) you need the brackets, just like you need the [ .. ] around a list comprehension. \nBut when you pass something from a generator expression to a function (which is a pretty common pattern, because that's pretty much the bi...
[ 8, 5, 2, 0 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0002932887_python_syntax.txt
Q: Python: Using `copyreg` to define reducers for types that already have reducers (Keep in mind I'm working in Python 3, so a solution needs to work in Python 3.) I would like to use the copyreg module to teach Python how to pickle functions. When I tried to do it, the _Pickler object would still try to pickle funct...
Python: Using `copyreg` to define reducers for types that already have reducers
(Keep in mind I'm working in Python 3, so a solution needs to work in Python 3.) I would like to use the copyreg module to teach Python how to pickle functions. When I tried to do it, the _Pickler object would still try to pickle functions using the save_global function. (Which doesn't work for unbound methods, and tha...
[ "The following hack seems to work in Python 3.1...:\nimport copyreg\ndef functionpickler(f):\n print('pickling', f.__name__)\n return f.__name__\n\nft = type(functionpickler)\ncopyreg.pickle(ft, functionpickler)\n\nimport pickle\npickle.Pickler = pickle._Pickler\ndel pickle.Pickler.dispatch[ft]\n\ns = pickle.dump...
[ 1 ]
[]
[]
[ "function", "pickle", "python" ]
stackoverflow_0002932742_function_pickle_python.txt
Q: Python help reading csv file failing due to line-endings I'm trying to create this script that will check the computer host name then search a master list for the value to return a corresponding value in the csv file. Then open another file and do a find an replace. I know this should be easy but haven't done so m...
Python help reading csv file failing due to line-endings
I'm trying to create this script that will check the computer host name then search a master list for the value to return a corresponding value in the csv file. Then open another file and do a find an replace. I know this should be easy but haven't done so much in python before. Here is what I have so far... masterlist...
[ "The two occurrences of '\\xD5' in line 194 and the last line have nothing to do with the problem.\nThe problem appears to be a bug, or a misleading error message, or incorrect/vague documentation, in the Python 2.6 csv module.\nIn the file, the lines are terminated by '\\x0D' aka '\\r' in the Classic Mac tradition...
[ 20, 2, 2 ]
[]
[]
[ "csv", "line_endings", "python", "universal" ]
stackoverflow_0002930673_csv_line_endings_python_universal.txt
Q: SQL Alchemy MVC and cross controller joins When using SQL Alchemy for abstracting your data access layer and using controllers as the way to access objects from that abstraction layer, how should joins be handled? So for example, say you have an Orders controller class that manages Order objects such that it provi...
SQL Alchemy MVC and cross controller joins
When using SQL Alchemy for abstracting your data access layer and using controllers as the way to access objects from that abstraction layer, how should joins be handled? So for example, say you have an Orders controller class that manages Order objects such that it provides getOrder, saveOrder, etc methods and likewis...
[ "Controllers are meant to encapsulate features for your convienience. Not to bind your hands. If you want to join, simply join. Use the controller that you think is logically fittest to make the query.\n" ]
[ 2 ]
[]
[]
[ "controllers", "dns", "model_view_controller", "python", "sqlalchemy" ]
stackoverflow_0002933796_controllers_dns_model_view_controller_python_sqlalchemy.txt
Q: how i can open different linux terminal to output differnt kinds of debug information in python? I need output different information to different terminal instances instead of print them in same output stream, say std.err or std.out. for example: I have 5 kinds of information say A-E need to be displayed on differ...
how i can open different linux terminal to output differnt kinds of debug information in python?
I need output different information to different terminal instances instead of print them in same output stream, say std.err or std.out. for example: I have 5 kinds of information say A-E need to be displayed on different terminal windows on same desktop, looks like [terminal 1] <- for displaying information A [termin...
[ "Open a pipe, then fork off a terminal running cat reading from the read end of the pipe, and write into the write end of the pipe.\n", "Using the subprocess module, just run several instances of whichever terminal program you like, each running \"cat\", using subprocess.Popen. Pass stdin=subprocess.PIPE in addit...
[ 3, 1 ]
[]
[]
[ "python", "stream", "terminal" ]
stackoverflow_0002933601_python_stream_terminal.txt
Q: Python os.path.walk() method I'm currently using the walk method in a uni assignment. It's all working fine, but I was hoping that someone could explain something to me. in the example below, what is the a parameter used for on the myvisit method? >>> from os.path import walk >>> def myvisit(a, dir, files): ... ...
Python os.path.walk() method
I'm currently using the walk method in a uni assignment. It's all working fine, but I was hoping that someone could explain something to me. in the example below, what is the a parameter used for on the myvisit method? >>> from os.path import walk >>> def myvisit(a, dir, files): ... print dir,": %d files"%len(files...
[ "The first argument to your callback function is the last argument of the os.path.walk function. Its most obvious use is to allow you to keep state between the successive calls to the helper function (in your case, myvisit).\nos.path.walk is a deprecated function. You really should use os.walk, which has no need fo...
[ 29, 11 ]
[]
[]
[ "python" ]
stackoverflow_0002934281_python.txt
Q: Is there any way to do this without using '__init__'? class a(object): c=b()# how to call the b method d=4 def __init__(self): print self.c def b(self): return self.d+1 a() how to call the 'b' method not in the __init__ thanks the error is : Traceback (most recent call last): ...
Is there any way to do this without using '__init__'?
class a(object): c=b()# how to call the b method d=4 def __init__(self): print self.c def b(self): return self.d+1 a() how to call the 'b' method not in the __init__ thanks the error is : Traceback (most recent call last): File "D:\zjm_code\a.py", line 12, in <module> class a(o...
[ "I would use a property instead:\nclass a(object):\n d=4\n def __init__(self):\n print self.c\n def b(self):\n return self.d+1\n c = property(b)\n\na()\na.c # returns a.b()\n\n", "If you want a().c to always return a().d + 1, then use property as suggested by Olivier. However, if you ...
[ 4, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002934363_python.txt
Q: Steps in list question, Python beginner The following code include the last number. >>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> numbers[::3] [1, 4, 7, 10] Why does not includet the last number 2, like 10, 8, 6, 4, 2? >>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> numbers[:1:-2] [10, 8, 6, 4] A: It seem...
Steps in list question, Python beginner
The following code include the last number. >>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> numbers[::3] [1, 4, 7, 10] Why does not includet the last number 2, like 10, 8, 6, 4, 2? >>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> numbers[:1:-2] [10, 8, 6, 4]
[ "It seems that the slice operator is simply non-inclusive of the second argument. In other-words, your 1 should be a 0:\n>>> numbers = [1,2,3,4,5,6,7,8,9,10]\n>>> numbers[:1:-2]\n[10, 8, 6, 4]\n>>> numbers[:0:-2]\n[10, 8, 6, 4, 2]\n\nHope that helps :)\nFor further info, see Note 5 here.\n", ":: is walking over t...
[ 4, 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002934819_python.txt
Q: Wxpython cut copy paste and openfiledialog i have a web browser made in python with menu. in one menu i have cut copy paste but no functionality and i need to make them work. i need an example of class oncopy.(event menu) Open file i manage to work like this .takes file and print on screen the link to that file bu...
Wxpython cut copy paste and openfiledialog
i have a web browser made in python with menu. in one menu i have cut copy paste but no functionality and i need to make them work. i need an example of class oncopy.(event menu) Open file i manage to work like this .takes file and print on screen the link to that file but how can make open dialog to open a file at lea...
[ "if filepath is the absolute pathname of the file you got from the opendialog, try:\nimport os\nos.startfile(filepath)\n\nThis will open your file with its corresponding windows application to which its extension is associated (like clicking twice in the file icon)\nTo copy a selected text in the HTML window, if yo...
[ 0 ]
[]
[]
[ "dialog", "events", "openfiledialog", "python", "wxpython" ]
stackoverflow_0002934892_dialog_events_openfiledialog_python_wxpython.txt
Q: Change array that might contain None to an array that contains "" in python I have a python function that gets an array called row. Typically row contains things like: ["Hello","goodbye","green"] And I print it with: print "\t".join(row) Unfortunately, sometimes it contains: ["Hello",None,"green"] Which generat...
Change array that might contain None to an array that contains "" in python
I have a python function that gets an array called row. Typically row contains things like: ["Hello","goodbye","green"] And I print it with: print "\t".join(row) Unfortunately, sometimes it contains: ["Hello",None,"green"] Which generates this error: TypeError: sequence item 2: expected string or Unicode, NoneType f...
[ "You can use a conditional expression:\n>>> l = [\"Hello\", None, \"green\"]\n>>> [(x if x is not None else '') for x in l]\n['Hello', '', 'green']\n\nA slightly shorter way is:\n>>> [x or '' for x in l]\n\nBut note that the second method also changes 0 and some other objects to the empty string.\n", "You can use...
[ 11, 1, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0002932304_python_string.txt
Q: What is the cleanest way to do a sort plus uniq on a Python list? Consider a Python list my_list containing ['foo', 'foo', 'bar']. What is the most Pythonic way to uniquify and sort a list ? (think cat my_list | sort | uniq) This is how I currently do it and while it works I'm sure there are better ways to do it. ...
What is the cleanest way to do a sort plus uniq on a Python list?
Consider a Python list my_list containing ['foo', 'foo', 'bar']. What is the most Pythonic way to uniquify and sort a list ? (think cat my_list | sort | uniq) This is how I currently do it and while it works I'm sure there are better ways to do it. my_list = [] ... my_list.append("foo") my_list.append("foo") my_list.ap...
[ "my_list = sorted(set(my_list))\n\n", "# Python ≥ 2.4\n# because of (generator expression) and itertools.groupby, sorted\n\nimport itertools\n\ndef sort_uniq(sequence):\n return (x[0] for x in itertools.groupby(sorted(sequence)))\n\nFaster:\nimport itertools, operator\nimport sys\n\nif sys.hexversion < 0x03000...
[ 132, 20, 6, 2 ]
[ "Can't say it is clean way to do that, but just for fun:\nmy_list = [x for x in sorted(my_list) if not x in locals()[\"_[1]\"]]\n\n" ]
[ -4 ]
[ "python", "unique" ]
stackoverflow_0002931672_python_unique.txt
Q: Partially flattening a list This is probably a really silly question but, given the example code at the bottom, how would I get a single list that retain the tuples? (I've looked at itertools but it flattens everything.) What I currently get is: ('id', 20, 'integer') ('companyname', 50, 'text') [('focus', 30, '...
Partially flattening a list
This is probably a really silly question but, given the example code at the bottom, how would I get a single list that retain the tuples? (I've looked at itertools but it flattens everything.) What I currently get is: ('id', 20, 'integer') ('companyname', 50, 'text') [('focus', 30, 'text'), ('fiesta', 30, 'text'), (...
[ "Can you make it into\n[[(\"id\",20,\"integer\")],\n [(\"companyname\",50,\"text\")],\n getproducts(),\n ...]\n\n? If so, you just need to concatenate the lists.\nreturn sum(column_title_list, [])\n\nYou could also use\nreturn [(\"id\",20,\"integer\"),(\"companyname\",50,\"text\")] + getproducts() + ...\n\n", "Th...
[ 2, 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002935291_python.txt
Q: Why does Python's 'for ... in' work differently on a list of values vs. a list of dictionaries? I'm wondering about some details of how for ... in works in Python. My understanding is for var in iterable on each iteration creates a variable, var, bound to the current value of iterable. So, if you do for c in cows;...
Why does Python's 'for ... in' work differently on a list of values vs. a list of dictionaries?
I'm wondering about some details of how for ... in works in Python. My understanding is for var in iterable on each iteration creates a variable, var, bound to the current value of iterable. So, if you do for c in cows; c = cows[whatever], but changing c within the loop does not affect the original value. However, it s...
[ "It helps to picture what happens to the reference held by c in each iteration:\n[ 0, 1, 2, 3, 4, 5 ]\n ^\n |\n c\n\nc holds a reference pointing to the first element in the list. When you do c += 2 (i.e., c = c + 2, the temporary variable c is reassigned a new value. This new value is 2, and c is rebound to thi...
[ 17, 5, 4, 4, 3, 1, 1 ]
[]
[]
[ "iteration", "python" ]
stackoverflow_0002926580_iteration_python.txt
Q: Are there any Python reference counting/garbage collection gotchas when dealing with C code? Just for the sheer heck of it, I've decided to create a Scheme binding to libpython so you can embed Python in Scheme programs. I'm already able to call into Python's C API, but I haven't really thought about memory manag...
Are there any Python reference counting/garbage collection gotchas when dealing with C code?
Just for the sheer heck of it, I've decided to create a Scheme binding to libpython so you can embed Python in Scheme programs. I'm already able to call into Python's C API, but I haven't really thought about memory management. The way mzscheme's FFI works is that I can call a function, and if that function returns a ...
[ "Your link to http://docs.python.org/extending/extending.html#reference-counts is the right place. The Extending and Embedding and Python/C API sections of the documentation are the ones that will explain how to use the C API.\nReference counting is one of the annoying parts of using the C API. The main gotcha is k...
[ 8, 3 ]
[]
[]
[ "garbage_collection", "python", "python_c_api", "reference_counting", "scheme" ]
stackoverflow_0002935186_garbage_collection_python_python_c_api_reference_counting_scheme.txt
Q: efficiently convert string (or tuple) to ctypes array I've got code that takes a PIL image and converts it to a ctypes array to pass out to a C function: w_px, h_px = img.size pixels = struct.unpack('%dI'%(w_px*h_px), img.convert('RGBA').tostring()) pixels_array = (ctypes.c_int * len(pixels))(*pixels) But I'm dea...
efficiently convert string (or tuple) to ctypes array
I've got code that takes a PIL image and converts it to a ctypes array to pass out to a C function: w_px, h_px = img.size pixels = struct.unpack('%dI'%(w_px*h_px), img.convert('RGBA').tostring()) pixels_array = (ctypes.c_int * len(pixels))(*pixels) But I'm dealing with big images, and unpacking that many items into fu...
[ "You can first build an uninitialized array:\npixarray = (ctypes.c_int * (w_px * h_px))()\n\nand then copy the image's contents into it:\n# dylib in MacOSX, cdll.wincrt in Win, libc.so.? in Unix, ...\nclib = ctypes.CDLL('libc.dylib')\n\n_ = clib.memcpy(pixarray, im.tostring(), w_px * h_px * 4)\n\nThe return value o...
[ 7 ]
[]
[]
[ "ctypes", "python", "python_imaging_library" ]
stackoverflow_0002935616_ctypes_python_python_imaging_library.txt
Q: Running shell commands without a shell window With either subprocess.call or subprocess.Popen, executing a shell command makes a shell window quicky appear and disappear. How can I run the shell command without the shell window? A: I imagine your observation is limited to Windows, since that, I believe, is the o...
Running shell commands without a shell window
With either subprocess.call or subprocess.Popen, executing a shell command makes a shell window quicky appear and disappear. How can I run the shell command without the shell window?
[ "I imagine your observation is limited to Windows, since that, I believe, is the only platform on which you'll get that \"console flash\" issue. If so, then the docs offer the following semi-helpful paragraph:\n\nThe startupinfo and creationflags, if\n given, will be passed to the\n underlying CreateProcess() fu...
[ 25 ]
[]
[]
[ "python", "shell", "subprocess", "windows" ]
stackoverflow_0002935704_python_shell_subprocess_windows.txt
Q: Web hooks in Python: Any particular library? I wanted to implement web hooks in python. Both at server end and client end. Is there any particular library for implementing web hooks? Or does django or twisted python handle this? A: You should probably mention that "web hooks" is a specific concept -- as expla...
Web hooks in Python: Any particular library?
I wanted to implement web hooks in python. Both at server end and client end. Is there any particular library for implementing web hooks? Or does django or twisted python handle this?
[ "You should probably mention that \"web hooks\" is a specific concept -- as explained at webhooks.org -- to avoid getting generic answers about the web, as I see you already have. It's hardly a popular or widespread concept, so the answerers' utter confusion is not surprising but easily predictable.\nOn your quest...
[ 7 ]
[]
[]
[ "python", "webhooks" ]
stackoverflow_0002935596_python_webhooks.txt
Q: Recalling import in module I'm still learning python and after playing around with pygame I noticed I'm re-importing things in modules I'm importing that I've already imported. import pygame For instance I have some classes in a separate file, but I must also import pygame into that file too for them to work. Doe...
Recalling import in module
I'm still learning python and after playing around with pygame I noticed I'm re-importing things in modules I'm importing that I've already imported. import pygame For instance I have some classes in a separate file, but I must also import pygame into that file too for them to work. Does it actually import the code tw...
[ "Subsequent imports pull the cached module reference from sys.modules. You need to import in order to add the module to the current namespace/scope.\n", "\nWhen Python imports a module, it first checks the module registry (sys.modules) to see if the module is already imported. If that’s the case, Python uses the ...
[ 2, 2, 0 ]
[]
[]
[ "feedback", "pygame", "python" ]
stackoverflow_0002936027_feedback_pygame_python.txt
Q: can a python script know that another instance of the same script is running... and then talk to it? I'd like to prevent multiple instances of the same long-running python command-line script from running at the same time, and I'd like the new instance to be able to send data to the original instance before the ne...
can a python script know that another instance of the same script is running... and then talk to it?
I'd like to prevent multiple instances of the same long-running python command-line script from running at the same time, and I'd like the new instance to be able to send data to the original instance before the new instance commits suicide. How can I do this in a cross-platform way? Specifically, I'd like to enable t...
[ "The Alex Martelli approach of setting up a communications channel is the appropriate one. I would use a multiprocessing.connection.Listener to create a listener, in your choice. Documentation at:\nhttp://docs.python.org/library/multiprocessing.html#multiprocessing-listeners-clients\nRather than using AF_INET (sock...
[ 11, 9, 1, 0 ]
[]
[]
[ "command_line", "interprocess", "ipc", "multithreading", "python" ]
stackoverflow_0002935836_command_line_interprocess_ipc_multithreading_python.txt
Q: Writing csv files with python with exact formatting parameters I'm having trouble with processing some csv data files for a project. Someone suggested using python/csv reader to help break down the files, which I've had some success with, but not in a way I can use. This code is a little different from what I w...
Writing csv files with python with exact formatting parameters
I'm having trouble with processing some csv data files for a project. Someone suggested using python/csv reader to help break down the files, which I've had some success with, but not in a way I can use. This code is a little different from what I was trying before. I am essentially attempting to create an array. ...
[ "If I had a cat for each time I saw a bio or psych or chem database in this state:\n\n\"each column contains 50 experiments,\n each with 4000 rows, for 200000 some\n rows total. What I want to do is take\n each column, and make it an individual\n csv file, with each experiment in its\n own column. So it would ...
[ 2, 0, 0 ]
[]
[]
[ "csv", "database_design", "python", "relational_database" ]
stackoverflow_0002933702_csv_database_design_python_relational_database.txt
Q: App Engine - Save response from an API in the data store as file (blob) I'm banging my head against the wall with this one: What I want to do is store a file that is returned from an API in the data store as a blob. Here is the code that I use on my local machine (which of course works due to an existing file syst...
App Engine - Save response from an API in the data store as file (blob)
I'm banging my head against the wall with this one: What I want to do is store a file that is returned from an API in the data store as a blob. Here is the code that I use on my local machine (which of course works due to an existing file system): client.convertHtml(html, open('html.pdf', 'wb')) Since I cannot write t...
[ "Found the error. Here is how it looks like right now (simplified).\n output = StringIO.StringIO()\n\n try:\n client.convertURI(\"example.com\", output)\n Report.pdf = db.Blob(output.getvalue())\n Report.put() \n except pdfcrowd.Error, why:\n logging.error('PDF creation failed ...
[ 2 ]
[]
[]
[ "api", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002935918_api_google_app_engine_google_cloud_datastore_python.txt
Q: openid along with oauth? In my application, users sign in/sign out via openid ( same as stackoverflow ). I would like to open up my application a bit via oauth to third party applications. How do I create my app which is openid-consumer to make it oauth-provider? Is there some standard library etc out there? I ...
openid along with oauth?
In my application, users sign in/sign out via openid ( same as stackoverflow ). I would like to open up my application a bit via oauth to third party applications. How do I create my app which is openid-consumer to make it oauth-provider? Is there some standard library etc out there? I am basically working in app en...
[ "OAuth python libraries are listed on this page:\nhttp://oauth.net/code/\n", "OAth and OpenID are had native support by app engine sinve 1.3.4. So you can implement transparent and solid authorization/authentication mechanism.\n" ]
[ 2, 2 ]
[]
[]
[ "google_app_engine", "oauth", "oauth_provider", "openid", "python" ]
stackoverflow_0002934326_google_app_engine_oauth_oauth_provider_openid_python.txt
Q: install python modules on shared web hosting I am using a shared hosting environment that will not give me access to the command line. Can I download the python module on my computer, compile it using python setup.py installand then simply upload a .py file to the web host? If yes, where does the install statement...
install python modules on shared web hosting
I am using a shared hosting environment that will not give me access to the command line. Can I download the python module on my computer, compile it using python setup.py installand then simply upload a .py file to the web host? If yes, where does the install statement place the compiled file?
[ "This is not directly an answer to your question but.. change your hosting provider! There are very cheap hostings with shell access and I swear that running Python site without access to shell is next to impossible.\nAlso, compiling Python library (I assume that it has some C bindings, otherwise there's not much t...
[ 2 ]
[]
[]
[ "compiler_construction", "python" ]
stackoverflow_0002936222_compiler_construction_python.txt
Q: Allocation algorithm help, using Python I've been working on this general allocation algorithm for students. The pseudocode for it (a Python implementation) is: for a student in a dictionary of students: for student preference in a set of preferences (ordered from 1 to 10): let temp_project be the fi...
Allocation algorithm help, using Python
I've been working on this general allocation algorithm for students. The pseudocode for it (a Python implementation) is: for a student in a dictionary of students: for student preference in a set of preferences (ordered from 1 to 10): let temp_project be the first preferred project check if temp_p...
[ "Seems like Assignment Problem might work for you, which can be solved using Hungarian Algorithm (as was noted in your other question: Student-Project allocation algorithms?). \nApparently there is a python implementation of the hungarian algorithm: http://pypi.python.org/pypi/hungarian/0.2\nI would recommend just ...
[ 3 ]
[]
[]
[ "algorithm", "allocation", "python" ]
stackoverflow_0002936675_algorithm_allocation_python.txt
Q: lightweight webserver to integrate on client end I need to create a python module that will be installed on end-user machines. One of the scripts in that module should be able to receive http POSTS (usually with some JSON formatted data in the body) and then pass on that data to an appropriate python script. I ca...
lightweight webserver to integrate on client end
I need to create a python module that will be installed on end-user machines. One of the scripts in that module should be able to receive http POSTS (usually with some JSON formatted data in the body) and then pass on that data to an appropriate python script. I can think of two ways to do this: Open a listening ser...
[ "batteries included\nPython 2\nPython 3 \n" ]
[ 4 ]
[]
[]
[ "python", "webserver" ]
stackoverflow_0002936792_python_webserver.txt