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: Django TypeError when passing arguments via URL Hello I am getting the following error in Django (latest version): TypeError at /post/1/ post() got an unexpected keyword argument 'post_id' This occurs when I press on a link on the home page to view the post it's self, I am trying to pass along the post's id (I am...
Django TypeError when passing arguments via URL
Hello I am getting the following error in Django (latest version): TypeError at /post/1/ post() got an unexpected keyword argument 'post_id' This occurs when I press on a link on the home page to view the post it's self, I am trying to pass along the post's id (I am using the default [hidden] primary key, not my own c...
[ "Change\ndef post(request, id):\n return HttpResponse(\"Hello this is post %\" %(post_id))\n\nto\ndef post(request, id):\n return HttpResponse(\"Hello this is post %s\" % id)\n\nAnd I suspect it will work a bit better!\n" ]
[ 2 ]
[]
[]
[ "django", "django_1.3", "python", "python_2.7" ]
stackoverflow_0006726385_django_django_1.3_python_python_2.7.txt
Q: Error when using ctypes module to acess a DLL written in C I have a DLL with one single function That gets five doubles and one int: __declspec(dllexport) struct res ITERATE(double z_r,double z_i,double c_r, double c_i, int iterations, double limit) It retuns a custom struct caled res which consists of a three-d...
Error when using ctypes module to acess a DLL written in C
I have a DLL with one single function That gets five doubles and one int: __declspec(dllexport) struct res ITERATE(double z_r,double z_i,double c_r, double c_i, int iterations, double limit) It retuns a custom struct caled res which consists of a three-double array: struct res { double arr[3]; }; To return the va...
[ "There is a problem with returning structs like that. Not all compilers return such structures the same way. I'd rather change the function declaration to this:\nvoid __declspec(dllexport) ITERATE(struct res* result, double z_r,double z_i, \n double c_r, double c_i, int iterations, double limit);\n\nThat way the...
[ 2 ]
[]
[]
[ "c", "ctypes", "dll", "python", "types" ]
stackoverflow_0006725870_c_ctypes_dll_python_types.txt
Q: What should an installation of Python 2.5 look like on Windows XP? I installed Python a while ago from the official python-2.5.4.msi, but I can't remember what else I might have done. On my disk, I have C:\Program Files\Python 2.5.4 and I also have C:\Python25. These directory contents look almost identical. The...
What should an installation of Python 2.5 look like on Windows XP?
I installed Python a while ago from the official python-2.5.4.msi, but I can't remember what else I might have done. On my disk, I have C:\Program Files\Python 2.5.4 and I also have C:\Python25. These directory contents look almost identical. The Program Files folder contains about 39 MB, the Python25 folder contains...
[ "It sounds like you might have installed python twice, each time using a different installation directory. You might want to consider uninstalling the two existing copies and installing a new copy.\nAlso...The following document should help you to understand how and where python installs and locates modules: Instal...
[ 4, 0 ]
[]
[]
[ "python", "windows_xp" ]
stackoverflow_0006726101_python_windows_xp.txt
Q: splitting and concatenating a string I was wondering if python had a built in function similar to string->list and list->string in scheme. So for example I would like to turn 'abc' into ['a','b','c'] and vice versa using a built in function. A: String to list: >>> list('abc') ['a', 'b', 'c'] List to string: >...
splitting and concatenating a string
I was wondering if python had a built in function similar to string->list and list->string in scheme. So for example I would like to turn 'abc' into ['a','b','c'] and vice versa using a built in function.
[ "String to list:\n>>> list('abc')\n['a', 'b', 'c']\n\nList to string:\n>>> ''.join(['a', 'b', 'c'])\n'abc'\n\n", "Split using a list comprehension [c for c in theString] .. and join them again using ''.join(theList). Other ways exist.\n" ]
[ 13, 0 ]
[]
[]
[ "append", "python", "split", "string" ]
stackoverflow_0006726636_append_python_split_string.txt
Q: How to resolve this error - ValueError: time data did not match format: I have a python code where I extract a date string (from a web page) which I then try to convert into a dateobject before using it. It has been working all along but since today I've been getting this error ValueError: time data did not match ...
How to resolve this error - ValueError: time data did not match format:
I have a python code where I extract a date string (from a web page) which I then try to convert into a dateobject before using it. It has been working all along but since today I've been getting this error ValueError: time data did not match format: data=Sun, 17 Jul 2011 23:51:19 fmt=%a, %d %b %Y %H:%M:%S This is m...
[ "Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) \n[GCC 4.4.3] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import datetime\n>>> myDate = \"Sun, 17 Jul 2011 23:51:19\"\n>>> datetime.datetime.strptime(myDate, '%a, %d %b %Y %H:%M:%S')\ndatetime.datetime(2011, 7, 17, ...
[ 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0006726865_datetime_python.txt
Q: Pygame, Python list index problem I'm attempting to create a Missile Command clone to challenge/expand my Python and Pygame skills and knowledge. Below is the code for the game so far (it's rudimentary, I'm a beginner): import math import pygame class Missile: def __init__(self, surface): self.surface = surfa...
Pygame, Python list index problem
I'm attempting to create a Missile Command clone to challenge/expand my Python and Pygame skills and knowledge. Below is the code for the game so far (it's rudimentary, I'm a beginner): import math import pygame class Missile: def __init__(self, surface): self.surface = surface self.missileList = [] self.c...
[ "You're modifying a list while iterating it, which is usually a mistake. In this case, the simplest way to make the code work is by iterating backwards:\nfor i in range(len(self.missileList)-1, -1, -1)\n\nThat works because you only ever delete the current item in the loop - when you iterate backwards, deleting th...
[ 4, 3, 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0006727222_pygame_python.txt
Q: How to display dictionary by their values, descending? I have a dictionary as follows: {'aapl': 4.0, 'abandon': 4.0, 'absenc': 3.0, 'accept': 1.0, 'access': 3.0, 'accessori': 4.0, 'accord': 3.0, 'achiev': 1.0, 'acquir': 1.5, 'acquisit': 2.3333333333333335, 'across': 5.0, 'activ': 2.0, 'ad': 2.269230769...
How to display dictionary by their values, descending?
I have a dictionary as follows: {'aapl': 4.0, 'abandon': 4.0, 'absenc': 3.0, 'accept': 1.0, 'access': 3.0, 'accessori': 4.0, 'accord': 3.0, 'achiev': 1.0, 'acquir': 1.5, 'acquisit': 2.3333333333333335, 'across': 5.0, 'activ': 2.0, 'ad': 2.2692307692307692, 'add': 2.5, 'addit': 2.8333333333333335, } How d...
[ ">>> D={'aapl': 4.0,\n... 'abandon': 4.0,\n... 'absenc': 3.0,\n... 'accept': 1.0,\n... 'access': 3.0,\n... 'accessori': 4.0,\n... 'accord': 3.0,\n... 'achiev': 1.0,\n... 'acquir': 1.5,\n... 'acquisit': 2.3333333333333335,\n... 'across': 5.0,\n... 'activ': 2.0,\n... 'ad': 2.2692307692307692,\n... 'add':...
[ 5, 1, 0, 0 ]
[]
[]
[ "dictionary", "python", "sorting", "tuples" ]
stackoverflow_0006727330_dictionary_python_sorting_tuples.txt
Q: Python: creating dictionary from a bunch of "key: value" strings? Suppose I have loaded this into a list: info = ['apple: 1', 'orange: 2', 'grape: 3'] How can I turn that into something like info = {line[0]: line[1] for line.split(': ') in info} So that I actually have a dict? A: You're very close! >>> info = ...
Python: creating dictionary from a bunch of "key: value" strings?
Suppose I have loaded this into a list: info = ['apple: 1', 'orange: 2', 'grape: 3'] How can I turn that into something like info = {line[0]: line[1] for line.split(': ') in info} So that I actually have a dict?
[ "You're very close!\n>>> info = ['apple: 1', 'orange: 2', 'grape: 3']\n>>> info = dict(line.split(': ') for line in info)\n>>> info\n{'orange': '2', 'grape': '3', 'apple': '1'}\n\nYou could do it the way you tried to in Python 2.7+, but you'd have to split the lines separately, so using dict is better. \nHere's wha...
[ 7, 2 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0006727394_dictionary_list_python.txt
Q: itunes persistent id - music library xml version and iTunes hex version I'd like to read a hex PersistentID string from ItunesMusicLibrary.xml, get two ints representing the high and low 32 bits, then use those two ints in an iTunes script. Unfortunately, the PersistentID string in ItunesMusicLibrary.xml does not ...
itunes persistent id - music library xml version and iTunes hex version
I'd like to read a hex PersistentID string from ItunesMusicLibrary.xml, get two ints representing the high and low 32 bits, then use those two ints in an iTunes script. Unfortunately, the PersistentID string in ItunesMusicLibrary.xml does not seem to be the same PersistentID that's in iTunes, as accessible through vari...
[ "You're interpreting the numbers as unsigned but iTunes is using signed. 2645110187 is the same as -1649857109. You might want something like this:\nstruct.unpack('!i', binascii.a2b_hex('0F1610959DA92DAB'[8:]))[0]\n\n...or get both values in one go:\nstruct.unpack('!ii', binascii.a2b_hex('0F1610959DA92DAB'))\n\n....
[ 1, 0 ]
[]
[]
[ "hex", "itunes", "itunes_sdk", "python" ]
stackoverflow_0006727041_hex_itunes_itunes_sdk_python.txt
Q: Optimising model of social network evolution I am writing a piece of code which models the evolution of a social network. The idea is that each person is assigned to a node and relationships between people (edges on the network) are given a weight of +1 or -1 depending on whether the relationship is friendly or un...
Optimising model of social network evolution
I am writing a piece of code which models the evolution of a social network. The idea is that each person is assigned to a node and relationships between people (edges on the network) are given a weight of +1 or -1 depending on whether the relationship is friendly or unfriendly. Using this simple model you can say tha...
[ "The following suggestions won't boost your performance that much because they are not on the algorithmic level, i.e. not very specific to your problem. However, they are generic suggestions for slight performance improvements:\nUnless you are using Python 3, change\nfor i in range(800000):\n\nto\nfor i in xrange(8...
[ 5, 4, 2, 1 ]
[]
[]
[ "networkx", "optimization", "python" ]
stackoverflow_0006725771_networkx_optimization_python.txt
Q: Track changes of atributes in instance. Python I want to implement function which takes as argument any object and trackes changes of value for specific attribute. Than saves old value of attribute in old_name attribute. For example: class MyObject(object): attr_one = None attr_two = 1 Lets name my magi...
Track changes of atributes in instance. Python
I want to implement function which takes as argument any object and trackes changes of value for specific attribute. Than saves old value of attribute in old_name attribute. For example: class MyObject(object): attr_one = None attr_two = 1 Lets name my magic function magic_function() Sot than i can do like t...
[ "This is a start:\nclass MagicWrapper(object):\n def __init__(self, wrapped):\n self._wrapped = wrapped\n\n def __getattr__(self, attr):\n return getattr(self._wrapped, attr)\n\n def __setattr__(self, attr, val):\n if attr == '_wrapped':\n super(MagicWrapper, self).__setattr...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006727491_python.txt
Q: Time based rotation I'm trying to figure out the best way of doing the following: I have a list of values: L I'd like to pick a subset of this list, of size N, and get a different subset (if the list has enough members) every X minutes. I'd like the values to be picked sequentially, or randomly, as long as all the...
Time based rotation
I'm trying to figure out the best way of doing the following: I have a list of values: L I'd like to pick a subset of this list, of size N, and get a different subset (if the list has enough members) every X minutes. I'd like the values to be picked sequentially, or randomly, as long as all the values get used. For e...
[ "You can use the itertools standard module to help:\nimport itertools\nimport random\nimport time\n\na = [\"google.com\", \"yahoo.com\", \"gmail.com\"]\ncombs = list(itertools.combinations(a, 2))\nrandom.shuffle(combs)\nfor c in combs:\n print(c)\n time.sleep(3600)\n\n\nEDIT: Based on your clarification in th...
[ 1 ]
[]
[]
[ "algorithm", "c++", "pseudocode", "python", "random" ]
stackoverflow_0006727616_algorithm_c++_pseudocode_python_random.txt
Q: Python get N elements from a list at a time using lambda Imagine I have a list like this: a = [1,2,3,4,5,6] Using a lambda function, I would like to return two elements at a time, so the result would be: res = [[1,2], [2,3], [3,4], [4,5], [5,6]] Any suggestions? A: >>> zip(a, a[1:]) [(1, 2), (2, 3), (3, 4), (4...
Python get N elements from a list at a time using lambda
Imagine I have a list like this: a = [1,2,3,4,5,6] Using a lambda function, I would like to return two elements at a time, so the result would be: res = [[1,2], [2,3], [3,4], [4,5], [5,6]] Any suggestions?
[ ">>> zip(a, a[1:])\n[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]\n\nFor arbitrary n:\n>>> n = 3\n>>> zip(*(a[i:] for i in range(n)))\n[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)]\n\n", ">>> import itertools\n>>> itertools.izip(a, itertools.islice(a,1,None))\n\nThis avoids creating a copy of your original list, which ...
[ 8, 4, 2, 0, 0 ]
[]
[]
[ "lambda", "list", "python" ]
stackoverflow_0006727623_lambda_list_python.txt
Q: VLC python binding issue => NameError: name 'u' is not defined I add the vlc.py to my vlc install directory and then try running a basic example: from vlc import * i=vlc.Instance('--no-audio', '--fullscreen') i.audio_get_volume() p=i.media_player_new() m=i.media_new('file:///tmp/foo.avi') m.get_mrl(...
VLC python binding issue => NameError: name 'u' is not defined
I add the vlc.py to my vlc install directory and then try running a basic example: from vlc import * i=vlc.Instance('--no-audio', '--fullscreen') i.audio_get_volume() p=i.media_player_new() m=i.media_new('file:///tmp/foo.avi') m.get_mrl() p.set_media(m) p.play() I get this error: Traceback (most rec...
[ "They herped the derp. There is no u. Change the line to del p and log a bug.\n" ]
[ 2 ]
[]
[]
[ "python", "vlc" ]
stackoverflow_0006727083_python_vlc.txt
Q: How to create unique key names in google app engine I'm having trouble figuring out how to create unique key names for my online election app. Here is a typical set of relevant entities: 1 Election 5 Candidates 100,000 Voters up to 100,000 Votes I need a unique key name for each Voter entity for the reasons exp...
How to create unique key names in google app engine
I'm having trouble figuring out how to create unique key names for my online election app. Here is a typical set of relevant entities: 1 Election 5 Candidates 100,000 Voters up to 100,000 Votes I need a unique key name for each Voter entity for the reasons expressed here. An email address would be unique for a vote...
[ "Double-check your assumptions. As it is, there is a situation that could hamper the ID's uniqueness:\nWhat if two voters use the same e-mail address? I know that my parents only have a single one between them. As it is, your ID would clash.\nThere are bunches of way to minimize collisions. If worst comes to worst,...
[ 3, 0 ]
[]
[]
[ "entity_group_transactions", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0006727712_entity_group_transactions_google_app_engine_google_cloud_datastore_python.txt
Q: ImportError when haystack is added to urls? When I add the following to my site.urls.py file #haystack search url(r'^search/', include('haystack.urls')), I get this error Caught ImportError while rendering: No module named urls here a href="{% url django.contrib.auth.views.logout %}">Logout</a> or at the first...
ImportError when haystack is added to urls?
When I add the following to my site.urls.py file #haystack search url(r'^search/', include('haystack.urls')), I get this error Caught ImportError while rendering: No module named urls here a href="{% url django.contrib.auth.views.logout %}">Logout</a> or at the first location of the {% url %} tag, when I comment ou...
[ "Ignore the template code and look at the traceback. I've had a few problems where it shows me template code but the error was actually being caused by python code (that you can find in the traceback).\nEnsure that haystack is a valid package in your Python path:\nComment out the one line that is problematic and di...
[ 1 ]
[]
[]
[ "django", "django_haystack", "python", "tags", "templates" ]
stackoverflow_0006727698_django_django_haystack_python_tags_templates.txt
Q: How do I find the MD5 hash of an ISO file using Python? I am writing a simple tool that allows me to quickly check MD5 hash values of downloaded ISO files. Here is my algorithm: import sys import hashlib def main(): filename = sys.argv[1] # Takes the ISO 'file' as an argument in the command line testFile ...
How do I find the MD5 hash of an ISO file using Python?
I am writing a simple tool that allows me to quickly check MD5 hash values of downloaded ISO files. Here is my algorithm: import sys import hashlib def main(): filename = sys.argv[1] # Takes the ISO 'file' as an argument in the command line testFile = open(filename, "r") # Opens and reads the ISO 'file' #...
[ "The object created by hashlib.md5 doesn't take a file object. You need to feed it data a piece at a time, and then request the hash digest.\nimport hashlib\n\ntestFile = open(filename, \"rb\")\nhash = hashlib.md5()\n\nwhile True:\n piece = testFile.read(1024)\n\n if piece:\n hash.update(piece)\n el...
[ 8, 3 ]
[]
[]
[ "hashlib", "iso", "md5", "python" ]
stackoverflow_0006727926_hashlib_iso_md5_python.txt
Q: Django Boolean is "True" after migration and not selected in ModelForm I am trying to add a row to my Model and have that option editable in a ModelForm in Django. I want the field to be True by default. Here's what I'm adding to my model: field_name = models.BooleanField(default=1) Then, I use South to do a mig...
Django Boolean is "True" after migration and not selected in ModelForm
I am trying to add a row to my Model and have that option editable in a ModelForm in Django. I want the field to be True by default. Here's what I'm adding to my model: field_name = models.BooleanField(default=1) Then, I use South to do a migration. Everything works perfectly, except instead of my database full of "1...
[ "Have you tried this.\nfield_name = models.BooleanField(default=True)\n\nWhat database are you using, does your database support Boolean fields? Or does it use a smallint field with 0 and 1 for false and true?\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "django_south", "python" ]
stackoverflow_0006727952_django_django_models_django_south_python.txt
Q: Notepad++ Tab Settings See Convert tabs to spaces in Notepad++ I have started on a personal quest to learn python and after following a Google lecture online the instructor advocated changing your tabs to spaces. I have browsed around in notepad++ and gone to the language settings and checked the change tabs to ...
Notepad++ Tab Settings
See Convert tabs to spaces in Notepad++ I have started on a personal quest to learn python and after following a Google lecture online the instructor advocated changing your tabs to spaces. I have browsed around in notepad++ and gone to the language settings and checked the change tabs to spaces text box but it is no...
[ "There are two places in the language settings that might be controlling tabs and spaces in Python. Check that the \"default\" language is set to spaces, and then check that \"Python\" is set to \"Use default value. It should look like this:\n\nPersonally, I prefer using tabs. I find it's easier to make sure everyt...
[ 34, 1 ]
[]
[]
[ "editor", "notepad++", "python", "spaces", "tabbing" ]
stackoverflow_0006728313_editor_notepad++_python_spaces_tabbing.txt
Q: How to Parse HTML with Non-ASCII Characters using BeautifulSoup? I keep getting the following error when trying to parse some html using BeautifulSoup: UnicodeDecodeError: 'ascii' codec can't decode byte 0xae in position 0: ordinal not in range(128) I've tried decoding the html using the solution to the questions...
How to Parse HTML with Non-ASCII Characters using BeautifulSoup?
I keep getting the following error when trying to parse some html using BeautifulSoup: UnicodeDecodeError: 'ascii' codec can't decode byte 0xae in position 0: ordinal not in range(128) I've tried decoding the html using the solution to the questions below, but keep getting the same error. I've tried all the solutions ...
[ "You say in a comment: \"\"\"I just looked up the content-type of the html I'm trying to parse to see if it was something I hadn't tried (earlier I just assumed it was UTF-8) but sure enough it was UTF-8 so another dead end.\"\"\"\nSigh. This is exactly why I have been trying to get you to divulge the HTML that you...
[ 2, 2 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0006725823_beautifulsoup_python.txt
Q: Explanation for argparse python modul behaviour: Where do the capital placeholders come from? I am trying to write a command line interface (for the first time) and after reading up about argparse, optparse and getopt I chose argparse because of several recommendations here on SO and elswhere in the net. Adapting ...
Explanation for argparse python modul behaviour: Where do the capital placeholders come from?
I am trying to write a command line interface (for the first time) and after reading up about argparse, optparse and getopt I chose argparse because of several recommendations here on SO and elswhere in the net. Adapting a little of the advice of Mr. van Rossum I hooked up my first command line interface like this: def...
[ "The capital letter items are just value placeholders; they're taken from the destination of the option. You can specify alternative placeholders via the metavar= param of add_argument:\nhttp://docs.python.org/dev/library/argparse.html#metavar\n", "Here are a couple basic argparse resources I dug up:\nSome slides...
[ 7, 2 ]
[]
[]
[ "argparse", "python" ]
stackoverflow_0006728019_argparse_python.txt
Q: Live audio feed in HTML 5 I am trying to make way to broadcast live audio feeds in HTML 5 compatible means. I don't want many advance features and all. But however I am looking for everything to be Open source. Can any one shed light into this. I am comfortable with python. Is it possible with python to get the au...
Live audio feed in HTML 5
I am trying to make way to broadcast live audio feeds in HTML 5 compatible means. I don't want many advance features and all. But however I am looking for everything to be Open source. Can any one shed light into this. I am comfortable with python. Is it possible with python to get the audio from mic and broadcast it i...
[ "Use SHOUTcast/Icecast and one of the many encoders for those to encode and stream.\nWhat you use on the player side is up to you, but you can do this with HTML5 or Flash. It's just MP3 over HTTP.\n" ]
[ 1 ]
[]
[]
[ "broadcasting", "html5_audio", "live_streaming", "python", "vlc" ]
stackoverflow_0006728473_broadcasting_html5_audio_live_streaming_python_vlc.txt
Q: problems running programs using the command terminal So I'm determined to learn programming and I decided to start with Python and ChucK (audio language) but I'm having issues running things in the cmd terminal. I get Python to open in the terminal but when I try to run a program, I always get a syntax error indic...
problems running programs using the command terminal
So I'm determined to learn programming and I decided to start with Python and ChucK (audio language) but I'm having issues running things in the cmd terminal. I get Python to open in the terminal but when I try to run a program, I always get a syntax error indicating something wrong with the filename. I also encounter ...
[ "First of all, your link should be http://imagebin.org/163567\nYou're managing to run the Python interpreter, then trying to again run Python from within that interpreter. Instead of what you've done, try just C:\\Python27\\python democodes.py at the command line from whatever directory democodes.py is in.\nAlso, c...
[ 1 ]
[]
[]
[ "command_line", "python", "syntax_error", "windows" ]
stackoverflow_0006728636_command_line_python_syntax_error_windows.txt
Q: How can I get Pika to retry connecting to RabbitMQ if it fails the first time? I'm trying to get my program, which uses Pika, to continually retry connecting to RabbitMQ on failure. From what I've seen of the Pika docs, there's a SimpleReconnectionStrategy class that can be used to accompish this but it doesn't se...
How can I get Pika to retry connecting to RabbitMQ if it fails the first time?
I'm trying to get my program, which uses Pika, to continually retry connecting to RabbitMQ on failure. From what I've seen of the Pika docs, there's a SimpleReconnectionStrategy class that can be used to accompish this but it doesn't seem to be working very well. strategy = pika.SimpleReconnectionStrategy() para...
[ "import socket\n\n...\n\nwhile True:\n connectSucceeded = False\n try:\n self.channel = self.connection.channel()\n connectSucceeded = True\n except socket.error:\n pass\n if connectSucceeded:\n break\n\nSomething like the above is usually used. You could also add time.sle...
[ 3 ]
[]
[]
[ "amqp", "python", "rabbitmq" ]
stackoverflow_0005616408_amqp_python_rabbitmq.txt
Q: Getting snapshot of process before it terminates I'd like to be execute a command-line and get a snapshot of its /proc tree. The point is to find out as much as possible about the process. One potential problem is that the process might terminate before I finish copying stuff. Any suggestions how to get around thi...
Getting snapshot of process before it terminates
I'd like to be execute a command-line and get a snapshot of its /proc tree. The point is to find out as much as possible about the process. One potential problem is that the process might terminate before I finish copying stuff. Any suggestions how to get around this? Here's what I have so far #!/usr/bin/python # # run...
[ "\nEvery symbolic link is also a file.\nfor f in os.listdir(path): do_something_with(f) is wrong unless you are your cwd is path.\n\nAlso, examine this snippet's output:\nimport os\n\nbase = \"/proc/%d\" % os.getpid()\nfor f in os.listdir(base):\n f = os.path.join(base, f)\n print \"%-40s %5s %5s %5s\" % (f, ...
[ 2 ]
[]
[]
[ "python", "ubuntu", "unix" ]
stackoverflow_0006728611_python_ubuntu_unix.txt
Q: Converting Relational databases to flat and vice-versa I'd like to write a script to convert from a relational database to a flat one and vice-versa. The database's rows mostly contain data from text input, but there are a few dropdown lists from the form that enter the primary IDs of a row from another table. Cur...
Converting Relational databases to flat and vice-versa
I'd like to write a script to convert from a relational database to a flat one and vice-versa. The database's rows mostly contain data from text input, but there are a few dropdown lists from the form that enter the primary IDs of a row from another table. Currently I have database rows that would look like say: (1, 4,...
[ "Make SQL-query for that gives needed data\nselect name1, name2, number1, number2\nfrom table1\njoin table2 on table1.id = table2.t1_id\n\nand using sqlalchemy will create and run your script\nfrom sqlalchemy import create_engine\n\nengine = create_engine('user_pass_address_port')\ndbc = engine.connect()\ndbr = dbc...
[ 0 ]
[]
[]
[ "non_relational_database", "python", "relational_database" ]
stackoverflow_0006728532_non_relational_database_python_relational_database.txt
Q: Why is it that you don't have to declare (object) for a class that only has __init__ in python? Thanks for helping a n00b Example of what I am talking about: class Complex: def __init__(self,x,y): self.x = x self.y = y Why is it that when you declare the class, you don't have to add (object) t...
Why is it that you don't have to declare (object) for a class that only has __init__ in python?
Thanks for helping a n00b Example of what I am talking about: class Complex: def __init__(self,x,y): self.x = x self.y = y Why is it that when you declare the class, you don't have to add (object) to it, class Complex(object):
[ "In Python 2.x, this makes your class old-style, with a different inheritance semantics. Since you don't use inheritance (and the method resolution order is the same in simple cases), it makes no difference in practice. If you're programming in Python 2.x, you should add (object) to profit from the advantages of ne...
[ 3, 3, 0 ]
[]
[]
[ "class", "object", "oop", "python" ]
stackoverflow_0006729141_class_object_oop_python.txt
Q: Ruby equivalent for python array I need a ruby equivalent for the following python code import array my_array = array.array('B', [0x00, 0x04, 0xcc, 0x50]).tostring() UPDATE: I am trying to write 4 bytes to the serial port using ruby-serialport gem. I was able to make it work in python by writing the above byte ar...
Ruby equivalent for python array
I need a ruby equivalent for the following python code import array my_array = array.array('B', [0x00, 0x04, 0xcc, 0x50]).tostring() UPDATE: I am trying to write 4 bytes to the serial port using ruby-serialport gem. I was able to make it work in python by writing the above byte array to the serial port. Now I am tryin...
[ "Are you looking for Array#pack?\nbyte_string = [0x00, 0x04, 0xCC, 0x50].pack('C*')\n\nFrom the fine manual:\n\narr.pack ( aTemplateString ) → aBinaryString\n Packs the contents of arr into a binary sequence according to the directives in aTemplateString.\n\nThe C template is for unsigned eight bit integers (i.e. ...
[ 6, 1, 1 ]
[]
[]
[ "bytearray", "python", "ruby", "ruby_on_rails" ]
stackoverflow_0006729329_bytearray_python_ruby_ruby_on_rails.txt
Q: text replace in python I have had written text file in which I have statements like these : WriteByte(0x6000, 0x28); // Register Value ... WriteByte(0x6002, 0x02); // WriteByte(0x6004, 0x08); // I have to replace 0x28 with a user given value as an input This means I have replace 0x28 w...
text replace in python
I have had written text file in which I have statements like these : WriteByte(0x6000, 0x28); // Register Value ... WriteByte(0x6002, 0x02); // WriteByte(0x6004, 0x08); // I have to replace 0x28 with a user given value as an input This means I have replace 0x28 with usr_value which may be 0...
[ "From the discussion below, if you want to find all the second arguments to WriteBytes and prompt for replacing, you can do something like this:\n\nparse the file to find all the 2nd arguments to WriteBytes, using a regular expression, and store them in a set (which will handle duplicates for you)\nfor all the valu...
[ 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0006729308_python_string.txt
Q: Funny behavior using urlretrieve on a dict in Python I wrote some code to download some files from URLs, which I put in a dict, however, when I run the script, everything runs fine, except in the end when it goes to download the files, it creates creates one file with one of the names, then I see that file get lar...
Funny behavior using urlretrieve on a dict in Python
I wrote some code to download some files from URLs, which I put in a dict, however, when I run the script, everything runs fine, except in the end when it goes to download the files, it creates creates one file with one of the names, then I see that file get larger and larger, and then it gets smaller again. This file ...
[ "What you want instead of your for loops is just:\nfor name, url in zip(names, urls):\n urllib.request.urlretrieve(url, name)\n\nYou don't want nested loops: you're getting all combinations of URL with name instead of just the matching pairs of URL and name. zip(names, urls) takes the first item of each list, th...
[ 2 ]
[]
[]
[ "dictionary", "python", "python_3.x", "urllib" ]
stackoverflow_0006729536_dictionary_python_python_3.x_urllib.txt
Q: Python CGI Script (using XML & mindom) does not print FOR loop counter Trying to print the results of a Yahoo search using an API, the For loop counter will not print its incremented value. The XML is parsed and printed, but the counter prints '1' over and over. The same code works fine for a Bing API. for coun...
Python CGI Script (using XML & mindom) does not print FOR loop counter
Trying to print the results of a Yahoo search using an API, the For loop counter will not print its incremented value. The XML is parsed and printed, but the counter prints '1' over and over. The same code works fine for a Bing API. for counter1 in range(50): try: for Result in YahooSearchResultsXML.getE...
[ "As it's written above, the printing is in the for Result in.. loop. If you have multipe results, you'll get multiple lines with the same content.\nAlso, the try shouldn't be indented? (this was fixed)\nEdit: from the info we gathered, you need to increment that counter in the inner loop. The way you have written i...
[ 0, 0 ]
[]
[]
[ "minidom", "python", "xml" ]
stackoverflow_0006729814_minidom_python_xml.txt
Q: how close a.lower() in python to a->lower() in C++ Since variables point to objects in python, I guess, and it is a reference. Suppose a is a string and can I fully interpret a.lower() in python as a replacement for C/C++ a->lower() on a pointer to char*? I know these are different languages, but trying to relate ...
how close a.lower() in python to a->lower() in C++
Since variables point to objects in python, I guess, and it is a reference. Suppose a is a string and can I fully interpret a.lower() in python as a replacement for C/C++ a->lower() on a pointer to char*? I know these are different languages, but trying to relate similar concepts so that it is easier to understand. Edi...
[ "char* does not have a lower() method. Your comparison is invalid.\nCalling str.lower() is like calling tolower(3) on each character in turn and returning the new string.\n", "you say:\n\nSuppose I have a class that implements a string that has a lower\n method.\n\nbut then it gets very difficult to guess what t...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0006729824_python.txt
Q: Why is it not ok to catch Exception instead of the more specific URLError? try: response = urllib2.urlopen(req) except Exception, e: logger.exception(e) Is there any convincing argument against catching Exception instead of urllib2.URLError in this code snippet ? A: There are could be unexpected reason...
Why is it not ok to catch Exception instead of the more specific URLError?
try: response = urllib2.urlopen(req) except Exception, e: logger.exception(e) Is there any convincing argument against catching Exception instead of urllib2.URLError in this code snippet ?
[ "There are could be unexpected reasons that an exception could be raised here that you don't or can't know about. You write your program as though the only exception here could be urllib2.URLError, and then one day something in the internals of urllib2 generates an exception that isn't one of those. It could be a ...
[ 7, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006729666_python.txt
Q: Python Internationalization (gettext) I'm experimenting with internationalization in Python. I started with a simple "Hello, World" script and I now grasp the basics of using gettext. I read in the documentation that concatenating strings together like so: msg = _('Start of message') msg += _(' end of message') i...
Python Internationalization (gettext)
I'm experimenting with internationalization in Python. I started with a simple "Hello, World" script and I now grasp the basics of using gettext. I read in the documentation that concatenating strings together like so: msg = _('Start of message') msg += _(' end of message') is not recommended as it splits the strings ...
[ "To be honest I know very little about Python and I only used Gettext with C++.\nIt seems that you are using placeholders and string formatting for externalized string. This is definitely good. If you did it correctly (as it seems to some extent, more on this later), the translators would be able to bring more than...
[ 1, 0 ]
[]
[]
[ "internationalization", "python" ]
stackoverflow_0006727167_internationalization_python.txt
Q: Find pattern in xml string I have following xml tags in my xml file as follows ''' <pd:link scheme="http://www.w3.org/1999/xhtml" target="www.altruvest.org <pd:unicode ch="2014"/> or <pd:unicode ch="2014"/> www.Boardmatch.org">"www.altruvest.org <pd:unicode ch="2014"/> or <pd:unicode ch="2014"/> www.Boardmatch....
Find pattern in xml string
I have following xml tags in my xml file as follows ''' <pd:link scheme="http://www.w3.org/1999/xhtml" target="www.altruvest.org <pd:unicode ch="2014"/> or <pd:unicode ch="2014"/> www.Boardmatch.org">"www.altruvest.org <pd:unicode ch="2014"/> or <pd:unicode ch="2014"/> www.Boardmatch.org</pd:link>) ''' in above tag ...
[ "Edited answer:\n>>> s = r'\"<pd:link scheme=\"http://www.w3.org/1999/xhtml\" target=\"www.altruvest.org <pd:unicode ch=\"2014\"/> or <pd:unicode ch=\"2014\"/> www.Boardmatch.org\">www.altruvest.org <pd:unicode ch=\"2014\"/> or <pd:unicode ch=\"2014\"/> www.Boardmatch.org</pd:link>\"'\n>>> import re\n>>> r = re.sea...
[ 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006730040_python_regex.txt
Q: Submitting search form using urllib2 (python) I am trying to search for courses in my school's system and logging in works with my login info import urllib, urllib2, cookielib,re username = 'user' password = 'pass' # Login main site cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProce...
Submitting search form using urllib2 (python)
I am trying to search for courses in my school's system and logging in works with my login info import urllib, urllib2, cookielib,re username = 'user' password = 'pass' # Login main site cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) login_data = urllib.urlencode({'userid' :...
[ "The second argument to urllib2.Request() is the POST data, not the GET query string. You can send the query string by directly attaching it to the URL:\nrequest = urllib2.Request('https://psns.cc.stonybrook.edu/psc/he90prods/EMPLOYEE/HRMS/c/SA_LEARNER_SERVICES.CLASS_SEARCH.GBL?' + urllib.urlencode(search_data))\n\...
[ 0 ]
[]
[]
[ "cookielib", "python", "urllib2" ]
stackoverflow_0006729206_cookielib_python_urllib2.txt
Q: Which of these is the most efficient? Question Which of these is the quickest? I'm using lighttpd's mod_fastcgi, Python 2.7 and flup.server.fcgi.WSGIServer. Should I yield strings directly in some_output_function, then return from app? def app(env, start): start('200 OK', [('Content-Type', 'text/html')]) r...
Which of these is the most efficient?
Question Which of these is the quickest? I'm using lighttpd's mod_fastcgi, Python 2.7 and flup.server.fcgi.WSGIServer. Should I yield strings directly in some_output_function, then return from app? def app(env, start): start('200 OK', [('Content-Type', 'text/html')]) return some_output_function() def some_outp...
[ "As a general rule generators are more efficient than lists when dealing with a lot of data. A list will be less overhead if the number of elements is small (e.g. in your example, only three elements).\nWhichever method you choose, it will most likely be dwarfed by the time spent fetching data from the cache or the...
[ 1, 1 ]
[]
[]
[ "fastcgi", "lighttpd", "mod_wsgi", "python", "wsgi" ]
stackoverflow_0006728573_fastcgi_lighttpd_mod_wsgi_python_wsgi.txt
Q: Many-to-many intersection in sqlalchemy I have a Character class with a .tags attribute; the .tags attribute is a list of Tag objects. in a many-to-many relationship. I'm trying to write a query that will find all pairs of characters that don't have the same name that have at least one tag in common; how would I g...
Many-to-many intersection in sqlalchemy
I have a Character class with a .tags attribute; the .tags attribute is a list of Tag objects. in a many-to-many relationship. I'm trying to write a query that will find all pairs of characters that don't have the same name that have at least one tag in common; how would I go about doing this?
[ "You go about this as following:\n\nthink of an SQL query which will give you the desired result\ncreate a corresponding SA query\n\nThe SQL query (with WITH clause on SQL Server for the sake of test data) is as below (obviously your table and column names might be different):\nWITH t_character (id, name)\nAS ( ...
[ 2 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0006721288_python_sqlalchemy.txt
Q: How to share db connection like session across different users? We're using Soaplib - Soap Server with apache/mod_wsgi and sqlalchemy as ORM for mysql connection. We tried to use global dict to store the db session handled by sqlalchemy - makesession connection. But when we move our code to the production environm...
How to share db connection like session across different users?
We're using Soaplib - Soap Server with apache/mod_wsgi and sqlalchemy as ORM for mysql connection. We tried to use global dict to store the db session handled by sqlalchemy - makesession connection. But when we move our code to the production environment using mod_wsgi it won't work, as it creates different processes f...
[ "A new process is not created for each request. What you were likely doing is that you were running in embedded mode with Apache prefork MPM. Apache will create many processes to handle requests and your requests are likely being handled by the different processes in turn. Eventually the requests will come back and...
[ 0 ]
[]
[]
[ "apache", "mod_wsgi", "python", "sqlalchemy" ]
stackoverflow_0006729639_apache_mod_wsgi_python_sqlalchemy.txt
Q: This python code in C/C++ I have this code: #!/usr/bin/python import urllib print 'Insert page to download:' page = raw_input() filehandle = urllib.urlopen(page) myFile = open('file.html','w') for lines in filehandle.readlines(): myFile.write(lines ) myFile.close() filehandle.close() This basically just...
This python code in C/C++
I have this code: #!/usr/bin/python import urllib print 'Insert page to download:' page = raw_input() filehandle = urllib.urlopen(page) myFile = open('file.html','w') for lines in filehandle.readlines(): myFile.write(lines ) myFile.close() filehandle.close() This basically just downloads the inputed webpage ...
[ "Try the libcurl library, which provides URL download functions for C (and many other languages including C++).\nIf you're writing code for Windows, you can also use the Windows Internet library.\n", "The quick and dirty answer is to use that python code and shell out from your C++ code, or embed python and run t...
[ 5, 1, 1 ]
[]
[]
[ "c", "c++", "python" ]
stackoverflow_0006726499_c_c++_python.txt
Q: Python datetime format mask I have the following datetime format to parse into datetime object in python: Wed, 13 Jul 2011 09:11:14 +0200 What format mask should I use for +0200 part? It means +2 hours. The thing is that I can't even find any man page on the Internet about datetime format masks. A: like this? I...
Python datetime format mask
I have the following datetime format to parse into datetime object in python: Wed, 13 Jul 2011 09:11:14 +0200 What format mask should I use for +0200 part? It means +2 hours. The thing is that I can't even find any man page on the Internet about datetime format masks.
[ "like this?\nIn [10]: now = datetime.datetime(*time.strptime(\"Wed, 13 Jul 2011 09:11:14 +0200\", \"%a, %d %b %Y %H:%M:%S +0200\")[0:5])\n\nIn [11]: now\nOut[11]: datetime.datetime(2011, 7, 13, 9, 11)\n\nSee doc.python.org\nFor everything related to time and dates, I turn to pleac\n", "It really depends fro what ...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006727208_python.txt
Q: Using multiple Python versions: Can IDLE be configured to see *.py3 / *.py2 I'm new to Python, and was curious about this idea. Since there are differences between Python 2.x and 3.x, could IDLE be modified (in a configuration or settings file) to recognize and compile files with a .py3 or .py2 extension? Also, is...
Using multiple Python versions: Can IDLE be configured to see *.py3 / *.py2
I'm new to Python, and was curious about this idea. Since there are differences between Python 2.x and 3.x, could IDLE be modified (in a configuration or settings file) to recognize and compile files with a .py3 or .py2 extension? Also, is this something that would difficult to implement, or better yet, is this worth t...
[ "Don't know about Idle, but the preferred way to have your files determine the python version to use would be not to have different file extensions, but to use a \"shebang\" line, like #! /usr/bin/python3. To make this work on windows as well as linux, there is the new Python Launcher for Windows (described in pep ...
[ 3, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0006729165_python_python_3.x.txt
Q: How can I run Django application tests together with other tests? I’m working on a project composed of two Python packages. foo contains some common business logic and foo.webapp contains a Django app providing an API over it. Module foo.tests contains unittest cases for the common logic, and foo.webapp.tests for ...
How can I run Django application tests together with other tests?
I’m working on a project composed of two Python packages. foo contains some common business logic and foo.webapp contains a Django app providing an API over it. Module foo.tests contains unittest cases for the common logic, and foo.webapp.tests for the API. Plus there’s a Django project for running the API. So it looks...
[ "I wrote a custom Django test runner along the lines of django-alltestsrunner (but instead of discovering the tests automatically, I specify a list of modules in settings).\nNow, when I do django_project/manage.py test, it runs all the tests. When I do django_project/manage.py test foo.webapp.tests, it runs only th...
[ 1 ]
[]
[]
[ "django", "python", "testing", "unit_testing" ]
stackoverflow_0006682140_django_python_testing_unit_testing.txt
Q: uploading file via telnet Im writing a python scrpit to upload files to my file server: host = "myhost.dev" tn = telnetlib.Telnet() tn.open(host, 5202) print tn.read_until("\n") fp = "./output" f = open(fp, "r") f_body = f.read() tn.write(f_body) tn.write("\n") f.close() If file has a new line character- 0a, ...
uploading file via telnet
Im writing a python scrpit to upload files to my file server: host = "myhost.dev" tn = telnetlib.Telnet() tn.open(host, 5202) print tn.read_until("\n") fp = "./output" f = open(fp, "r") f_body = f.read() tn.write(f_body) tn.write("\n") f.close() If file has a new line character- 0a, and it is part of a binary data...
[ "I think that telnet is not the best option for transfering files, but if you still want to use it for uploading files. You may try to do the following (haven't tried, but I think should work)\n#On client side\n...\nimport base64\nwith open('test.gz','rb') as f:\n content = f.read()\n\ncontent_serialized = base6...
[ 4, 0 ]
[]
[]
[ "python", "telnetlib" ]
stackoverflow_0006730697_python_telnetlib.txt
Q: How-to import constants in many files I have a package containing many modules. Each module uses constants that I have defined independently in each file. However, all these constants have to be constistent with each other. So I try to define them in a single file and import it in each file. When I run it I have e...
How-to import constants in many files
I have a package containing many modules. Each module uses constants that I have defined independently in each file. However, all these constants have to be constistent with each other. So I try to define them in a single file and import it in each file. When I run it I have errors for constants not found. Is their a c...
[ "You can declare all your constants in one file, say constants.py and then import them into others. Here is an example:\n# constants.py\nFOO = 'foo'\nPI = 3.14\n\n# main.py\nimport constants\nprint constants.PI\n\n" ]
[ 12 ]
[]
[]
[ "import", "package", "python" ]
stackoverflow_0006731345_import_package_python.txt
Q: IRC "No Ident response" I am trying to make a IRC client in Python and I got a problem with Ident. I listen on port 113 for message from the Ident server, this works. The message looks like this: 49764 , 6667. But when I am sending the message back I get "No Ident response" (The message looks like the message in t...
IRC "No Ident response"
I am trying to make a IRC client in Python and I got a problem with Ident. I listen on port 113 for message from the Ident server, this works. The message looks like this: 49764 , 6667. But when I am sending the message back I get "No Ident response" (The message looks like the message in the RFC). Nothing that I tried...
[ "You are missing parts of the RFC. The request does indeed look like \"49764, 6667\", but your response need to be a little longer:\n49764,6667:USERID:UNIX:Nicklas\n\nDon't forget to terminate it with CRLF.\n" ]
[ 1 ]
[]
[]
[ "ident", "irc", "python", "sockets" ]
stackoverflow_0006731299_ident_irc_python_sockets.txt
Q: Logging queries with sqlalchemy 0.6 With turbogears 2.1 and sqlalchemy 0.7 the queries from console were logged out to stdout. However I needed to downgred to 0.6 and they no longer appear. Documentation of logging seems to be identical and I couldn't find anything in changelog. How to log in sqlalchemy 0.6? EDIT ...
Logging queries with sqlalchemy 0.6
With turbogears 2.1 and sqlalchemy 0.7 the queries from console were logged out to stdout. However I needed to downgred to 0.6 and they no longer appear. Documentation of logging seems to be identical and I couldn't find anything in changelog. How to log in sqlalchemy 0.6? EDIT The DBSession.bind.echo is set to False. ...
[ "I don't know about TurboGears, but you need to ensure that the engine's echo setting is set to True, e.g.\nengine = sqlalchemy.create_engine('sqlite:///:memory:', echo=True)\n\nBy default, the echo setting is False, so queries aren't logged to stdout. It's possible that TG configures the two SA versions differentl...
[ 5, 3 ]
[]
[]
[ "python", "sqlalchemy", "turbogears", "turbogears2" ]
stackoverflow_0006194533_python_sqlalchemy_turbogears_turbogears2.txt
Q: Query and Display Results Every 'X' amount of Minutes from Oracle Database Is there a way that I can query an Oracle 10g database, and display the results in a dynamically refreshed html file every 3 minutes, for example? Here is my predicament: I have several queries that I would LOVE to display the results of ...
Query and Display Results Every 'X' amount of Minutes from Oracle Database
Is there a way that I can query an Oracle 10g database, and display the results in a dynamically refreshed html file every 3 minutes, for example? Here is my predicament: I have several queries that I would LOVE to display the results of to a whole organization on a basic HTML web page with some CSS. The problem is ...
[ "you can also execute an Ajax Request every 3 minutes using the setTimeout() function.\nUsing jQuery framework\n$(document).ready(function() {\n setTimeout(\"getFeed()\", 180000); //180000 = 3 minutes in milliseconds\n});\n\nfunction getFeed() {\n //ajaxRequest here\n}\n\nFor more info on ajax you can go here...
[ 2, 1 ]
[]
[]
[ "oracle", "php", "plsql", "python", "xml" ]
stackoverflow_0006721089_oracle_php_plsql_python_xml.txt
Q: How do I get Sphinx to markup C calls in text the way the standard Python docs do? In the standard Python documentation, system calls appear as bold, fixed-width font. You can see this in the asyncore section, when it mentions select() or poll() for example: http://docs.python.org/py3k/library/asyncore.html I chec...
How do I get Sphinx to markup C calls in text the way the standard Python docs do?
In the standard Python documentation, system calls appear as bold, fixed-width font. You can see this in the asyncore section, when it mentions select() or poll() for example: http://docs.python.org/py3k/library/asyncore.html I checked the source code for asyncore, and it has no special markups for these functions, so ...
[ "Where did you see that there is no special markup for the C function calls? When I looked at the latest source for this file it has :cfunc:'select', which I think is old style Sphinx markup for C code. For the latest way of doing it read up on The C Domain.\n" ]
[ 1 ]
[]
[]
[ "python", "python_sphinx" ]
stackoverflow_0006730532_python_python_sphinx.txt
Q: How to get to the SSL/TLS internals from Python? I am implementing the XMPP protocol in Python (2.7 and 3.2) and I found one important thing stopping me from making the implementation fully compliant. The current specification (RFC 6120) requires implementation of the SCRAM-SHA-1-PLUS SASL mechanism (RFC 5802), wh...
How to get to the SSL/TLS internals from Python?
I am implementing the XMPP protocol in Python (2.7 and 3.2) and I found one important thing stopping me from making the implementation fully compliant. The current specification (RFC 6120) requires implementation of the SCRAM-SHA-1-PLUS SASL mechanism (RFC 5802), which, in turn, requires the 'tls-unique' channel bindin...
[ "It seems the easiest way to get the data from the Python SSLSocket is to fix the standard Python library. So I did it, the patch will be included in Python 3.3.\nhttp://bugs.python.org/issue12551#msg140450\n", "This hopefully will save you some time.\nPython SASL resources:\n\nSuelta pure-python SASL library (pr...
[ 12, 0 ]
[]
[]
[ "python", "ssl" ]
stackoverflow_0006646633_python_ssl.txt
Q: How to create a Matrix through an iteration in Python I want to create a (3n*7) Matrix in python through Iteration, I did this in VB.Net and it worked but it gives me some challenge in Python as this a new language to me. n can be the number of Iterations to build up the matrix, i.e. ; if u iterated 3 times, the m...
How to create a Matrix through an iteration in Python
I want to create a (3n*7) Matrix in python through Iteration, I did this in VB.Net and it worked but it gives me some challenge in Python as this a new language to me. n can be the number of Iterations to build up the matrix, i.e. ; if u iterated 3 times, the matrix will be a 9*7 matrix. Here is how I did it in VB.Net....
[ "One solution is to use a numpy (download here) matrix:\n>>> from numpy import zeros, matrix\n>>> n = 2\n>>> mat = matrix(zeros([3*n, 7]))\n>>> mat\nmatrix([[ 0., 0., 0., 0., 0., 0., 0.],\n [ 0., 0., 0., 0., 0., 0., 0.],\n [ 0., 0., 0., 0., 0., 0., 0.],\n [ 0., 0., 0., 0., ...
[ 3, 1, 1 ]
[]
[]
[ "numpy", "python", "vb.net" ]
stackoverflow_0006731462_numpy_python_vb.net.txt
Q: Embedded jpeg showing in svg, but not in pdf when generated with svglib, reportlab I'm using version 0.6.3 of svglib and reportlab 2.5. I created the test svg in Inkscape; placed one jpeg in it, embedded with base64. When I step in the code, the jpeg gets generated in svglib, but it never shows up in pdf. Vector ...
Embedded jpeg showing in svg, but not in pdf when generated with svglib, reportlab
I'm using version 0.6.3 of svglib and reportlab 2.5. I created the test svg in Inkscape; placed one jpeg in it, embedded with base64. When I step in the code, the jpeg gets generated in svglib, but it never shows up in pdf. Vector shapes work fine and get shown, but jpeg is missing. I was using the basic command in te...
[ "Without a little more detail this is tough to answer, the most common mistake, though, when including images is not including the namespace:\n<image href=\"someurlgoeshere\" x=\"0\" y=\"0\" height=\"10\" width=\"10\"></image>\n\nvs\n<image xlink:href=\"someurlgoeshere\" x=\"0\" y=\"0\" height=\"10\" width=\"10\"><...
[ 0 ]
[]
[]
[ "django", "pdf", "python", "svg" ]
stackoverflow_0006705619_django_pdf_python_svg.txt
Q: Running Python script using WshShell.Run in VBS does not generate output file I've got a problem with some VB scripting - it doesn't seem like it should be terribly difficult to solve, but even after trudging through many a page of Google I have yet to find a solution. [The problem] Here is my python file (test.py...
Running Python script using WshShell.Run in VBS does not generate output file
I've got a problem with some VB scripting - it doesn't seem like it should be terribly difficult to solve, but even after trudging through many a page of Google I have yet to find a solution. [The problem] Here is my python file (test.py), simplified to just show the problem: f = open("testing.txt", 'w') f.write("oh ha...
[ "First, your Python script looks suspicious, I doubt the backslashes work in a simple string. At least, in my test, it didn't work, I just replaced them with forward slashes.\nNext, you can see the error message by prepending cmd with cmd /k, the run window remains on screen. You can see the .py file isn't found, b...
[ 3, 0 ]
[]
[]
[ "python", "vbscript" ]
stackoverflow_0006732543_python_vbscript.txt
Q: ImportError: cannot import name NO_DEFAULT I'm trying to run a Django site's manage.py script, but it fails with the following error: Traceback (most recent call last): File "manage.py", line 2, in <module> from django.core.management import execute_manager File "/scratch/tools/lib/python2.5/site-packages/...
ImportError: cannot import name NO_DEFAULT
I'm trying to run a Django site's manage.py script, but it fails with the following error: Traceback (most recent call last): File "manage.py", line 2, in <module> from django.core.management import execute_manager File "/scratch/tools/lib/python2.5/site-packages/django/core/management/__init__.py", line 4, in ...
[ "As always in Python, __all__ is more of a guideline than a rule. It comes about because of the we-love-to-hate-it *-import, described in the docs as\n\nIf the list of identifiers is replaced by a star ('*'), all public\n names defined in the module are bound in the local namespace of the\n import statement.\n\nT...
[ 0 ]
[]
[]
[ "django", "importerror", "optparse", "python" ]
stackoverflow_0006732363_django_importerror_optparse_python.txt
Q: Unexpected NameError I'm writing a script to batch-rename all files inside a folder. I'm trying to make it modular, so the core algorithm (the one that generates the new file name) is easily exchangeable. Here's what I've got so far: from os import listdir, rename def renamer(path, algorithm, counter=False, data=...
Unexpected NameError
I'm writing a script to batch-rename all files inside a folder. I'm trying to make it modular, so the core algorithm (the one that generates the new file name) is easily exchangeable. Here's what I've got so far: from os import listdir, rename def renamer(path, algorithm, counter=False, data=None, data2=None, safe=Tru...
[ "don't use exec or eval for this, and just write\nnew = algorithm(i, file_index, data, data2)\n\nmake sure all your algorithms can use the 4 arguments (ignoring those they don't need). \nIf you don't like this, the following is much more pythonic and efficient than using eval:\nargs = [i] \nif counter:\n args.ap...
[ 3, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006732562_python.txt
Q: Human readable form of DNS lookup I have got a very simple idea in mind that i want to try out. Say i have a browser, chrome for instance, and i want to search for the ip of the domain name, say www.google.com. I use windows 7 and i have set the dns lookup properties to manual and have given the address 127.0.0.1 ...
Human readable form of DNS lookup
I have got a very simple idea in mind that i want to try out. Say i have a browser, chrome for instance, and i want to search for the ip of the domain name, say www.google.com. I use windows 7 and i have set the dns lookup properties to manual and have given the address 127.0.0.1 where my server (written in Python is r...
[ "If you want to analyse the query data using python, I recommend the excellent scapy library (http://www.secdev.org/projects/scapy/) It's got decoding (and building!) routines for many network protocols including DNS.\nHere's your original program with the scapy decoding added:\nfrom time import sleep\nimport sock...
[ 4, 2, 0 ]
[ "What is your goal? \nIf you want to learn how DNS operates, you could start by reading the relevant RFCs. Or use wireshark to capture and analyse the DNS traffic for you. \n" ]
[ -1 ]
[ "dns", "python", "tcp" ]
stackoverflow_0006567467_dns_python_tcp.txt
Q: Python Regex returns me the value with parentheses I'm trying to run this code: picture = re.search("#4F9EFF;\"><img src=\"(.+?)\" width=\"120\" height=\"90\"", data) and when i do print picture.groups(1) it returns me the value but with parentheses, why? Output: ('http://sample.com/img/file.jpg',) A: The group...
Python Regex returns me the value with parentheses
I'm trying to run this code: picture = re.search("#4F9EFF;\"><img src=\"(.+?)\" width=\"120\" height=\"90\"", data) and when i do print picture.groups(1) it returns me the value but with parentheses, why? Output: ('http://sample.com/img/file.jpg',)
[ "The group is a tuple containing one element. You can access the string (which is the first match) as output[0]. The important part is the comma after the string.\nBUT\nDON'T PARSE HTML WITH REGEX\nYou should use a proper HTML parser. This will save you innumerable headaches in the future, when your regex fails to ...
[ 4, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006732923_python.txt
Q: mechanize submit form character encoding problem I am trying to scrape http://www.nscb.gov.ph/ggi/database.asp, specifically all the tables you get from selecting the municipalities/provinces. I am using python with lxml.html and mechanize. my scraper works fine so far, however I get HTTP Error 500: Internal Serve...
mechanize submit form character encoding problem
I am trying to scrape http://www.nscb.gov.ph/ggi/database.asp, specifically all the tables you get from selecting the municipalities/provinces. I am using python with lxml.html and mechanize. my scraper works fine so far, however I get HTTP Error 500: Internal Server Error when submitting the municipality[19] "Peñarrub...
[ "quick and dirty hack:\ndef _pairs(self):\n return [(k, v.decode('utf-8').encode('latin-1')) for (i, k, v, c_i) in self._pairs_and_controls()]\n\nfrom mechanize import HTMLForm\nHTMLForm._pairs = _pairs\n\nor something less invasive (I think there are no other solutions because the class Item protects 'name' fie...
[ 1, 1 ]
[]
[]
[ "encoding", "mechanize", "python", "scraper" ]
stackoverflow_0006610208_encoding_mechanize_python_scraper.txt
Q: Remove letter duplicates that are in a row Looking for a fast way to limit duplicates to a max of 2 when they occur next to each other. For example: jeeeeeeeep => ['jep','jeep'] Looking for suggestions in python but happy to see an example in anything - not difficult to switch. Thanks for any assistance! EDIT: E...
Remove letter duplicates that are in a row
Looking for a fast way to limit duplicates to a max of 2 when they occur next to each other. For example: jeeeeeeeep => ['jep','jeep'] Looking for suggestions in python but happy to see an example in anything - not difficult to switch. Thanks for any assistance! EDIT: English doesn't have any (or many) consonants (sa...
[ "Here's a recursive solution using groupby. I've left it up to you which characters you want to be able to repeat (defaults to vowels only though):\nfrom itertools import groupby\n\ndef find_dub_strs(mystring):\n grp = groupby(mystring)\n seq = [(k, len(list(g)) >= 2) for k, g in grp]\n allowed = ('aeioupt...
[ 3, 1, 1, 0 ]
[ "Use regular expressions along with a key press event!\n" ]
[ -1 ]
[ "pattern_matching", "python", "spell_checking", "string" ]
stackoverflow_0006733443_pattern_matching_python_spell_checking_string.txt
Q: Python random digit letter and additional generator I would like to generate a random number string of N length with this code: import random import string N=512 print ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for x in range(N)) What is missing is that I would like to...
Python random digit letter and additional generator
I would like to generate a random number string of N length with this code: import random import string N=512 print ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for x in range(N)) What is missing is that I would like to add "special characters like e.g. "@,;:.§$%&/(!"" And I ...
[ "string module has a class for such special characters:\n>>> print string.punctuation\n!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\n\nTo save generated string to file use something like:\nN=512\nchars_per_line = 15\n\ns = ''.join(random.choice(string.digits + string.ascii_letters + string.punctuation) for i in xrange(N))\n\...
[ 5, 3 ]
[]
[]
[ "generator", "python", "random" ]
stackoverflow_0006733380_generator_python_random.txt
Q: Subclass-safe class variable I can do: class T(object): i = 5 # then use the value somewhere in a function def p(self): print id(i), T.i .. but, if I happen to subclass T .. class N(T): pass .. then N.i will in fact be T.i. I found a way to deal with this: class T(object): i = 5 ...
Subclass-safe class variable
I can do: class T(object): i = 5 # then use the value somewhere in a function def p(self): print id(i), T.i .. but, if I happen to subclass T .. class N(T): pass .. then N.i will in fact be T.i. I found a way to deal with this: class T(object): i = 5 def p(self): print self.__...
[ "Uh... did you know you can refer to class attributes from instances?\nclass T(object):\n i = 5\n\n def p(self):\n print(id(self.i), self.i)\n\n\nClass methods aside, I just thought of an interesting idea. Why not use a property that accesses the underlying class instance?\nclass T(object):\n _i = 5...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006733702_python.txt
Q: Fastest way in Python to find a 'startswith' substring in a long sorted list of strings I've done a lot of Googling, but haven't found anything, so I'm really sorry if I'm just searching for the wrong things. I am writing an implementation of the Ghost for MIT Introduction to Programming, assignment 5. As part of ...
Fastest way in Python to find a 'startswith' substring in a long sorted list of strings
I've done a lot of Googling, but haven't found anything, so I'm really sorry if I'm just searching for the wrong things. I am writing an implementation of the Ghost for MIT Introduction to Programming, assignment 5. As part of this, I need to determine whether a string of characters is the start of any valid word. I ha...
[ "Generator expressions are evaluated lazily, so if you only need to determine whether or not your word is valid, I would expect the following to be more efficient since it doesn't necessarily force it to build the full list once it finds a match:\ndef word_exists(wordlist, word_fragment):\n return any(w.startsw...
[ 15, 4, 1, 0, 0 ]
[ "Doing binary search in the list is not going to guarantee you anything. I am not sure how that would work either. \nYou have a list which is ordered, it is a good news. The algorithmic performance complexity of both your cases is O(n) which is not bad, that you just have to iterate through the whole wordlist once...
[ -3 ]
[ "performance", "python", "sorting" ]
stackoverflow_0006722985_performance_python_sorting.txt
Q: globals dict error When I try to run this code """Hello World""" print globals()[__doc__] Why do I get this error ? Traceback (most recent call last): File "D:\myProjects\python\Python-13.py", line 3, in <module> print globals()[__doc__] KeyError: 'Hello World' Context : I just want the doc string of current mo...
globals dict error
When I try to run this code """Hello World""" print globals()[__doc__] Why do I get this error ? Traceback (most recent call last): File "D:\myProjects\python\Python-13.py", line 3, in <module> print globals()[__doc__] KeyError: 'Hello World' Context : I just want the doc string of current module
[ "You need print globals()['__doc__'].\n", "The docstring of the current module is __doc__. In your code you are trying to use that string as key in the global dictionary of the module.\nTo be clear, to print the docstring, just do print __doc__.\n" ]
[ 6, 5 ]
[]
[]
[ "global", "python" ]
stackoverflow_0006733882_global_python.txt
Q: Python - Get post data I am trying to make some python scripts on google appspot. I am just starting with python so I don't now verry much about it. I am using the example code you can find on the google appspot documentations. But whenever I submit the form in this code, I just get an blank page and no errors. An...
Python - Get post data
I am trying to make some python scripts on google appspot. I am just starting with python so I don't now verry much about it. I am using the example code you can find on the google appspot documentations. But whenever I submit the form in this code, I just get an blank page and no errors. Anyone knows why? import cgi ...
[ "WOAH\nIf you're using google app engine (hosted on appspot so I'm sure that's what you're using) then you use this:\ntPostVariable = self.request.get('PostVariableName')\n\nIf you've set up your handler like this then it will automagically work:\nclass ClassName(webapp.RequestHandler):\n #For Get Pages\n def...
[ 1, 0, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006723757_google_app_engine_python.txt
Q: How to find out what database (e.g. wether using mysql/pgsql/?) in a django south migration? I'm writing a migration using Django's South, and it can only work on MySQL databases. Is there anyway I can find out what database is being used (i.e. is this running on mysql or is it on postgres, etc.). I want to then r...
How to find out what database (e.g. wether using mysql/pgsql/?) in a django south migration?
I'm writing a migration using Django's South, and it can only work on MySQL databases. Is there anyway I can find out what database is being used (i.e. is this running on mysql or is it on postgres, etc.). I want to then raise an exception. I am writing a nontrivial migration (renaming forgein keys), and I think it'll ...
[ "I don't think south says which database the migration was created with, instead of looking at south could you look at the django settings and see what database they have configured.\nLook at the database engines they have set in the settings and if it is something other then \"django.db.backends.mysql\" throw your...
[ 1 ]
[]
[]
[ "database", "django", "django_south", "migration", "python" ]
stackoverflow_0006733784_database_django_django_south_migration_python.txt
Q: How would I validate a wsdl document using python? How would I validate a wsdl document using python? Which python frameworks would I use?? Could I do it with just a few lines of code?? Are there any really succinct web services libraries out there?? Code examples appreciated. thanks A: You could use SOAPpy, lik...
How would I validate a wsdl document using python?
How would I validate a wsdl document using python? Which python frameworks would I use?? Could I do it with just a few lines of code?? Are there any really succinct web services libraries out there?? Code examples appreciated. thanks
[ "You could use SOAPpy, like this. You could also have a look at the info in this answer.\n" ]
[ 1 ]
[]
[]
[ "python", "validation", "web_services", "wsdl" ]
stackoverflow_0006733825_python_validation_web_services_wsdl.txt
Q: Get 'popular categories' in django i have 2 models Books and Categories and I'm wondering how i would get the top 10 categories by the amount of books they have in them. My model looks like this class Book(models.Model): """(Book description)""" categories = models.ManyToManyField(Category) class Category...
Get 'popular categories' in django
i have 2 models Books and Categories and I'm wondering how i would get the top 10 categories by the amount of books they have in them. My model looks like this class Book(models.Model): """(Book description)""" categories = models.ManyToManyField(Category) class Category(models.Model): """(Topic descriptio...
[ "Have a look at Aggregation and order-by in the Django documentation.\nYou should be able to do something like:\nCategory.objects.annotate(num_books=Count('book')).order_by('num_books')\n\nThis will give you a list of categories ordered by their popularity, and you can then display only the first (or last) ten usin...
[ 5 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0006734035_django_mysql_python.txt
Q: Syntax Error When Running paster? No idea what happened, but all of a sudden, paster stopped working on my server (working with virtualenv and pyramid). Tried reinstalling everything but didn't work - same error again: Traceback (most recent call last): File "bin/paster", line 7, in ? sys.exit( File "/home...
Syntax Error When Running paster?
No idea what happened, but all of a sudden, paster stopped working on my server (working with virtualenv and pyramid). Tried reinstalling everything but didn't work - same error again: Traceback (most recent call last): File "bin/paster", line 7, in ? sys.exit( File "/home/user/webapps/myapp/htdocs/lib/python2....
[ "You are using Python 2.4. It does not have the with statement. It only came in Python 2.5.\nUpdate your version of Python.\n" ]
[ 3 ]
[]
[]
[ "paster", "pyramid", "python", "syntax" ]
stackoverflow_0006729070_paster_pyramid_python_syntax.txt
Q: How connect Spyder to mysql on Winx64 and Fedora? Im trying to use Spyder with pyodbc to connect mysql using a PyQT4 gui framework. I have pyodbc in Spyder figure out. How do I use PyQt4 to get info into gui's? I'm looking to use gui on Fedora and winx64. Edit: I figured out the fedora driver. Can anyone help me...
How connect Spyder to mysql on Winx64 and Fedora?
Im trying to use Spyder with pyodbc to connect mysql using a PyQT4 gui framework. I have pyodbc in Spyder figure out. How do I use PyQt4 to get info into gui's? I'm looking to use gui on Fedora and winx64. Edit: I figured out the fedora driver. Can anyone help me with QMYSQL driver.
[ "See this\nhttp://doc.qt.nokia.com/latest/sql-driver.html#how-to-build-the-mysql-driver-for-mingw-users\nMaybe that will help. \n", "Have you considered using PyQt's built-in MySQL support? This could make it a bit easier to display DB info, depending on what you want the interface to look like.\n" ]
[ 1, 0 ]
[]
[]
[ "pyqt4", "python", "spyder" ]
stackoverflow_0006582404_pyqt4_python_spyder.txt
Q: How to set LANG variable in Windows? I'm making an application that supports multi language. And I am using gettext and locale to solve this issue. How to set LANG variable in Windows? In Linux and Unix-like systems it's just as simple as $ LANG=en_US python appname.py And it will automatically set the locale to...
How to set LANG variable in Windows?
I'm making an application that supports multi language. And I am using gettext and locale to solve this issue. How to set LANG variable in Windows? In Linux and Unix-like systems it's just as simple as $ LANG=en_US python appname.py And it will automatically set the locale to that particular language. But in Windows,...
[ "Windows locale support doesn't rely on LANG variable (or, indeed, any other environmental variable). It is whatever the user set it to in Control Panel.\n", "you can use a batch file like in here: http://www.geany.org/Documentation/FAQ#QQuestions11 \nset LANG=en_US\nsomething.exe\n\nor set it through the control...
[ 6, 5 ]
[]
[]
[ "locale", "python", "windows" ]
stackoverflow_0001180590_locale_python_windows.txt
Q: Order by method in model i have 2 models Car and Rating. People rate cars (duhh). I have wrote a simple get_average_score() method which gets the average score of the Car, below are my models. class Car(models.Model): def get_average_score(self): return self.rating_set.aggregate(Avg('score')) class Rating(m...
Order by method in model
i have 2 models Car and Rating. People rate cars (duhh). I have wrote a simple get_average_score() method which gets the average score of the Car, below are my models. class Car(models.Model): def get_average_score(self): return self.rating_set.aggregate(Avg('score')) class Rating(models.Model): car = models.F...
[ "No but you could do this using annotate e.g.\nCar.objects.annotate(score=Avg('rating__score').order_by('-score')\n\n" ]
[ 1 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0006734615_django_mysql_python.txt
Q: Python regular expression again - match url part II Ok. I get regexp from here (only WWW links, second version). Everything is fine, except one thing, it parse BBCode too. Regexp (?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s(...
Python regular expression again - match url part II
Ok. I get regexp from here (only WWW links, second version). Everything is fine, except one thing, it parse BBCode too. Regexp (?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’])) What fails...
[ "This is a little rough, but try this:\n$preg = \"%(?:https?://|www\\d{0,3}.)(?:[\\/A-Za-z0-9-_.]+(?!(?:<|\\[/([A-Za-z0-9])+?\\1)))%\";\n\nI've tested it and it should work as expected if I understood your question correctly.\n" ]
[ 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006734459_python_regex.txt
Q: Google AppEngine tells me that my int is not an int The relevant part of the code: pk = int(pk) logging.info('pk: %r :: %s', pk, type(pk)) instance = models.Model.get_by_id(int(pk)) The output from the log message above pk: 757347 :: <type 'int'> The stacktrace: Traceback (mo...
Google AppEngine tells me that my int is not an int
The relevant part of the code: pk = int(pk) logging.info('pk: %r :: %s', pk, type(pk)) instance = models.Model.get_by_id(int(pk)) The output from the log message above pk: 757347 :: <type 'int'> The stacktrace: Traceback (most recent call last): File "/base/python_runtime/python...
[ "Does your model have a property 'pk', which is now an IntegerProperty(), but was previously a StringProperty(), and the entity with id 757347 was saved with the old version of the model?\n", "Create a custom validator for your pk IntegerProperty.\nI think @saxon-druce has the right idea about what is failing.\nY...
[ 5, 2, 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0005660549_google_app_engine_google_cloud_datastore_python.txt
Q: Facing "MemoryError" while doing multithread txt file I/Os, looking for better solution I'm working with only one txt file which is about 4 MB, and the file needs frequently I/O such as append new lines/search for certain lines which includes specific phrases/replace certain line with another line etc. In order t...
Facing "MemoryError" while doing multithread txt file I/Os, looking for better solution
I'm working with only one txt file which is about 4 MB, and the file needs frequently I/O such as append new lines/search for certain lines which includes specific phrases/replace certain line with another line etc. In order to process the file "at the same time", threading.RLock() is used to lock the resource when it...
[ "Without seeing more of your code, it's impossible to know why you are running out of memory. The with statement is the preferred way to open files and close them when done though:\nwith open(\"TestFile.txt\", \"r\") as current_file:\n file_content = current_file.read()\n\n(sorry, UpperCamelCase for variables j...
[ 1, 0 ]
[]
[]
[ "file_io", "memory_management", "multithreading", "python", "with_statement" ]
stackoverflow_0006734146_file_io_memory_management_multithreading_python_with_statement.txt
Q: Token() objects in Lepl So I'm making my way through the Lepl tutorial, a Python parser, and I can't quite figure out what exactly the difference is between something like Token(Real()) and just Real(). I found the docs on the function but they are pretty unhelpful. So, what exactly does the Token() class do? Why ...
Token() objects in Lepl
So I'm making my way through the Lepl tutorial, a Python parser, and I can't quite figure out what exactly the difference is between something like Token(Real()) and just Real(). I found the docs on the function but they are pretty unhelpful. So, what exactly does the Token() class do? Why is it different than regular ...
[ "Normally, LEPL operates on a stream of characters as they are in the input. That's simple, but as you have seen you'd need lots of redundant rules to ignore e.g. whitespace whereever it is legal but ignored.\nThis problem has a common solution, namely first running the input string though a relatively simple autom...
[ 4 ]
[]
[]
[ "lepl", "parsing", "python" ]
stackoverflow_0006734487_lepl_parsing_python.txt
Q: Delete a variable in boo I know that the similarities between boo and Python are only superficial, but still, how can I do an equivalent of the following Python code in boo? a = 'a' del a a = 1 I've tried a = 'a' a = null System.GC.Collect() ...
Delete a variable in boo
I know that the similarities between boo and Python are only superficial, but still, how can I do an equivalent of the following Python code in boo? a = 'a' del a a = 1 I've tried a = 'a' a = null System.GC.Collect() ...
[ "This is not possible in Boo. Boo uses implicit static-typing. Thus, all variables are strongly typed based on their first assignment within their scope. Once assigned, the type of the variable cannot change.\nGarbage collecting will ensure that objects on the heap which are no longer referenced will be removed fro...
[ 3, 0 ]
[]
[]
[ ".net", "boo", "garbage_collection", "python" ]
stackoverflow_0006257867_.net_boo_garbage_collection_python.txt
Q: Psycopg2 error messages All, I am writing error messages to a log file and it's becoming pretty large because it errors on unique constraints in the DB. That is fine and it's actually want it to do so my question is, how can I avoid writing the duplicate key errors to the log file every time they happen? ...
Psycopg2 error messages
All, I am writing error messages to a log file and it's becoming pretty large because it errors on unique constraints in the DB. That is fine and it's actually want it to do so my question is, how can I avoid writing the duplicate key errors to the log file every time they happen? except Exception as err: ...
[ "Psycopg passes the PostgreSQL error code along with the exception in the attribute pgcode: you can verify that the error is actually related to a unique violation and avoid logging them. For example:\ntry:\n cursor.execute(\"...\")\nexcept psycopg2.IntegrityError as err:\n if err.pgcode != '23505':\n ...
[ 8 ]
[]
[]
[ "error_handling", "psycopg2", "python" ]
stackoverflow_0006697719_error_handling_psycopg2_python.txt
Q: python asynchat state I've just started working with the basics of python socket networking. As an exercise in understanding, I've been trying to hash out a basic server that will ask it's client for a file type, and upon receiving a string of the extension, ask for the actual file. I've found numerous tutorials...
python asynchat state
I've just started working with the basics of python socket networking. As an exercise in understanding, I've been trying to hash out a basic server that will ask it's client for a file type, and upon receiving a string of the extension, ask for the actual file. I've found numerous tutorials online that use the asynco...
[ "Normally the connection would be kept open after it's initially created, so all the parts of the communication from the same client go to the same HTTPChannel object - accept is only called when a new connection is created.\n" ]
[ 1 ]
[]
[]
[ "asyncore", "python", "sockets" ]
stackoverflow_0006735399_asyncore_python_sockets.txt
Q: weird py2exe error I made this code into an executable with py2exe: # File: zipfile-example-1.py from Tkinter import * import zipfile import os import glob Admin = Tk() Admin.configure(bg='grey') La = Label(Admin,bg='grey', text='Dir to back up.') La.pack() Ent = Entry(Admin, bg='grey') Ent.pack() la = Label(Admin...
weird py2exe error
I made this code into an executable with py2exe: # File: zipfile-example-1.py from Tkinter import * import zipfile import os import glob Admin = Tk() Admin.configure(bg='grey') La = Label(Admin,bg='grey', text='Dir to back up.') La.pack() Ent = Entry(Admin, bg='grey') Ent.pack() la = Label(Admin,bg='grey', text='Zip fi...
[ "You can't have dashes in the name of a Python module. And you can't call a Python module zipfile, because there's already a standard library module with that name. Does it work if you rename it to z.py, before you run py2exe?\n" ]
[ 1 ]
[]
[]
[ "py2exe", "python" ]
stackoverflow_0006182438_py2exe_python.txt
Q: Multithreaded FTP upload. Is it possible? I need to upload multiple files from directory to the server via FTP and SFTP. I've solved this task for SFTP with python, paramiko and threading. But I have problem with doing it for FTP. I tried to use ftplib for python, but it seems that it doesn't support threading and...
Multithreaded FTP upload. Is it possible?
I need to upload multiple files from directory to the server via FTP and SFTP. I've solved this task for SFTP with python, paramiko and threading. But I have problem with doing it for FTP. I tried to use ftplib for python, but it seems that it doesn't support threading and I upload all files one by one, which is very s...
[ "There is an effor of creating an asynchronous FTP client but basically the FTP protocol allows synchronous commands. To allow parallel downloads/uploads you need to open multiple FTP connections. This can be done by ftplib and threads.\n", "Another approach to concurrency besides through is asynchronous io. For ...
[ 2, 1, 0, 0 ]
[]
[]
[ "curl", "ftp", "multithreading", "php", "python" ]
stackoverflow_0002570621_curl_ftp_multithreading_php_python.txt
Q: Help me with mercurial extension exportfiles i'm trying to use exportfiles extension for mercurial but I'm getting this error: c:\xampp\htdocs\dev>hg exportfiles -r 1 /tmp/export ** unknown exception encountered, please report by visiting ** http://mercurial.selenic.com/wiki/BugTracker ** Python 2.6.6 (r266:84297...
Help me with mercurial extension exportfiles
i'm trying to use exportfiles extension for mercurial but I'm getting this error: c:\xampp\htdocs\dev>hg exportfiles -r 1 /tmp/export ** unknown exception encountered, please report by visiting ** http://mercurial.selenic.com/wiki/BugTracker ** Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel...
[ "Mercurial's API changed after version 1.8. \n\nVarious functions have been moved from cmdutil.py to scmutil.py,\n including revrange/revsingle/revpair and match/matchall/matchfiles\n\nAssuming this is the source of the extension you're using, line 11 should be\nfrom mercurial import util, scmutil\n\nand line 39 s...
[ 5, 1 ]
[]
[]
[ "mercurial", "python", "tortoisehg" ]
stackoverflow_0006734810_mercurial_python_tortoisehg.txt
Q: PyQt Sort List of Radio Buttons I am trying to dynamically create a list of radio buttons that represents the open COM ports on my computer. Creating and displaying the list the first time is easy enough since I can just sort the ports to be in numerical order and then add their corresponding radio button to my v...
PyQt Sort List of Radio Buttons
I am trying to dynamically create a list of radio buttons that represents the open COM ports on my computer. Creating and displaying the list the first time is easy enough since I can just sort the ports to be in numerical order and then add their corresponding radio button to my vertical layout. However, if the use...
[ "Instead of using addWidget(), determine the index in the list of buttons to place the new one, and use QBoxLayout.insertWidget(index, widget) to insert it there:\nnewButton = QRadioButton(...)\nnewText = newButton.text()\n\nindex = 0\nfor button in get_buttons():\n if button.text() >= newText:\n break\n ...
[ 3 ]
[]
[]
[ "pyqt", "python", "radio_button", "user_interface" ]
stackoverflow_0006735663_pyqt_python_radio_button_user_interface.txt
Q: Treat value of string as .. an attribute name? Say I have a dict: d = { 'eggs': 4, 'cheese': 6, 'coconuts': 8, } Is is possible to loop over the dictionary, creating variables named after the keys, assigning them the corresponding value? eggs = 4 cheese = 6 coconuts = 8 Or maybe inside an object? sel...
Treat value of string as .. an attribute name?
Say I have a dict: d = { 'eggs': 4, 'cheese': 6, 'coconuts': 8, } Is is possible to loop over the dictionary, creating variables named after the keys, assigning them the corresponding value? eggs = 4 cheese = 6 coconuts = 8 Or maybe inside an object? self.eggs = 4 self.cheese = 6 self.coconuts = 8 Is thi...
[ ">>> d = {\n... 'eggs': 4,\n... 'cheese': 6,\n... 'coconuts': 8,\n... }\n>>> globals().update(d)\n>>> eggs\n4\n>>> cheese\n6\n>>> coconuts\n8\n>>> d\n{'cheese': 6, 'eggs': 4, 'coconuts': 8}\n\nBut for classes, it is easier(safer), just use:\nfor item, value in d.items():\n setattr(some_object, item,...
[ 6, 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0006735583_python.txt
Q: find and update duplicates in a list of lists I am looking for a Pythonic way to solve the following problem. I have (what I think is) a working solution but it has complicated flow controls and just isn't "pretty". (Basically, a C++ solution) I have a list of lists. Each list contains multiple items of varying...
find and update duplicates in a list of lists
I am looking for a Pythonic way to solve the following problem. I have (what I think is) a working solution but it has complicated flow controls and just isn't "pretty". (Basically, a C++ solution) I have a list of lists. Each list contains multiple items of varying types (maybe 10 items per list) The overall order...
[ "from collections import defaultdict\n\nlists = [['apple', 'window', 'pear', 2, 1.55, 'banana'],\n['apple', 'orange', 'kiwi', 3, 1.80, 'banana'],\n['apple', 'envelope', 'star_fruit', 2, 1.55, 'banana'],\n['apple', 'orange', 'pear', 2, 0.80, 'coffee_cup'],\n['apple', 'orange', 'pear', 2, 3.80, 'coffee_cup']]\n\ndic ...
[ 3, 1, 0 ]
[]
[]
[ "duplicates", "list", "python" ]
stackoverflow_0006735950_duplicates_list_python.txt
Q: Check if classes in modules implement the right interface I have the following interface : class Interface(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def run(self): """Run the process.""" return I have a collections of modules that are all in the same directory. Each mo...
Check if classes in modules implement the right interface
I have the following interface : class Interface(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def run(self): """Run the process.""" return I have a collections of modules that are all in the same directory. Each module contains a single class that implements my interface. For...
[ "You're probably looking for something like this:\nfrom os import listdir\nfrom sys import path\n\nmodpath = \"/path/to/modules\"\n\nfor modname in listdir(modpath):\n if modname.endswith(\".py\"):\n\n # look only in the modpath directory when importing\n oldpath, path[:] = path[:], [modpath]\n\n ...
[ 0 ]
[]
[]
[ "abstract_methods", "introspection", "metaclass", "python" ]
stackoverflow_0006736154_abstract_methods_introspection_metaclass_python.txt
Q: Different instances of A in B (Python) In a situation like this b1 and b2 both have the same instanse of A. class A: def __init__(self): self.var=1 class B: a=A() def __init__(self): pass b1=B() b2=B() b1.a.var=2 #changing "var" in b1 would also change it in b2 print(b2.a.var) # prin...
Different instances of A in B (Python)
In a situation like this b1 and b2 both have the same instanse of A. class A: def __init__(self): self.var=1 class B: a=A() def __init__(self): pass b1=B() b2=B() b1.a.var=2 #changing "var" in b1 would also change it in b2 print(b2.a.var) # prints 2 What should i do to have 2 different ...
[ "With B defined as it is, its attribute a belongs to the class itself, not each individual instance. You would need to do something like this:\nclass B:\n def __init__(self):\n self.a = A()\n\nto get separate instances of A for every B.\n", "You need to initialize it on a per-instance basis instead of a...
[ 6, 2, 2, 2 ]
[]
[]
[ "class", "instance", "python" ]
stackoverflow_0006736318_class_instance_python.txt
Q: how to: Twisted privmsg to accept non-ascii strings I have an IRC bot written in python that uses Twisted. It can print non-ascii strings without a problem with self.msg(channel, str.encode('utf-8'). However, I get exceptions when a non-ascii string is being received with privmsg: def privmsg(self, user, channel, ...
how to: Twisted privmsg to accept non-ascii strings
I have an IRC bot written in python that uses Twisted. It can print non-ascii strings without a problem with self.msg(channel, str.encode('utf-8'). However, I get exceptions when a non-ascii string is being received with privmsg: def privmsg(self, user, channel, msg): msg = msg.encode('utf-8') user = user.split...
[ "I think you want \"decode\", not \"encode\". The argument to privmsg is a byte string (str, in python 2.x), so if you want it to be text you have to de-code those bytes.\nYou can't force the encoding to be UTF-8, because the encoding is whatever you happened to receive from the server. Thanks to IRC's complete l...
[ 3 ]
[]
[]
[ "encoding", "python", "twisted", "unicode" ]
stackoverflow_0006733968_encoding_python_twisted_unicode.txt
Q: How do I make this list function faster? def removeDuplicatesFromList(seq): # Not order preserving keys = {} for e in seq: keys[e] = 1 return keys.keys() def countWordDistances(li): ''' If li = ['that','sank','into','the','ocean'] This function would return: { that:1, san...
How do I make this list function faster?
def removeDuplicatesFromList(seq): # Not order preserving keys = {} for e in seq: keys[e] = 1 return keys.keys() def countWordDistances(li): ''' If li = ['that','sank','into','the','ocean'] This function would return: { that:1, sank:2, into:3, the:4, ocean:5 } However, if ...
[ "import collections\ndef countWordDistances(li):\n wordmap = collections.defaultdict(list)\n for i, w in enumerate(li, 1):\n wordmap[w].append(i)\n for k, v in wordmap.iteritems():\n wordmap[k] = sum(v)/float(len(v))\n\n return wordmap\n\nThis makes only one pass through the list, and keep...
[ 15, 5, 3, 1, 1, 1, 0 ]
[ "Oneliner -\nfrom __future__ import division # no need for this if using py3k\n\ndef countWordDistances(li):\n '''\n If li = ['that','sank','into','the','ocean'] \n This function would return: { that:1, sank:2, into:3, the:4, ocean:5 }\n However, if there is a duplicate term, take the average of th...
[ -1 ]
[ "algorithm", "dictionary", "list", "optimization", "python" ]
stackoverflow_0006728719_algorithm_dictionary_list_optimization_python.txt
Q: Python command execution output Possible Duplicate: Running shell command from python and capturing the output I want to capture the output of a command into a variable, so later that variable can be used again. I need to change this script so it does that: #!/usr/bin/python import os command = raw_input("Enter ...
Python command execution output
Possible Duplicate: Running shell command from python and capturing the output I want to capture the output of a command into a variable, so later that variable can be used again. I need to change this script so it does that: #!/usr/bin/python import os command = raw_input("Enter command: ") os.system(command) If I...
[ "import subprocess\ncommand = raw_input(\"Enter command: \")\np = subprocess.Popen(command, stdout=subprocess.PIPE)\noutput, error = p.communicate()\n\n", "The output of the command can be captured with the subprocess module, specifically, the check_output function..\noutput = subprocess.check_output(\"ls\")\n\nS...
[ 9, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006736627_python.txt
Q: Literal parentheses in postgres query, pgadmin vs. psycopg2 The following query takes out the parentheses from a string, i.e. it regex replaces them with nothing. It works as expected when I test it in pgAdimin III (1.12), but when part of a python script using psycopg2, it does not replace the parentheses at all...
Literal parentheses in postgres query, pgadmin vs. psycopg2
The following query takes out the parentheses from a string, i.e. it regex replaces them with nothing. It works as expected when I test it in pgAdimin III (1.12), but when part of a python script using psycopg2, it does not replace the parentheses at all. SELECT regexp_replace(location.name, '\\(|\\)', '', 'g') A...
[ "Use parametrized arguments:\nsql='SELECT regexp_replace(location, %s, %s, %s) from foo'\ncursor.execute(sql,[r'\\(|\\)','','g'])\n\nFor example:\nimport psycopg2\nconnection=psycopg2.connect(\n database=config.PGDB,\n host=config.HOST,\n password=config.PASS)\ncursor=connection.cursor()\nsql='CREATE TABL...
[ 2 ]
[]
[]
[ "pgadmin", "postgresql", "python" ]
stackoverflow_0006736307_pgadmin_postgresql_python.txt
Q: Python memory management insights -- id() Playing around with id(). Began with looking at the addresses of identical attributes in non-identical objects. But that doesn't matter now, I guess. Down to the code: class T(object): pass class N(object): pass First test (in interactive console): n = N() t = T(...
Python memory management insights -- id()
Playing around with id(). Began with looking at the addresses of identical attributes in non-identical objects. But that doesn't matter now, I guess. Down to the code: class T(object): pass class N(object): pass First test (in interactive console): n = N() t = T() id(n) # prints 4298619728 id(t) # prints 4298...
[ "You asked a lot of questions. I'll do my best to answer some of them, and hopefully you'll be able to figure out the rest (ask if you need help).\nFirst question: explain behaviour of id\n>>> n1 = N()\n>>> n2 = N()\n>>> id(n1) == id(n2)\nFalse\n\nThis shows that Python creates a new object each time you call an ob...
[ 7, 5, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006733477_python.txt
Q: python win32api.LoadKeyboardLayout(), doesnt change language in IDLE shell? Can someone help me out please...I'm trying to start my first programming project. It will be implemented in python. I need to have a textbox (which i am using wxpython for). If the user enters any text into this text box, then I want it ...
python win32api.LoadKeyboardLayout(), doesnt change language in IDLE shell?
Can someone help me out please...I'm trying to start my first programming project. It will be implemented in python. I need to have a textbox (which i am using wxpython for). If the user enters any text into this text box, then I want it to appear as arabic. I wanted to this by automagically changing the users Keyboar...
[ "\nKeyboard layout setting in Windows is per-process (and inherited from the parent process)\nIDLE runs your Python script in a background process separate from its GUI\n\nSo you have successfully changed the keyboard layout of the background Python process that is running your script, but not of IDLE's GUI.\n" ]
[ 5 ]
[]
[]
[ "keyboard", "python", "python_idle", "winapi" ]
stackoverflow_0006725041_keyboard_python_python_idle_winapi.txt
Q: yaml in Google App Engine with index.html I'm building a website, I have no index.py how to I ensure index.html comes up when I type in my http://localhost:8080/? I have in yaml - url: / static_files: static/HTML upload: static/HTML/index.html but this does not seem to work. A: Your static_files directive n...
yaml in Google App Engine with index.html
I'm building a website, I have no index.py how to I ensure index.html comes up when I type in my http://localhost:8080/? I have in yaml - url: / static_files: static/HTML upload: static/HTML/index.html but this does not seem to work.
[ "Your static_files directive needs to include the full path to the file:\nstatic_files: static/HTML/index.html\n\n" ]
[ 11 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006736751_google_app_engine_python.txt
Q: How do python submodules share a scarce resource between them? I am breaking up a large monolothic python file into six separate submodules. Originally in onebigfile.py, I had conn = MySqldb.connect() c = conn.cursor() and then a function would use it as so: def getFromDB(): c.execute(sql) Now, I have restr...
How do python submodules share a scarce resource between them?
I am breaking up a large monolothic python file into six separate submodules. Originally in onebigfile.py, I had conn = MySqldb.connect() c = conn.cursor() and then a function would use it as so: def getFromDB(): c.execute(sql) Now, I have restructured my module to NewModule/ __init__.py users.py accounts...
[ "You can certainly share the connection object between python modules, and your idea to have the connection be a module-scoped variable will accomplish this nicely (with a few exceptions, Python modules are singletons, so even if they are imported multiple times from different files, they are only loaded once). You...
[ 8, 2 ]
[]
[]
[ "namespaces", "python", "python_module" ]
stackoverflow_0006736860_namespaces_python_python_module.txt
Q: PyQT4 installation in nokia n79 I am just newbie to python and now, I am writing an interface in Nokia n79 phone. My question is that is it possible to install PyQt4 in nokia n79 or possible to run PyQt4 in Nokia n79. If yes, how? Is there anyway that I could take as a reference or take as an example. A: There a...
PyQT4 installation in nokia n79
I am just newbie to python and now, I am writing an interface in Nokia n79 phone. My question is that is it possible to install PyQt4 in nokia n79 or possible to run PyQt4 in Nokia n79. If yes, how? Is there anyway that I could take as a reference or take as an example.
[ "There are python packages for symbian, look for python for S60. It's an open source project. Download the sis file to your phone and install it... good luck.\n" ]
[ 0 ]
[]
[]
[ "mobile", "pyqt4", "python", "user_interface" ]
stackoverflow_0006736179_mobile_pyqt4_python_user_interface.txt
Q: Change an object's properties at run time? I have a project in Python 2.7 and wxPython. I have both IDLE and Boa Constructor available as IDEs. I need to change one or more properties of a GUI object, such as a button, at run time - especially size, location, and text (the latter in buttons and labels). How do I c...
Change an object's properties at run time?
I have a project in Python 2.7 and wxPython. I have both IDLE and Boa Constructor available as IDEs. I need to change one or more properties of a GUI object, such as a button, at run time - especially size, location, and text (the latter in buttons and labels). How do I change these properties at run time? Mind you, I'...
[ "@JasonMc92, Yes it is definitely possible to change a wx object's properties (labels, size, position, etc.) on demand within your application. What you need to do is read up on wxPython event handling to know how to catch actions like clicking a button and add your instructions to change your desired properties as...
[ 2, 1 ]
[]
[]
[ "properties", "python", "runtime", "wxpython", "wxwidgets" ]
stackoverflow_0006736195_properties_python_runtime_wxpython_wxwidgets.txt
Q: Have Python 2.7 functions remember value and not reference? Closure Weirdness I'm trying to return from a function a list of functions, each of which uses variables from the outside scope. This isn't working. Here's an example which demonstrates what's happening: a = [] for i in range(10): a.append(lambda x: x...
Have Python 2.7 functions remember value and not reference? Closure Weirdness
I'm trying to return from a function a list of functions, each of which uses variables from the outside scope. This isn't working. Here's an example which demonstrates what's happening: a = [] for i in range(10): a.append(lambda x: x+i) a[1](1) # returns 10, where it seems it should return 2 Why is this happening,...
[ "The i refers to the same variable each time, so i is 9 in all of the lambdas because that's the value of i at the end of the loop. Simplest workaround involves a default argument:\nlambda x, i=i: x+i\n\nThis binds the value of the loop's i to a local variable i at the lambda's definition time.\nAnother workaround ...
[ 11, 4, 2 ]
[]
[]
[ "closures", "functional_programming", "python", "scope" ]
stackoverflow_0006737112_closures_functional_programming_python_scope.txt
Q: Using SWIG to wrap C++ class with virtual methods and overriding them in python I'm trying to "pythonize" method arguments when calling python callback: %module (directors="1") py_test %feature("director") mgr; struct hdr_val { const char *hdr; const char *val; }; struct hdr_...
Using SWIG to wrap C++ class with virtual methods and overriding them in python
I'm trying to "pythonize" method arguments when calling python callback: %module (directors="1") py_test %feature("director") mgr; struct hdr_val { const char *hdr; const char *val; }; struct hdr_list { int count; struct hdr_val *elems; }; struct myinfo...
[ "Ok I've found the answer\nThe typemap should be placed BEFORE class mgr\n%typemap(directorin) myinfo const * {\n $input = Py_BuildValue(\"(iiso)\", $1_name->newcid, $1_name->oldcid, \n $1_name->uri, make_hdrlist(&$1_name->hlist));\n}\n\n" ]
[ 1 ]
[]
[]
[ "c++", "callback", "python", "swig" ]
stackoverflow_0006684253_c++_callback_python_swig.txt
Q: How to unit test a Python function that draws PDF graphics? I'm writing a CAD application that outputs PDF files using the Cairo graphics library. A lot of the unit testing does not require actually generating the PDF files, such as computing the expected bounding boxes of the objects. However, I want to make sure...
How to unit test a Python function that draws PDF graphics?
I'm writing a CAD application that outputs PDF files using the Cairo graphics library. A lot of the unit testing does not require actually generating the PDF files, such as computing the expected bounding boxes of the objects. However, I want to make sure that the generated PDF files "look" correct after I change the c...
[ "(See also update below!)\nI'm doing the same thing using a shell script on Linux that wraps\n\nImageMagick's compare command\nthe pdftk utility\nGhostscript (optionally)\n\n(It would be rather easy to port this to a .bat Batch file for DOS/Windows.)\nI have a few reference PDFs created by my application which are ...
[ 23, 8, 0, 0, 0 ]
[]
[]
[ "cairo", "imagemagick", "pdf_generation", "python", "unit_testing" ]
stackoverflow_0004672945_cairo_imagemagick_pdf_generation_python_unit_testing.txt
Q: Python: GUI for Nokia N79 cell phones Did anybody how to write GUI in Nokia N79 and how ? I mean what packages and something link or tutorial would be helpful. Please. A: Python for symbain OS is also known as PyS60. You need to refer to (the only) book - Mobile Python: Rapid prototyping of applications on th...
Python: GUI for Nokia N79 cell phones
Did anybody how to write GUI in Nokia N79 and how ? I mean what packages and something link or tutorial would be helpful. Please.
[ "Python for symbain OS is also known as PyS60.\nYou need to refer to (the only) book - \nMobile Python: Rapid prototyping of applications on the mobile platform\n\nYou can find lots of examples from the book itself here.\nYou can download PyS60 (SourceForge) and install the interpreter on your symbian phone and y...
[ 1 ]
[]
[]
[ "mobile", "python", "user_interface" ]
stackoverflow_0006737122_mobile_python_user_interface.txt