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: Where should I be looking for reverse tree traversal of an lxml.etree? I'm not sure of the name of the exact type of traversal I want to do, but basically I want to read the document element by element in reverse order from the current element. The iterdescendants() method doesn't seem to do anything, and the iter...
Where should I be looking for reverse tree traversal of an lxml.etree?
I'm not sure of the name of the exact type of traversal I want to do, but basically I want to read the document element by element in reverse order from the current element. The iterdescendants() method doesn't seem to do anything, and the iterancestors() method doesn't walk into the subelements, it just steps up and o...
[ "Maybe something like this?\nimport lxml.etree as et\n\nxmldata = \"\"\"\n<data>\n <mango>1</mango>\n <kiwi>2</kiwi>\n <banana>3</banana>\n <plum>4</plum>\n</data>\n\"\"\"\n\ntree = et.fromstring(xmldata)\n\nel = tree.find('plum')\nprint el.text\n\nwhile True:\n el = el.getprevious()\n if el is No...
[ 0 ]
[]
[]
[ "iterator", "lxml", "python", "tree_traversal" ]
stackoverflow_0007943071_iterator_lxml_python_tree_traversal.txt
Q: pyqt: how to put a border frame around a widget I'm making some changes to an existing PyQt project. The UI was created with Qt Designer. The relevant part is a QWidget that displays text. I'm trying to put margins around the text. I'd think the simplest way to do this would be to put a border around the QWidge...
pyqt: how to put a border frame around a widget
I'm making some changes to an existing PyQt project. The UI was created with Qt Designer. The relevant part is a QWidget that displays text. I'm trying to put margins around the text. I'd think the simplest way to do this would be to put a border around the QWidget whose background color is the same as the QWidget's...
[ "Put your QWidget inside another QWidget with its background set to the same colour.\nYou can then use the layout of the parent QWidget to adjust the width of the margin on each side (this can all be done within Qt Designer).\nEDIT\nHere are the steps to take in Qt Designer to achieve this:\n\nSelect the frame widg...
[ 3 ]
[]
[]
[ "pyqt", "python", "qframe", "qt_designer" ]
stackoverflow_0007942268_pyqt_python_qframe_qt_designer.txt
Q: Python I need to write a loop that creates two seperate running totals, and I don't understand my error I have a homework problem that I cant figure out, can someone help --Create a function called sums that will prompt the user to enter integer values (either positive or negative). The function should keep separa...
Python I need to write a loop that creates two seperate running totals, and I don't understand my error
I have a homework problem that I cant figure out, can someone help --Create a function called sums that will prompt the user to enter integer values (either positive or negative). The function should keep separate running totals of the positive values and the negative values. The user should be allowed to continue ente...
[ "Because they're separate while loops - the first one is executed, then the second one is executed. You don't want that at all. Here's a layout of what you should do:\n\ntake a number from input, store it as inputnum\nwhile inputnum isn't 0\n determine whether inputnum is positive or negative\n add inputnum t...
[ 7 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0007943139_loops_python.txt
Q: Getting text-only content from non-English website I am trying to get the text-only contents of a non-English website. For example, I want to get the hindi contents of http://www.bbc.co.uk/hindi/ For text dump of an English website, I use wget to fetch the contents. Then use an HTML parser for removing the HTML ta...
Getting text-only content from non-English website
I am trying to get the text-only contents of a non-English website. For example, I want to get the hindi contents of http://www.bbc.co.uk/hindi/ For text dump of an English website, I use wget to fetch the contents. Then use an HTML parser for removing the HTML tags and give me clean text. What are the equivalent tools...
[ "It sounds like the method you're using to parse HTML falls down when encountering unicode. There's a module called BeautifulSoup that's great for parsing all manner of websites, and it handles unicode just fine. Try interactively:\n>>> import urllib, BeautifulSoup\n>>> html = urllib.urlopen( 'http://www.bbc.co.uk/...
[ 2 ]
[]
[]
[ "java", "non_english", "python", "web_crawler", "web_scraping" ]
stackoverflow_0007943221_java_non_english_python_web_crawler_web_scraping.txt
Q: How to accept data while sending in my python script? i have this written a server side script and a client script to send messages to each other but each script can only send its message after it has received one,im pretty new to this and im wondering if anyone can help me out so that they can send and receive me...
How to accept data while sending in my python script?
i have this written a server side script and a client script to send messages to each other but each script can only send its message after it has received one,im pretty new to this and im wondering if anyone can help me out so that they can send and receive messages at will. Any help is appreciated. Server script : ht...
[ "I don't have time for a good answer, but the short of it is that you want to use select.select() to see if there's anything going on either on your socket or on stdin.\n" ]
[ 0 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0007942568_python_sockets.txt
Q: Add KML as geometry column in fusion table? I have a CSV file with: area ID area name URL of a KML file with the area boundaries: http://link.to/area_ID.kml How can I load in the KML to a column in the CSV in order to upload it to Fusion Tables? I'm working in Python. The KML is also available as JSON if that h...
Add KML as geometry column in fusion table?
I have a CSV file with: area ID area name URL of a KML file with the area boundaries: http://link.to/area_ID.kml How can I load in the KML to a column in the CSV in order to upload it to Fusion Tables? I'm working in Python. The KML is also available as JSON if that helps. I know that I need to add it as a geometry...
[ "As long as your CSV is valid (for example your kml values are properly quoted), it should load fine. If you believe Refine is the issue, you can skip that and just upload your CSV directly via the fusion tables UI.\n" ]
[ 1 ]
[]
[]
[ "google_fusion_tables", "kml", "python" ]
stackoverflow_0007821005_google_fusion_tables_kml_python.txt
Q: Use a python flickr lib to search images from tags - but without an api key Does anyone know if something like this is possible? Do a quick search, using tags, for public flickr images, but without using an api ley, and retrieve images based on that search? (I already read Why do I need a flickr API key, I want to...
Use a python flickr lib to search images from tags - but without an api key
Does anyone know if something like this is possible? Do a quick search, using tags, for public flickr images, but without using an api ley, and retrieve images based on that search? (I already read Why do I need a flickr API key, I want to know if there are libs that can do this search without it). Or maybe give a rss ...
[ "Sure, seduce a developer on the Flickr dev team and get them to open a back door for you. Or use your mad hax0r skills to do the same, sans seduction.\nSeriously, though, Flickr says you need an API key to use their API. So you get an API key.\nOr you could scrape the entire flickr site, building up your own metad...
[ 2 ]
[]
[]
[ "api", "flickr", "python" ]
stackoverflow_0007943545_api_flickr_python.txt
Q: Make two characters equivalent in a Python find() call Using Python, I want to search for, for example, 'tune yards' in a block of text that may say 'tune-yards' (with a hyphen) and it may say 'tune yards' (without). I want both to be considered matches. I'm using the find() function. Is there a good Pythonic way ...
Make two characters equivalent in a Python find() call
Using Python, I want to search for, for example, 'tune yards' in a block of text that may say 'tune-yards' (with a hyphen) and it may say 'tune yards' (without). I want both to be considered matches. I'm using the find() function. Is there a good Pythonic way to treat - and spaces as one and the same, instead of just s...
[ ">>> re.search('tune[ -]yards', '58 tune yards of music')\n<_sre.SRE_Match object at 0x1ad68b8>\n>>> re.search('tune[ -]yards', '35 tune-yards of trombone')\n<_sre.SRE_Match object at 0x1ad6988>\n\nAnd match objects are always true (with the other possible returned value being None), so the result can be tested via...
[ 4, 0 ]
[]
[]
[ "character", "find", "python", "search", "string" ]
stackoverflow_0007943458_character_find_python_search_string.txt
Q: Python for NLTK in Excel file I would like to analyze text data in an Excel file. I know how I could read an Excel file via Python, but each piece of data becomes one value of a list. However, I would like to analyze text in each cell. Here is my example of the Excel file: NAME INDUSTRY INFO A ...
Python for NLTK in Excel file
I would like to analyze text data in an Excel file. I know how I could read an Excel file via Python, but each piece of data becomes one value of a list. However, I would like to analyze text in each cell. Here is my example of the Excel file: NAME INDUSTRY INFO A FINANCIAL THIS COMPANY IS BL...
[ "You are passing all values in a row to word_tokenize but you are only interested in what is in the 3rd column. You are also processing the header row. Try this:\nimport xlrd\nbook = xlrd.open_workbook(\"your_input_file.xls\")\nsheet = book.sheet_by_index(0)\nfor row_index in xrange(1, sheet.nrows): # skip heading ...
[ 1 ]
[]
[]
[ "nltk", "python" ]
stackoverflow_0007943145_nltk_python.txt
Q: Simple XMPP bot on python I have the simple code of XMPP bot by python and http://xmpppy.sourceforge.net/ #!/usr/bin/python # -*- coding: utf-8 -*- import xmpp import urllib2 import ConfigParser config = ConfigParser.ConfigParser() config.read('ipbot.conf') ########################## user= (config.get('account'...
Simple XMPP bot on python
I have the simple code of XMPP bot by python and http://xmpppy.sourceforge.net/ #!/usr/bin/python # -*- coding: utf-8 -*- import xmpp import urllib2 import ConfigParser config = ConfigParser.ConfigParser() config.read('ipbot.conf') ########################## user= (config.get('account', 'login')) password=(config.ge...
[ "The following code should do it. A few notes:\n\nWokkel uses so-called subprotocol handlers to cover support for specific\nsubprotocols, usually split up by conceptual feature, by namespace or per\nXEP.\nXMPPClient is a so-called stream manager that establishes connections,\nand takes care of authentication with t...
[ 5 ]
[]
[]
[ "bots", "python", "twisted", "xmpp" ]
stackoverflow_0005950156_bots_python_twisted_xmpp.txt
Q: Downsides to reading strings from Excel in python using encode('utf-8') I am reading a large amount of data from an excel spreadsheet in which I read (and reformat and rewrite) from the spreadsheet using the following general structure: book = open_workbook('file.xls') sheettwo = book.sheet_by_index(1) out = open(...
Downsides to reading strings from Excel in python using encode('utf-8')
I am reading a large amount of data from an excel spreadsheet in which I read (and reformat and rewrite) from the spreadsheet using the following general structure: book = open_workbook('file.xls') sheettwo = book.sheet_by_index(1) out = open('output.file', 'w') for i in range(sheettwo.nrows): z = i + 1 topri...
[ "The XLRD Documentation states it clearly: \"From Excel 97 onwards, text in Excel spreadsheets has been stored as Unicode.\". Since you are likely reading in files newer than 97, they are containing Unicode codepoints anyway. It is therefore necessary that keep the content of these cells as Unicode within Python an...
[ 4, 0 ]
[]
[]
[ "character_encoding", "python", "utf_8", "xlrd" ]
stackoverflow_0007748001_character_encoding_python_utf_8_xlrd.txt
Q: i18n breaking turbogears setup -wiki20 tutorial ollowing the 20wiki tutorial as a Turbogears newbie I'm using win7, python 2.7.2 (I guess the my computer locale is hebrew, but for the beginning I was planning on english development) and I think the turbogears version is 2.1.3 when I run the "paster serve --reload ...
i18n breaking turbogears setup -wiki20 tutorial
ollowing the 20wiki tutorial as a Turbogears newbie I'm using win7, python 2.7.2 (I guess the my computer locale is hebrew, but for the beginning I was planning on english development) and I think the turbogears version is 2.1.3 when I run the "paster serve --reload development.ini I get in the localhost:8085 (I change...
[ "this was answered here: TurboGears 2 quickstart shows error immediately\nproblem with webob - you should uninstall with easy install the current webob version (1.2b or something like that) and \neasy_install webob==1.1.1\n\nafter that it'll work\nI also got the following advice in the turbogears google group:\nTo ...
[ 1 ]
[]
[]
[ "pylons", "python", "turbogears2" ]
stackoverflow_0007882071_pylons_python_turbogears2.txt
Q: converting web page scraper from python 2 to python 3 I've a python 2 script to scrape data from a reddit thread, but I've currently got python 3 installed. I've no python knowledge, but have googled that the (initial?) problem is urllib2. Would this be easy to convert to python 3, or would it be better to install...
converting web page scraper from python 2 to python 3
I've a python 2 script to scrape data from a reddit thread, but I've currently got python 3 installed. I've no python knowledge, but have googled that the (initial?) problem is urllib2. Would this be easy to convert to python 3, or would it be better to install python 2? Code here: import urllib2 import json # grab da...
[ "The 2to3 utility that comes with Python will do most of the work for you – call it on your file with the -w argument to convert the file automatically.\nAfter that, you will need to convert raw_data from a byte string to a character string. Use decode right before your json.loads line:\nraw_data = raw_data.decode(...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007944259_python.txt
Q: Python: list.index fails to find existing element Can someone explain to me how the funcion list.index() functions? I have the following code: def getPos(self,tile): print self.tiles[5][5] print tile try: myIndex = self.tiles.index(tile) #some code except: ...
Python: list.index fails to find existing element
Can someone explain to me how the funcion list.index() functions? I have the following code: def getPos(self,tile): print self.tiles[5][5] print tile try: myIndex = self.tiles.index(tile) #some code except: print "exception raised" #some code ...
[ "self.tiles appears to be a sequence (e.g. list or tuple) of sequences. \nElements of self.tiles are sequences, not tiles.\nself.tiles.index(tile) tries to find a sequence which equals tile, and fails.\nTry instead:\ndef getPos(self,tile):\n for i,row in enumerate(self.tiles):\n for j,elt in enumerate(row...
[ 4, 3 ]
[ "How come tiles[5][5] and tile points to the same instance? It appears to me that you grab entire this object at tile[5][5] as tile and try to locate it as an element of it. dont understand your intention\n" ]
[ -1 ]
[ "list", "python" ]
stackoverflow_0007944355_list_python.txt
Q: Custom RTTI for use in script-defined types I'm developing a game engine in C++ that allows Python scripting. Here's an example of how functions can be defined in Python that are then called by the an event manager whenever a certain event occurs: # Import some classes defined in C++ from cpp.event import PlayerDi...
Custom RTTI for use in script-defined types
I'm developing a game engine in C++ that allows Python scripting. Here's an example of how functions can be defined in Python that are then called by the an event manager whenever a certain event occurs: # Import some classes defined in C++ from cpp.event import PlayerDiesEvent, EventManager def onPlayerDeath(event): ...
[ "I'm not familiar with boost::python; it might have some feature that makes this easier. I just know of a custom RTTI system that works pretty well:\nQt has a meta-object system, where reflection and a degree of dynamic behavior is added by having a metaobject associated with each class that knows about that class'...
[ 1 ]
[]
[]
[ "boost_python", "c++", "python", "rtti" ]
stackoverflow_0007943854_boost_python_c++_python_rtti.txt
Q: How to get ready using python 3.X on Mac? I download the python 3.2 on OS X, and I installed in my harddisk. But the problem is , when I go to terminal, I type python... It still shows the old version like this: Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type...
How to get ready using python 3.X on Mac?
I download the python 3.2 on OS X, and I installed in my harddisk. But the problem is , when I go to terminal, I type python... It still shows the old version like this: Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" ...
[ "in your terminal, type python3.\non unix like system, python 2.x is generally the default python version for use by the system. but the language syntax has drastically changed between python 2 and python 3, making the 2 incompatible. thus, you cannot replace python 2 by python 3 on your system or you may completel...
[ 9 ]
[]
[]
[ "development_environment", "macos", "python" ]
stackoverflow_0007944533_development_environment_macos_python.txt
Q: Elegantly changing the color of a plot frame in matplotlib This is a kind of follow-up question to this post, where the coloring of axes, ticks and labels was discussed. I hope it is alright to open a new, extended question for this. Changing the color of a complete frame (ticks and axes) around a double-plot (via...
Elegantly changing the color of a plot frame in matplotlib
This is a kind of follow-up question to this post, where the coloring of axes, ticks and labels was discussed. I hope it is alright to open a new, extended question for this. Changing the color of a complete frame (ticks and axes) around a double-plot (via add_subplot) with axes [ax1, ax2] results in a lot of code. Thi...
[ "Assuming you're using a reasonably up-to-date version of matplotlib (>= 1.0), perhaps try something like this:\nimport matplotlib.pyplot as plt\n\n# Make the plot...\nfig, axes = plt.subplots(nrows=2)\naxes[0].plot(range(10), 'r-')\naxes[1].plot(range(10), 'bo-')\n\n# Set the borders to a given color...\nfor ax in...
[ 32, 27, 10 ]
[]
[]
[ "colors", "matplotlib", "python" ]
stackoverflow_0007778954_colors_matplotlib_python.txt
Q: subprocess.Popen help needed I need to execute a command using subprocess.Popen. The command which I need to run is: ./Test -t -1 Test is an executable file while the other arguments -t and -1 are for enabling the outputs (logs) to the shell. I want to write the output to a log file. Unfortunately I am unable to...
subprocess.Popen help needed
I need to execute a command using subprocess.Popen. The command which I need to run is: ./Test -t -1 Test is an executable file while the other arguments -t and -1 are for enabling the outputs (logs) to the shell. I want to write the output to a log file. Unfortunately I am unable to do it. I tried like this: output ...
[ "try this:\noutput = open(\"outputlog.log\", \"a\")\np = subprocess.Popen([\"./Test\", \"-t\", \"-1\"], stdout=subprocess.PIPE)\noutput.writelines(p.stdout.readlines())\n\n", "Two things might be going wrong:\n\nTest -t -1 may be writing to stderr, not stdout.\noutput may need to be flushed or closed before the b...
[ 1, 0 ]
[]
[]
[ "ipc", "python", "ubuntu" ]
stackoverflow_0007940986_ipc_python_ubuntu.txt
Q: Fetch first n bytes from the URL Is that possible to fetch only a number of bytes from some URL and then close the connection with urllib/urllib2? Or even may be a part from n-th byte to k-th? There is a page on that side and I don't need to load the whole page, only a piece of it. A: You can set the Range heade...
Fetch first n bytes from the URL
Is that possible to fetch only a number of bytes from some URL and then close the connection with urllib/urllib2? Or even may be a part from n-th byte to k-th? There is a page on that side and I don't need to load the whole page, only a piece of it.
[ "You can set the Range header to request a certain range of bytes, but \nyou are dependent on the server to honor the request:\nimport urllib2\nreq = urllib2.Request('http://www.python.org/')\n#\n# Here we request that bytes 18000--19000 be downloaded.\n# The range is inclusive, and starts at 0.\n#\nreq.headers['Ra...
[ 6 ]
[]
[]
[ "python", "urllib", "urllib2" ]
stackoverflow_0007944699_python_urllib_urllib2.txt
Q: What code is executed when a class is being defined? When I import a module that has a class, what code is executed when that class is first read and the class object created? Is there any way I can influence what happens? Edit: I realize my question might be a bit too general... I'm looking for something more lo...
What code is executed when a class is being defined?
When I import a module that has a class, what code is executed when that class is first read and the class object created? Is there any way I can influence what happens? Edit: I realize my question might be a bit too general... I'm looking for something more low-level which will allow me to do introspection from C++. ...
[ "Many possible things can happen. The most basic:\nThe contents of the class block are executed when the it is first read.\nTo see this in action, this example:\nclass Foo(object):\n print \"bar\"\n\n def __init__(self):\n print \"baz\"\n\nWill print bar when the module is imported.\nIf a class has a ...
[ 5, 4, 3, 2, 0 ]
[]
[]
[ "c++", "class", "introspection", "metaprogramming", "python" ]
stackoverflow_0007941660_c++_class_introspection_metaprogramming_python.txt
Q: How to remove all duplicates from list except one element in Python? I already know how to remove all duplicates from List by using set: ls = list(set(ls)) What i want to know is there any way to remove all duplicates except one element instances, as efficient as the method above? ls = [1, 2, 3, 3, 3, 4, 4] #i wa...
How to remove all duplicates from list except one element in Python?
I already know how to remove all duplicates from List by using set: ls = list(set(ls)) What i want to know is there any way to remove all duplicates except one element instances, as efficient as the method above? ls = [1, 2, 3, 3, 3, 4, 4] #i want to keep 4, no matter if it is duplicate but want to remove duplicates f...
[ "One way would be to add back in the extra deleted 4s:\nsl = list(set(ls))\nsl += [4] * (ls.count(4) - 1)\n\nAlternatively, just always append the 4s to the new list:\ns = set()\nsl = []\nfor elem in ls:\n if elem == 4 or elem not in s:\n sl.append(elem)\n s.add(elem)\n\nUsing a set allows constant...
[ 4 ]
[]
[]
[ "list", "performance", "python" ]
stackoverflow_0007944895_list_performance_python.txt
Q: Connection issue with twisted / wokkel when running locally I've created a simple XMPP robot with the twisted/wokkel lib. It works wonderfully when I run it on my local machine connecting to a foreign XMPP server. However, when I run the twisted script from the xmpp machine itself it immediately refuses the connec...
Connection issue with twisted / wokkel when running locally
I've created a simple XMPP robot with the twisted/wokkel lib. It works wonderfully when I run it on my local machine connecting to a foreign XMPP server. However, when I run the twisted script from the xmpp machine itself it immediately refuses the connection (or drops it). I was able to disable TLS on ejabberd, and th...
[ "Sounds like you don't have the Python OpenSSL libs installed or in your python path, try installing python-openssl (Debian/Ubuntu package name) or your server distro equivalent. Twisted starts up without it it just disables TLS and SSL functionality.\nIf you do have Python's OpenSSL libs, it's likely to be a weird...
[ 0, 0 ]
[]
[]
[ "python", "twisted", "wokkel", "xmpp" ]
stackoverflow_0006617687_python_twisted_wokkel_xmpp.txt
Q: Should I ensure that all my web application code is UTF-8? I have a Django site that contains only English language strings. I'll be localising this to other languages. I haven't set any sort of file encoding options. Do need to convert all my Python code to UTF-8? is this a good practice? If so, do I need to actu...
Should I ensure that all my web application code is UTF-8?
I have a Django site that contains only English language strings. I'll be localising this to other languages. I haven't set any sort of file encoding options. Do need to convert all my Python code to UTF-8? is this a good practice? If so, do I need to actually convert the file to be UTF-8 or do I simply need to add thi...
[ "The # coding: utf-8 line is only necessary for files which contain special characters directly. Depending on how you want to achieve l10n, you have to take care how you process the strings.\nIn Python2, you should use unicode() objects, while in Python3, normal str()ings are the thing to use.\n" ]
[ 3 ]
[]
[]
[ "django", "file_encodings", "python", "utf_8" ]
stackoverflow_0007944992_django_file_encodings_python_utf_8.txt
Q: How to handle exceptions with Pyramid transaction manager? I'm building my first Pyramid app (coming from Pylons) and I'm trying to figure out how to handle exceptions with pyramid_tm... For example, in Pylons I would do something like try: Session.add(object) Session.commit() except IntegrityError: Sessi...
How to handle exceptions with Pyramid transaction manager?
I'm building my first Pyramid app (coming from Pylons) and I'm trying to figure out how to handle exceptions with pyramid_tm... For example, in Pylons I would do something like try: Session.add(object) Session.commit() except IntegrityError: Session.rollback() flash("Object already present") but how is thi...
[ "Use Session.flush() instead of Session.commit().\nWith pyramid_tm, you should never (need to) do commit() yourself in request handling code.\n" ]
[ 5 ]
[]
[]
[ "exception_handling", "pyramid", "python", "transactions" ]
stackoverflow_0007943971_exception_handling_pyramid_python_transactions.txt
Q: Server-side COLLADA converter I'm building a web form to accommodate users uploading .obj and .fbx 3D models to a site. We need a server-side solution to convert these files to Collada (dae). It would be massively helpful if someone could point me in the right direction as I have no solid ideas yet on a possible s...
Server-side COLLADA converter
I'm building a web form to accommodate users uploading .obj and .fbx 3D models to a site. We need a server-side solution to convert these files to Collada (dae). It would be massively helpful if someone could point me in the right direction as I have no solid ideas yet on a possible solution. I'd like to hear what othe...
[ "I would use a Python prograam on the server triggered by PHP. I would look around for a Python library for working with Collada files (e.g. http://collada.in4lines.com/) then I would use the FBX Python SDK to convert FBX files to Collada. For OBJ maybe something like http://pygame.org/wiki/OBJFileLoader would be h...
[ 3 ]
[]
[]
[ "3d", "collada", "python", "server_side_scripting", "webgl" ]
stackoverflow_0007930655_3d_collada_python_server_side_scripting_webgl.txt
Q: Find index in SortedCollection I use this implementation of SortedCollection. >>> a = SortedCollection(key=itemgetter(1)) >>> a.insert_right(('A',5)) >>> a.insert_right(('B',3)) >>> a.insert_right(('C',7)) >>> a SortedCollection([('B', 3), ('A', 5), ('C', 7)], key=<operator.itemgetter object at 0x028C99B0>) What ...
Find index in SortedCollection
I use this implementation of SortedCollection. >>> a = SortedCollection(key=itemgetter(1)) >>> a.insert_right(('A',5)) >>> a.insert_right(('B',3)) >>> a.insert_right(('C',7)) >>> a SortedCollection([('B', 3), ('A', 5), ('C', 7)], key=<operator.itemgetter object at 0x028C99B0>) What would be the syntax of finding the i...
[ "Tested:\n[x[0] for x in a].index('A')\n\nSortedCollection behaves much like a list, so it's actually the same syntax as searching in\n[('B', 3), ('A', 5), ('C', 7)]\n\n", "a = SortedCollection(key=itemgetter(1))\na.insert_right(('A',5))\na.insert_right(('B',3))\na.insert_right(('C',7))\n\nprint [y[0] for y in a]...
[ 1, 1 ]
[]
[]
[ "indexing", "python", "sortedcollection" ]
stackoverflow_0007945118_indexing_python_sortedcollection.txt
Q: Python - finding words based on repeated characters specified in a string Let's say I have a list of words: resign resins redyed resist reeded I also have a string ".10.10" I need to iterate through the list and find the words where there are repeated characters in the same locations where there are numbers in the...
Python - finding words based on repeated characters specified in a string
Let's say I have a list of words: resign resins redyed resist reeded I also have a string ".10.10" I need to iterate through the list and find the words where there are repeated characters in the same locations where there are numbers in the string. For instance, the string ".10.10" would find the word 'redyed' since t...
[ "def matches(s, pattern):\n d = {}\n return all(cp == \".\" or d.setdefault(cp, cs) == cs\n for cs, cp in zip(s, pattern))\n\na = [\"resign\", \"resins\", \"redyed\", \"resist\", \"reeded\"]\nprint [s for s in a if matches(s, \".01.01\")]\nprint [s for s in a if matches(s, \".00.0.\")]\n\nprints...
[ 5 ]
[]
[]
[ "character", "python", "string" ]
stackoverflow_0007945232_character_python_string.txt
Q: Compare items of list with each other in Python Consider a list o emails: ['a@amail.com','b@bmail.com','c@cmail.com',...] I want to compare list items with each other. For example emails would be unique. What is the way for compare items of list with each other in Python? A: If you just want to test whether or ...
Compare items of list with each other in Python
Consider a list o emails: ['a@amail.com','b@bmail.com','c@cmail.com',...] I want to compare list items with each other. For example emails would be unique. What is the way for compare items of list with each other in Python?
[ "If you just want to test whether or not there were duplicates in the list, you can use:\nif len(set(list_o_emails)) == len(list_o_emails):\n # all are different\nelse:\n # you had a duplicate\n raise forms.ValidationError # from your comment\n\nsince set will eliminate any duplicates for you and comparing...
[ 3, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007944457_list_python.txt
Q: Implementing a TLV protocol via TCP I'm currently trying to implement a (T)LV protocol to be used on top of TCP. A very early version of this protocol was built by just sending one message per send-recv pair. (i.e. send("message to transmit" -- recv(... )). This is really bad bandwidth-wise - I guess because I'm s...
Implementing a TLV protocol via TCP
I'm currently trying to implement a (T)LV protocol to be used on top of TCP. A very early version of this protocol was built by just sending one message per send-recv pair. (i.e. send("message to transmit" -- recv(... )). This is really bad bandwidth-wise - I guess because I'm sending really small packets. So now I am ...
[ "Doing two sends in a row may result in two actual packets going out, which is not so great. To fix this you can concatenate the two pieces yourself, or use writev (aka \"gather write\"), or TCP_CORK on the first send to prevent it from turning into a packet all by itself.\nAs for the receive side, you should rece...
[ 1 ]
[]
[]
[ "c++", "protocol_buffers", "python", "tcp" ]
stackoverflow_0007940685_c++_protocol_buffers_python_tcp.txt
Q: Why should JavaScript files be localised differently in Django? When localising Django application the makemessages command simply parses all the TXT, HTML and PY files and generates PO files for them but when localising JS files, you need to run the djangojs command. I haven't delved into the Django source to fig...
Why should JavaScript files be localised differently in Django?
When localising Django application the makemessages command simply parses all the TXT, HTML and PY files and generates PO files for them but when localising JS files, you need to run the djangojs command. I haven't delved into the Django source to figure out why this done differently. Could someone explain? I've read ...
[ "The reason why it's handled differently is in the docs. \n\nAdding translations to JavaScript poses some problems:\n\nJavaScript code doesn't have access to a gettext implementation.\nJavaScript code doesn't have access to .po or .mo files; they need to be delivered by the server. \nThe translation catalogs for...
[ 1 ]
[]
[]
[ "django", "localization", "python" ]
stackoverflow_0007945098_django_localization_python.txt
Q: Python - replacing lower case letters >>> import string >>> word = "hello." >>> word2 = word.replace(string.lowercase, '.') >>> print word2 hello. I just want all the lowercase letters to turn into full stops. What am I doing wrong here? A: Use a regular expression: from re import sub print sub("[a-z]", '.', "...
Python - replacing lower case letters
>>> import string >>> word = "hello." >>> word2 = word.replace(string.lowercase, '.') >>> print word2 hello. I just want all the lowercase letters to turn into full stops. What am I doing wrong here?
[ "Use a regular expression:\nfrom re import sub\n\nprint sub(\"[a-z]\", '.', \"hello.\")\n\nstr.replace is looking for the string abcdefghijklmnopqrstuvwxyz to replace it with ., not looking for each individual letter to replace.\n", "you should use string.translate():\n>>> import string\n>>> input = 'abcABCaAbBcC...
[ 5, 4, 3, 2, 1 ]
[]
[]
[ "lowercase", "python", "replace", "string" ]
stackoverflow_0007945487_lowercase_python_replace_string.txt
Q: Preferred Python twitter API? I found at http://dev.twitter.com/pages/libraries#python that there are several Twitter APIs for Python. I've been using python-twitter for a while but never needed the API Search. Now I need to do a job that includes Twitter searches and I see they are not supported by this lib. I wo...
Preferred Python twitter API?
I found at http://dev.twitter.com/pages/libraries#python that there are several Twitter APIs for Python. I've been using python-twitter for a while but never needed the API Search. Now I need to do a job that includes Twitter searches and I see they are not supported by this lib. I wonder know which of the listed ones ...
[ "Twython has proven good for a current project of mine. It seems to be the most up-to-date with the Twitter API.\nIf you need streaming API support I would recommend Tweepy.\n", "I have been using Python Twitter Tools and like it a lot. It still won't handle your search filtering for you, but you would have to do...
[ 18, 1 ]
[]
[]
[ "python", "twitter" ]
stackoverflow_0002322149_python_twitter.txt
Q: python and assigning variable values in if statements I'm somewhat of a beginner in python and I swear I got a very similar program to what I'm doing right now to work. But, for some reason, I can't make it work. I was able to pinpoint my problem and created a fake program to play around with it. Here is what the ...
python and assigning variable values in if statements
I'm somewhat of a beginner in python and I swear I got a very similar program to what I'm doing right now to work. But, for some reason, I can't make it work. I was able to pinpoint my problem and created a fake program to play around with it. Here is what the program: global heading global heading2 global a heading=2...
[ "global statement is meaningless outside of a function. If you want to modify the global variable, instead of introducing a local one, you need to put global inside the function\ndef foo():\n global x\n x = x2\n\nAlso, don't use globals.\n", "The line:\n heading=heading2\n\nCreates a new local variable c...
[ 4, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007945724_python.txt
Q: python create a class with complex numbers i have done this in c++ but i am trying it to python and have difficulties.I did this code: class mycomplex: def __init__(self,real=None,imag=None): self.real=real self.imag=imag def read_data(self): self.real=input("Give the real part :") self.imag=input...
python create a class with complex numbers
i have done this in c++ but i am trying it to python and have difficulties.I did this code: class mycomplex: def __init__(self,real=None,imag=None): self.real=real self.imag=imag def read_data(self): self.real=input("Give the real part :") self.imag=input("Give the imag part :") def addition(self,comp...
[ "Python has implemented complex numbers by default.\nSee here or here or here.\nEdit: Maybe you are interested in the following:\nYour read_data won't work correctly because of the following:\nreal = input(..) creates a new local variable real. You probably want to modify self.real, thus you should write self.real ...
[ 2, 1, 0, 0, -1 ]
[]
[]
[ "python" ]
stackoverflow_0007945730_python.txt
Q: how to get client ip in soap web service method? I'm using soaplib library for SOAP web services, I want to access client's IP Address when client request has been made in my web service method. class HelloWorldService(DefinitionBase): @soap(String, Integer, _returns=Array(String)) def say_hello(self, name...
how to get client ip in soap web service method?
I'm using soaplib library for SOAP web services, I want to access client's IP Address when client request has been made in my web service method. class HelloWorldService(DefinitionBase): @soap(String, Integer, _returns=Array(String)) def say_hello(self, name, times): # here I want to Access client's IP ...
[ "From the make_server I'm assuming you're using BaseHTTPServer or one of the packages that builds on top of it.\nIn your request handling code, you should be able to find a reference to the client socket. Use that to get getsockname() and retrieve the client IP and TCP source port.\nFor example, if the socket refe...
[ 1, 0 ]
[]
[]
[ "python", "soaplib", "web_services" ]
stackoverflow_0006955553_python_soaplib_web_services.txt
Q: Django custom form field initial data I am having trouble understanding how to initialize a custom form field in a django view. For example: http://djangosnippets.org/snippets/907/ from datetime import date, datetime from calendar import monthrange class CreditCardField(forms.IntegerField): @staticmethod ...
Django custom form field initial data
I am having trouble understanding how to initialize a custom form field in a django view. For example: http://djangosnippets.org/snippets/907/ from datetime import date, datetime from calendar import monthrange class CreditCardField(forms.IntegerField): @staticmethod def get_cc_type(number): number = ...
[ "All fields have an 'initial' attribute so you set that even if it's a custom field\nhttps://code.djangoproject.com/browser/django/trunk/django/forms/fields.py#L45\nso you should just be able to overwrite the constructor:\nclass PaymentForm(forms.Form):\n def __init__(self, exp = None, *args, **kwargs):\n ...
[ 8 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0007945898_django_django_forms_django_models_python.txt
Q: python with flashdrives and linux commands I have 2 questions. So i am making a python program that will backup and restore a selected directory for me. This is my first program and i am using easygui as my gui for this program. what i want to know is how i can take a linux command that is executed and display the...
python with flashdrives and linux commands
I have 2 questions. So i am making a python program that will backup and restore a selected directory for me. This is my first program and i am using easygui as my gui for this program. what i want to know is how i can take a linux command that is executed and display the result of that in a msgbox , or would tkinter b...
[ "import commands\nfrom easygui import *\n\noutput = commands.getstatusoutput(\"command\")\nmsgbox(msg=output[1])\n\nThat's how you get the output of a command and show it in a message box.\n" ]
[ 1 ]
[]
[]
[ "easygui", "python", "tkinter", "usb_flash_drive" ]
stackoverflow_0007946156_easygui_python_tkinter_usb_flash_drive.txt
Q: Windows Gstreamer ALSA Alternative? Does anyone know an alternative to ALSA that can be used on windows, with gstreamer, and how to install it, and where to find python bindings for it if it needs it? thanks xxx A: SDL does a decent job of abstracting sound interfaces in a platform-independent way. PyGame contai...
Windows Gstreamer ALSA Alternative?
Does anyone know an alternative to ALSA that can be used on windows, with gstreamer, and how to install it, and where to find python bindings for it if it needs it? thanks xxx
[ "SDL does a decent job of abstracting sound interfaces in a platform-independent way. PyGame contains an interface to SDL and works on many platforms. Such abstraction, of course, sets many limitations, but maybe it will still do for you. \nConverted from a comment.\n", "not sure if this is still relevant, but I ...
[ 3, 1, 0, 0 ]
[]
[]
[ "alsa", "gstreamer", "python", "windows" ]
stackoverflow_0004907828_alsa_gstreamer_python_windows.txt
Q: pyqt: controlling a border widget In pyqt: how to put a border frame around a widget I created a border around a widget. I'd now like to be able to control that border from the underlying program. 1) The base widget has a class name in Qt Designer and uses that class name in the program. How do I give a class na...
pyqt: controlling a border widget
In pyqt: how to put a border frame around a widget I created a border around a widget. I'd now like to be able to control that border from the underlying program. 1) The base widget has a class name in Qt Designer and uses that class name in the program. How do I give a class name to my border widget? 2) I've set bac...
[ "The name of the widget can be set in the Property Editor with the objectName property. The class name (e.g. QWidget) cannot be changed.\nThe background colour can be set using the setStyleSheet method.\nTip: A lot of these kinds of questions can answered by using pyuic4 to convert the ui file to a python module, s...
[ 0 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0007946123_pyqt_python.txt
Q: Is possible to iterate file by two lines? Possible Duplicate: reading lines 2 at a time In python we can iterate over file line by line. But what if i want iterate by two lines? f = open("filename") for line1, line2 in ?? f ??: do_stuff(line1, line2) A: Use the grouper function from the itertools recipes. ...
Is possible to iterate file by two lines?
Possible Duplicate: reading lines 2 at a time In python we can iterate over file line by line. But what if i want iterate by two lines? f = open("filename") for line1, line2 in ?? f ??: do_stuff(line1, line2)
[ "Use the grouper function from the itertools recipes.\nfrom itertools import zip_longest\n\ndef grouper(n, iterable, fillvalue=None):\n \"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return zip_longest(fillvalue=fillvalue, *args)\n\n\nf = open(filename)\nfor line1, line2 in ...
[ 5, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007946372_python.txt
Q: Asynchronously read stdout from subprocess.Popen I am running a sub-program using subprocess.popen. When I start my Python program from the command window (cmd.exe), the program writes some info and dates in the window as the program evolves. When I run my Python code not in a command window, it opens a new comma...
Asynchronously read stdout from subprocess.Popen
I am running a sub-program using subprocess.popen. When I start my Python program from the command window (cmd.exe), the program writes some info and dates in the window as the program evolves. When I run my Python code not in a command window, it opens a new command window for this sub-program's output, and I want to...
[ "Use this:\ncmd = subprocess.Popen([\"c:/flow/flow.exe\"], stdout=subprocess.PIPE)\nfor line in cmd.stdout:\n print line.rstrip(\"\\n\")\ncmd.wait() # you may already be handling this in your current code\n\nNote that you will still have to wait for the sub-program to flush its stdout buffer (which is commonly ...
[ 8, 2, 0 ]
[]
[]
[ "python", "subprocess", "windows" ]
stackoverflow_0001822237_python_subprocess_windows.txt
Q: how to get the version of Selenium RC server I am using selenium2 RC with the python client (selenium.py) and I need to get the version of the selenium on the server. (for example "2rc2","2rc3" etc.) is there any command i can send to the server to get its version? A: I know this was already answered but it may ...
how to get the version of Selenium RC server
I am using selenium2 RC with the python client (selenium.py) and I need to get the version of the selenium on the server. (for example "2rc2","2rc3" etc.) is there any command i can send to the server to get its version?
[ "I know this was already answered but it may help someone else. Another way to get your selenium server's version is right click the selenium-server.jar, and open it was any file archiver software such as 7zip or winrar. There you should find a file called VERSION.txt which will tell you your servers version\n", ...
[ 5, 2 ]
[]
[]
[ "python", "python_2.7", "selenium_rc", "selenium_webdriver" ]
stackoverflow_0006424975_python_python_2.7_selenium_rc_selenium_webdriver.txt
Q: Flask easy_install error windows 7 When I follow the instructions on http://flask.pocoo.org/docs/installation/ I get the following error when I execute 'easy_install' in the windows command line interpreter: error: No urls, filenames, or requirements specified (see --help) Why do I get this error? Btw, I ran ez_s...
Flask easy_install error windows 7
When I follow the instructions on http://flask.pocoo.org/docs/installation/ I get the following error when I execute 'easy_install' in the windows command line interpreter: error: No urls, filenames, or requirements specified (see --help) Why do I get this error? Btw, I ran ez_setup.py and it works because there are e...
[ "That's exactly what's supposed to happen when you run the command easy_install. The Flask installation instructions you link to tell you to type\n> easy_install virtualenv\n\nnot\n> easy_install\n\n" ]
[ 1 ]
[]
[]
[ "flask", "python", "windows", "windows_7" ]
stackoverflow_0007946556_flask_python_windows_windows_7.txt
Q: Download a file part by part in Python 3 I'm using Python 3 to download a file: local_file = open(file_name, "w" + file_mode) local_file.write(f.read()) local_file.close() This code works, but it copies the whole file into memory first. This is a problem with very big files because my program becomes memory hungr...
Download a file part by part in Python 3
I'm using Python 3 to download a file: local_file = open(file_name, "w" + file_mode) local_file.write(f.read()) local_file.close() This code works, but it copies the whole file into memory first. This is a problem with very big files because my program becomes memory hungry. (Going from 17M memory to 240M memory for a...
[ "Try using the method described here:\nLazy Method for Reading Big File in Python?\nI am specifically referring to the accepted answer. Let me also copy it here to ensure complete clarity of response.\n def read_in_chunks(file_object, chunk_size=1024):\n \"\"\"Lazy function (generator) to read a file pie...
[ 3 ]
[]
[]
[ "download", "memory", "packet", "python", "urllib" ]
stackoverflow_0007947087_download_memory_packet_python_urllib.txt
Q: related to freebase library I'm using freebase library to get the article. But it is not working. I'm using this example. http://tinyurl.com/6ynwrbk Can any one fix this error? thanks import freebase query = { "id": "/en/jimi_hendrix", "/common/topic/article": [{ "text": { "maxlength": 400, "...
related to freebase library
I'm using freebase library to get the article. But it is not working. I'm using this example. http://tinyurl.com/6ynwrbk Can any one fix this error? thanks import freebase query = { "id": "/en/jimi_hendrix", "/common/topic/article": [{ "text": { "maxlength": 400, "chars": None } }] } result ...
[ "The error you are getting is MQL complaining that there is no such property \"chars\". It works in the queryeditor because you are using MQL Extensions, a feature that is not currently supported. \nFreebase doesn't store topic descriptions along with the other data due to size issues, but you can use the new Text ...
[ 1, 0, 0 ]
[]
[]
[ "freebase", "python" ]
stackoverflow_0007941210_freebase_python.txt
Q: Rolling statistics for a game I am very new to programming. I have only touched the surface of one language, Python, which is what I am working with at the moment. I am trying to write a program that can display random rolling numbers between a range like 1-100. For lack of being able to explain it, I would rather...
Rolling statistics for a game
I am very new to programming. I have only touched the surface of one language, Python, which is what I am working with at the moment. I am trying to write a program that can display random rolling numbers between a range like 1-100. For lack of being able to explain it, I would rather show a video of what I am looking ...
[ "You haven't formulated your question correctly if people has to watch a Youtube video to understand what you want to do. Without watching the video, I can only assume you want to know how random integers work.\nimport random\n\nx = random.randint(1, 100)\n\nIf you want it rolling, you can simply either make three ...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007947058_python.txt
Q: regarding freebase library (how to use bol (film) title as id?) I'm using freebase library to print the article. All is working fine. But I want to ask something from you. Following example working fine. Suppose I have title like this bol (film). Now I want to use this title like this "id": "/en/bol_(film)",. But ...
regarding freebase library (how to use bol (film) title as id?)
I'm using freebase library to print the article. All is working fine. But I want to ask something from you. Following example working fine. Suppose I have title like this bol (film). Now I want to use this title like this "id": "/en/bol_(film)",. But This is not working. In wikipedia API, We can use this title as bol20...
[ "There is no guarantee that there will be an id /en/foo for a given title \"Foo\". In order to find the correct id for your topic you have to either use the search service to get a list of candidate ids, or use MQL for exact phrase matches.\nSearch\nhttps://www.googleapis.com/freebase/v1-sandbox/search?query=bol\no...
[ 1 ]
[]
[]
[ "freebase", "python" ]
stackoverflow_0007943632_freebase_python.txt
Q: Import a class from a folder at another level I have a python application like this / /crawl.py /crawl/__init__.py /crawl/john.py /tests/test_john.py What I am trying to do, is run the unit test test_john.py which needs to use john.py but it's in another folder. In my tests/test_john.py I get this when I run it ...
Import a class from a folder at another level
I have a python application like this / /crawl.py /crawl/__init__.py /crawl/john.py /tests/test_john.py What I am trying to do, is run the unit test test_john.py which needs to use john.py but it's in another folder. In my tests/test_john.py I get this when I run it Traceback (most recent call last): File "test_joh...
[ "If your root folder is in your pythonpath and you make it an importable package as follows:\n/__init__.py\n/crawl.py\n/crawl/__init__.py\n/crawl/john.py\n/tests/__init__.py\n/tests/test_john.py\n\nyou can do:\nfrom crawl.john import John\n\nor\nfrom ..crawl.john import John\n\n", "If your OS supports it, put a s...
[ 17, 2 ]
[]
[]
[ "import", "python" ]
stackoverflow_0007944054_import_python.txt
Q: Parsing C# in scripting language I'd like to write some simple scripts which will parse C# code and modify it or mayby for the begining, pull some interesting parts. Is there any library for, ex. Python, to do that? I know there are few libraries (in NRefactor there is something to build AST from C#), but i'd like...
Parsing C# in scripting language
I'd like to write some simple scripts which will parse C# code and modify it or mayby for the begining, pull some interesting parts. Is there any library for, ex. Python, to do that? I know there are few libraries (in NRefactor there is something to build AST from C#), but i'd like something for script langs - parse an...
[ "I don't know if this exists for Python. Nor do I understand your \"script\" langauge constraint; Python is a full language.\nOur DMS Software Reengineering Toolkit and its C# Front End can parse C# in its various dialects including C# 4.0, build ASTs, and renerate valid C# code from those ASTs.\nThe DMS machinery...
[ 0 ]
[]
[]
[ "abstract_syntax_tree", "c#", "python" ]
stackoverflow_0007947621_abstract_syntax_tree_c#_python.txt
Q: Finding a pair of entries that are out of order I am trying to create a function that returns the number of pairs that are out of order. For example, this function would return 6 for the argument 'DCBA'. My code so far is: def calc_out_of_order_pairs(s): res = [] sum = 0 for i in s: for j in s:...
Finding a pair of entries that are out of order
I am trying to create a function that returns the number of pairs that are out of order. For example, this function would return 6 for the argument 'DCBA'. My code so far is: def calc_out_of_order_pairs(s): res = [] sum = 0 for i in s: for j in s: res.append(i+j) for test in res: ...
[ ">>> from itertools import combinations\n>>> sum(x>y for x,y in combinations(\"DCBA\",2))\n6\n\nHint: Using combinations like this returns each pair where the first in the pair occurs earlier in the string than the second\n>>> list(combinations(\"DCBA\", 2))\n[('D', 'C'), ('D', 'B'), ('D', 'A'), ('C', 'B'), ('C', '...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0007947939_python.txt
Q: Is there an equivalent to maven/ivy dependency management for python? Is there an equivalent to maven/ivy dependency management for python? I mean, something that will automatically download all my dependencies based on a simple specification (as is done for java ) ? Thanks. A: http://www.pip-installer.org/e...
Is there an equivalent to maven/ivy dependency management for python?
Is there an equivalent to maven/ivy dependency management for python? I mean, something that will automatically download all my dependencies based on a simple specification (as is done for java ) ? Thanks.
[ "http://www.pip-installer.org/en/latest/index.html (Requirements files)\nhttp://www.buildout.org/\n", "I know about Pip, that uses a very simple text format for requirements specification.\n" ]
[ 3, 0 ]
[]
[]
[ "dependencies", "java", "python" ]
stackoverflow_0007947477_dependencies_java_python.txt
Q: urllib2 load part of compressed page I need analogue: urllib2.urlopen(url).read(100) But for compressed pages, like: request = urllib2.Request(url) request.add_header('Accept-encoding', 'gzip') response = urllib2.urlopen(request) buf = StringIO(response.read(100)) gzip.GzipFile(fileobj=buf, mode='r').read() IOEr...
urllib2 load part of compressed page
I need analogue: urllib2.urlopen(url).read(100) But for compressed pages, like: request = urllib2.Request(url) request.add_header('Accept-encoding', 'gzip') response = urllib2.urlopen(request) buf = StringIO(response.read(100)) gzip.GzipFile(fileobj=buf, mode='r').read() IOError: CRC check failed 0xd71b7369L != 0x0L ...
[ "Try using the zlib library instead. Gzip relies on zlib, but introduces file-level compression concept along with CRC checking, and it seems like this is not what you want.\nSee this good HTTP Compression in python article (although the article mentions not to use zlib directly, you should try both and base your ...
[ 0, 0, 0 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0007947784_python_urllib2.txt
Q: Python 'int' object is not subscriptable Im trying to read a file and make sure that each value is in order. I dont think im converting the string into the integer correctly. Here is some of my code. I am also trying to use flags. fileName = input("What file name? ") infile = open(fileName,'r') correct_order_flag ...
Python 'int' object is not subscriptable
Im trying to read a file and make sure that each value is in order. I dont think im converting the string into the integer correctly. Here is some of my code. I am also trying to use flags. fileName = input("What file name? ") infile = open(fileName,'r') correct_order_flag = False i = 0 line = infile.readline() while l...
[ "You are correct - you are indicating with eval(xStr)[i] that eval(xStr) is an array, and thus can be subscripted. What it looks like you may want (since you say you want to convert the string to an int) is just int(xStr), to make that whole line:\nif int(xStr) < i:\n\n", "For starters, you don't read the whole f...
[ 4, 1, 0, 0 ]
[]
[]
[ "python", "scriptable" ]
stackoverflow_0007948159_python_scriptable.txt
Q: Writing a pseudo terminal in python for a web based ubuntu terminal I am interested in writing a web based terminal which can execute and autocomplete the commands in ubuntu terminal. I have fiddled with Anyterm http://www.anyterm.org which uses ROTE: "a simple C library for VT102 terminal emulation" at the backen...
Writing a pseudo terminal in python for a web based ubuntu terminal
I am interested in writing a web based terminal which can execute and autocomplete the commands in ubuntu terminal. I have fiddled with Anyterm http://www.anyterm.org which uses ROTE: "a simple C library for VT102 terminal emulation" at the backend server and javascript/html for the terminal ui. The problem was that I ...
[ "You need to learn the basic terminology first. The shell is the program that interprets your input command lines, such as grep \"foo\" abc.txt. A terminal emulator is a program that mimics a terminal. Terminal is a device with display and keyboard that one \nused in 1970s to access a UNIX mainframe. A pseudotermin...
[ 4, 0 ]
[]
[]
[ "javascript", "pty", "python", "terminal", "unix" ]
stackoverflow_0007948329_javascript_pty_python_terminal_unix.txt
Q: What is causing this GAE error message? I'm migrating a webapp to python 2.7 with GAE and this error message appears: File "/base/python27_runtime/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 129, in _StartResponse raise InvalidResponseError('headers must be str') InvalidResponseError: heade...
What is causing this GAE error message?
I'm migrating a webapp to python 2.7 with GAE and this error message appears: File "/base/python27_runtime/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 129, in _StartResponse raise InvalidResponseError('headers must be str') InvalidResponseError: headers must be str What does it mean? I saw some...
[ "self.response.headers[u'P3P'] = u'CP=HONK'\nTry passing strings here instead of casting to unicode.\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007947438_google_app_engine_python.txt
Q: creating a special kind of merged list within a list in django I'm sure that this is pretty easy to do but I'm not sure how to do it. I have three lists: list1=[a1, a2, a3...], list2=[b1, b2, b3...], and list3=[c1, c2, c3...] I want to pass a list that is a by-item merger of these three: finalList = [[a1, b1, c1,]...
creating a special kind of merged list within a list in django
I'm sure that this is pretty easy to do but I'm not sure how to do it. I have three lists: list1=[a1, a2, a3...], list2=[b1, b2, b3...], and list3=[c1, c2, c3...] I want to pass a list that is a by-item merger of these three: finalList = [[a1, b1, c1,], [a2, b2, c2], [a3, b3, c3]...] How do I do this?
[ "That's what the built-in zip() is for:\nfinal_list = zip(list1, list2, list3)\n\nNote that final_list will actually be a list of tuples, and its length will be the length of the shortest input list.\nThe functions itertools.izip() and itertools.izip_longest() are also noteworthy.\n" ]
[ 8 ]
[]
[]
[ "nested_lists", "python" ]
stackoverflow_0007948479_nested_lists_python.txt
Q: Returning consecutive positive number sequences in a list I need to return the longest sequence of positive numbers in a list. currently I have: def longestSequencePos(nums): longest_sequence = [] current_sequence = [] for obj in nums: if current_sequence and current_sequence[-1]+1 == obj: ...
Returning consecutive positive number sequences in a list
I need to return the longest sequence of positive numbers in a list. currently I have: def longestSequencePos(nums): longest_sequence = [] current_sequence = [] for obj in nums: if current_sequence and current_sequence[-1]+1 == obj: current_sequence.append(obj) else: ...
[ "Look into the maximum subsequence problem.\n", "In python you could: \ndef find_longest_sequence(source_list):\n longest_sequence = []\n current_sequence = []\n\n for obj in source_list:\n if current_sequence and current_sequence[-1]+1 == obj:\n current_sequence.append(obj)\n ...
[ 1, 1 ]
[]
[]
[ "jython", "list", "python" ]
stackoverflow_0007948476_jython_list_python.txt
Q: Scraping With IronPython, Loading Images In C# So I wrote my scraper and passed a C# class (card) into IronPython, which it then happily loaded with what I think is binary image data into a byte[] like so: imageurl = "http://blabla.com/Image.ashx?id=" + card.Id + "&type=card" imageresult = urllib2.urlopen(imageurl...
Scraping With IronPython, Loading Images In C#
So I wrote my scraper and passed a C# class (card) into IronPython, which it then happily loaded with what I think is binary image data into a byte[] like so: imageurl = "http://blabla.com/Image.ashx?id=" + card.Id + "&type=card" imageresult = urllib2.urlopen(imageurl).read() if imageresult == '': print 'Could not ...
[ "It looks like byte[] cannot be persisted. Check out this question:\nNHibernate MappingException: no persister for byte[]\nit may be that you're not getting the same message because it's happening in IronPython not in C#, due to C#'s type checking.\nHere's another link a possible solution by serializing byte[] as A...
[ 1, 0 ]
[]
[]
[ "asp.net_mvc", "image", "ironpython", "python", "web_scraping" ]
stackoverflow_0007936058_asp.net_mvc_image_ironpython_python_web_scraping.txt
Q: How do I define a Python property *outside* of a class definition? I would like to define a Python property outside of a class definition: c = C() c.user = property(lambda self: User.objects.get(self.user_id)) print c.user.email But I get the following error: AttributeError: 'property' object has no attribute 'em...
How do I define a Python property *outside* of a class definition?
I would like to define a Python property outside of a class definition: c = C() c.user = property(lambda self: User.objects.get(self.user_id)) print c.user.email But I get the following error: AttributeError: 'property' object has no attribute 'email' What is the correct syntax for defining a property outside of a cl...
[ "Object instances like c cannot have properties; only classes like C can have properties. So you need to set the property on the class, not the instance, because Python only looks for it on the class:\nC.user = property(lambda self: User.objects.get(self.user_id))\n\n" ]
[ 17 ]
[]
[]
[ "properties", "python" ]
stackoverflow_0007948691_properties_python.txt
Q: Python traceback issue regarding Popen I'm getting this error when running my code: Traceback (most recent call last): File "./autoConnect.py", line 22, in <module> call("wicd-cli -yn " + str(defNum) + " -c") File "/usr/lib/python2.6/subprocess.py", line 470, in call return Popen(*popenargs, **kwargs)....
Python traceback issue regarding Popen
I'm getting this error when running my code: Traceback (most recent call last): File "./autoConnect.py", line 22, in <module> call("wicd-cli -yn " + str(defNum) + " -c") File "/usr/lib/python2.6/subprocess.py", line 470, in call return Popen(*popenargs, **kwargs).wait() File "/usr/lib/python2.6/subprocess...
[ "Is wicd-cli -yn in your path?\nYou get this error if the command is not available.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0007948804_python.txt
Q: Create nested JSON from flat csv Trying to create a 4 deep nested JSON from a csv based upon this example: Region,Company,Department,Expense,Cost Gondwanaland,Bobs Bits,Operations,nuts,332 Gondwanaland,Bobs Bits,Operations,bolts,254 Gondwanaland,Maureens Melons,Operations,nuts,123 At each level I would like to su...
Create nested JSON from flat csv
Trying to create a 4 deep nested JSON from a csv based upon this example: Region,Company,Department,Expense,Cost Gondwanaland,Bobs Bits,Operations,nuts,332 Gondwanaland,Bobs Bits,Operations,bolts,254 Gondwanaland,Maureens Melons,Operations,nuts,123 At each level I would like to sum the costs and include it in the outp...
[ "Here are some hints.\nParse the input to a list of lists with csv.reader:\n>>> rows = list(csv.reader(source.splitlines()))\n\nLoop over the list to buildi up your dictionary and summarize the costs. Depending on the structure you're looking to create the build-up might look something like this:\n>>> summary = []...
[ 8 ]
[]
[]
[ "csv", "flat", "json", "nested", "python" ]
stackoverflow_0007948709_csv_flat_json_nested_python.txt
Q: Simple streaming video object recognition I'm doing a project where I want to count things in a video based on their colour. For example, I might want to roll marbles past a camera and have a computer count how many green ones there are, and how often they come past. More specifically, I want to take a video (in ...
Simple streaming video object recognition
I'm doing a project where I want to count things in a video based on their colour. For example, I might want to roll marbles past a camera and have a computer count how many green ones there are, and how often they come past. More specifically, I want to take a video (in practice this will be a streamed video) and ide...
[ "Since you specified Python, you might want to have a look at OpenCV which has a Python interface. \n" ]
[ 1 ]
[]
[]
[ "computer_vision", "image_processing", "python", "video_processing", "video_streaming" ]
stackoverflow_0007948869_computer_vision_image_processing_python_video_processing_video_streaming.txt
Q: Add two lists in Python I am trying to add together two lists so the first item of one list is added to the first item of the other list, second to second and so on to form a new list. Currently I have: def zipper(a,b): list = [a[i] + b[i] for i in range(len(a))] print 'The combined list of a and b is' ...
Add two lists in Python
I am trying to add together two lists so the first item of one list is added to the first item of the other list, second to second and so on to form a new list. Currently I have: def zipper(a,b): list = [a[i] + b[i] for i in range(len(a))] print 'The combined list of a and b is' print list a = input("\n\nI...
[ "Zip first, then add (only not).\n['%s+%s' % x for x in zip(a, b)]\n\n", "What you should do\nYou should use \nlist = [str(a[i]) +\"+\"+ str(b[i]) for i in range(len(a))]\ninstead of \nlist = [str(a[i]) + str(b[i]) for i in range(len(a))]\n\nIn your version, you never say that you want the plus character in the o...
[ 9, 3 ]
[]
[]
[ "int", "list", "python", "string" ]
stackoverflow_0007948941_int_list_python_string.txt
Q: Django: static files in a 404 template How to include stylesheets and images into a 404 page template using the default view? I created a 404.html file in the root of the site's templates directory: <!DOCTYPE html> <html> <head> {% load static %} <link rel="stylesheet" href="{% get_static_prefix %}css/404....
Django: static files in a 404 template
How to include stylesheets and images into a 404 page template using the default view? I created a 404.html file in the root of the site's templates directory: <!DOCTYPE html> <html> <head> {% load static %} <link rel="stylesheet" href="{% get_static_prefix %}css/404.css" /> </head> <body class="page-404"> ...
[ "It appears, staticfiles app does work with DEBUG = False. Only it doesn’t pick up files from individual apps’ static directories. It would serve files from the global STATIC_ROOT directory (from settings.py).\nTo get the static files copied to STATIC_ROOT, you need to run the collectstatic command:\npython manage....
[ 2, 0, 0 ]
[]
[]
[ "django", "django_staticfiles", "django_templates", "python", "static_files" ]
stackoverflow_0007946180_django_django_staticfiles_django_templates_python_static_files.txt
Q: How do I write the date to a .txt? I am trying to write the date to a .txt file. The following is the code that I have made to do this but it always gives me an error. import datetime mylist = [] today = datetime.date.today() mylist.append(today) print mylist[0] file = open('Date.txt', 'a') file.write(mylist) fi...
How do I write the date to a .txt?
I am trying to write the date to a .txt file. The following is the code that I have made to do this but it always gives me an error. import datetime mylist = [] today = datetime.date.today() mylist.append(today) print mylist[0] file = open('Date.txt', 'a') file.write(mylist) file.close() This code gives me the follo...
[ "File#write expects a string, not a list. Try file.write(repr(mylist)).\n", "You can only write strings, it is stated in the error.\nSo you can do this to write the liste (converted in string) into the txt file:\nfile.write(str(mylist))\n\nSimple example\n>>> a= [1,2,3]\n>>> b = str(a)\n>>> b\n'[1, 2, 3]'\n>>> f ...
[ 1, 1, 1 ]
[]
[]
[ "datetime", "list", "python", "text_files" ]
stackoverflow_0007949047_datetime_list_python_text_files.txt
Q: Hachoir Parser in Android I need to implement the Hachoir framework in the android phone. I am lost as to where to start and how to go about understanding the framework. Is there anyway to call the python files into my android code or some other documentation which will help me get started ? I appreciate the help ...
Hachoir Parser in Android
I need to implement the Hachoir framework in the android phone. I am lost as to where to start and how to go about understanding the framework. Is there anyway to call the python files into my android code or some other documentation which will help me get started ? I appreciate the help !
[ "You asked a general question, so the best I can do is give you a general answer. On android, you can't execute python as far as I know. The only thing that comes close is Android Scripting Environment.\n" ]
[ 1 ]
[]
[]
[ "android", "hachoir_parser", "python" ]
stackoverflow_0007949081_android_hachoir_parser_python.txt
Q: python datetime, convert weekday's abbrv to number? How would i go about converting a weekday abbreviation (%a) into the weekday number (%u) using python datetime module? A: >>> import calendar >>> zip(list(calendar.day_abbr), range(7)) [('Mon', 0), ('Tue', 1), ('Wed', 2), ('Thu', 3), ('Fri', 4), ('Sat', 5), ('S...
python datetime, convert weekday's abbrv to number?
How would i go about converting a weekday abbreviation (%a) into the weekday number (%u) using python datetime module?
[ ">>> import calendar\n>>> zip(list(calendar.day_abbr), range(7))\n[('Mon', 0), ('Tue', 1), ('Wed', 2), ('Thu', 3), ('Fri', 4), ('Sat', 5), ('Sun', 6)]\n\n", "Better use the time.strptime function, which depends on the locale. If it is set to English (usually by default), you should get\n>>> import time \n>>> time...
[ 6, 2, 1 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0006252588_datetime_python.txt
Q: parse .xml with prefix's on tags? xml.etree.ElementTree I can read tags, except when there is a prefix. I'm not having luck searching SO for a previous question. I need to read media:content. I tried image = node.find("media:content"). Rss input: <channel> <title>Popular Photography in the last 1 week</title> ...
parse .xml with prefix's on tags? xml.etree.ElementTree
I can read tags, except when there is a prefix. I'm not having luck searching SO for a previous question. I need to read media:content. I tried image = node.find("media:content"). Rss input: <channel> <title>Popular Photography in the last 1 week</title> <item> <title>foo</title> <media:category label="Mis...
[ "Here's an example of using XML namespaces with ElementTree:\n>>> x = '''\\\n<channel xmlns:media=\"http://www.w3.org/TR/html4/\">\n <title>Popular Photography in the last 1 week</title>\n <item>\n <title>foo</title>\n <media:category label=\"Miscellaneous\">photography/misc</media:category>\n <media:co...
[ 5, 0 ]
[]
[]
[ "python", "xml", "xml.etree" ]
stackoverflow_0007949092_python_xml_xml.etree.txt
Q: Python global namespaces and evaluation order Try this out: A = 1 B = 2 C = A + B def main(): global C print A The output of main() is 1. Why is this? Why should main get to know about the other global variables used to evaluate C? A: Global variables are always available to all local scopes in Python,...
Python global namespaces and evaluation order
Try this out: A = 1 B = 2 C = A + B def main(): global C print A The output of main() is 1. Why is this? Why should main get to know about the other global variables used to evaluate C?
[ "Global variables are always available to all local scopes in Python, including functions. In this case, within main() A, B, and C are all in scope.\nThe global keyword doesn't do what it seems you think it does; rather, it permits a local scope to manipulate a global function (it makes global variables \"writable\...
[ 8, 4 ]
[]
[]
[ "global", "namespaces", "python" ]
stackoverflow_0007949184_global_namespaces_python.txt
Q: Native Java / Python / Objective C in Firefox? Is it possible to integrate Java, Python, or Objective C directly with the Firefox browser? In particular to do "real", native tasks such as writing files or connecting to a local database, or better yet, directly calling systems level code ? Notably, there is a po...
Native Java / Python / Objective C in Firefox?
Is it possible to integrate Java, Python, or Objective C directly with the Firefox browser? In particular to do "real", native tasks such as writing files or connecting to a local database, or better yet, directly calling systems level code ? Notably, there is a post on native code execution, somewhat slanted toward...
[ "A \"signed\" Java applet, given the correct permissions and approved by the user, can run in the browser context and have access to files or databases. However, Java applets in the browser are almost never used today (I've had Java disabled in my browser for years).\nMicrosoft browsers offer ActiveX, which is a wa...
[ 3, 3, 2, 0 ]
[]
[]
[ "c++", "firefox_addon", "java", "python" ]
stackoverflow_0007747556_c++_firefox_addon_java_python.txt
Q: Filtering a list of images by using a filter and association lists I've got an assignment and part of it asks to define a process_filter_description. Basically I have a list of images I want to filter: images = ["1111.jpg", "2222.jpg", "circle.JPG", "square.jpg", "triangle.JPG"] Now I have an association list tha...
Filtering a list of images by using a filter and association lists
I've got an assignment and part of it asks to define a process_filter_description. Basically I have a list of images I want to filter: images = ["1111.jpg", "2222.jpg", "circle.JPG", "square.jpg", "triangle.JPG"] Now I have an association list that I can use to filter the images: assc_list = [ ["numbers", ["1111.jpg",...
[ "Instead of an \"associative list\", how about using a dictionary?\nfilter_assoc = {'numbers': ['1111.jpg', '2222.jpg'] ,\n 'shapes': ['circle.JPG', 'square.jpg', 'triangle.JPG']}\n\nNow, just see which images are in each group:\n>>> filter_assoc['numbers']\n['1111.jpg', '2222.jpg']\n>>>\n>>> filter...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0007949383_python.txt
Q: Python function that will return a count (int) representing the longest consecutive sequence of positive numbers in array The return value must be 0 or positive representing the length of the sequence. Let's call the function longestSequencePos(), with one argument (nums). And if you would comment out each se...
Python function that will return a count (int) representing the longest consecutive sequence of positive numbers in array
The return value must be 0 or positive representing the length of the sequence. Let's call the function longestSequencePos(), with one argument (nums). And if you would comment out each section so I can understand it.
[ "def countLongestSequence(nums):\n countMax=0\n count=0\n for i in range(0, len(nums)+1):\n if i == len(nums) or nums[i] <= 0:\n if count > countMax:\n countMax=count\n count=0\n else: ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0007949396_python.txt
Q: Large lists of numbers I have to do calculations with the numbers from a text file, with the text file containing around 24,000 floats, and I have used this to read the lines from the text file into a list: returns = open('trader.txt', 'r').readlines() Should the name of the list now be returns? I ask this becaus...
Large lists of numbers
I have to do calculations with the numbers from a text file, with the text file containing around 24,000 floats, and I have used this to read the lines from the text file into a list: returns = open('trader.txt', 'r').readlines() Should the name of the list now be returns? I ask this because I used simply print retur...
[ "Save these two lines as text file with extention of py, such as calc.py\nreturns = open('trader.txt', 'r').readlines()\nprint returns \n\nthen goto that black window and type python calc.py It should work if you have python on your machine.\n", "Your two line program is fine and should work. If it isn't working...
[ 0, 0 ]
[]
[]
[ "floating_point", "list", "python", "sum" ]
stackoverflow_0007949366_floating_point_list_python_sum.txt
Q: fast data comparison in python I want to compare a large set of data in the form of 2 dictionaries of varying lengths. (edit) post = {0: [0.96180319786071777, 0.37529754638671875], 10: [0.20612385869026184, 0.17849941551685333], 20: [0.20612400770187378, 0.17510984838008881],...} pre = {0: [0.96...
fast data comparison in python
I want to compare a large set of data in the form of 2 dictionaries of varying lengths. (edit) post = {0: [0.96180319786071777, 0.37529754638671875], 10: [0.20612385869026184, 0.17849941551685333], 20: [0.20612400770187378, 0.17510984838008881],...} pre = {0: [0.96180319786071777, 0.37529754638671875...
[ "This is basically what sets are designed for (computing differences in sets of items). The only gotcha is that the things you put into a set need to be hashable, and lists aren't. However, tuples are, so if you convert to that, you can put those into a set:\npost_set = set(tuple(x) for x in post.itervalues())\npre...
[ 5, 1 ]
[]
[]
[ "comparison", "dictionary", "list", "python" ]
stackoverflow_0007949635_comparison_dictionary_list_python.txt
Q: HTML Parser In Python without fixing HTML I need to parse through html but I do not need the python parsing library to attempt to "fix" the html. Any suggestions on a tool or method to use (in python)? In my situation, if the html is malformed then my script needs to end the processing. I tried BeautifulSoup but i...
HTML Parser In Python without fixing HTML
I need to parse through html but I do not need the python parsing library to attempt to "fix" the html. Any suggestions on a tool or method to use (in python)? In my situation, if the html is malformed then my script needs to end the processing. I tried BeautifulSoup but it fixed things that I did not want it to fix. I...
[ "The book Foundations of Python Network Programming has a detailed comparison of what it looks like to scrape the same web page with Beautiful Soup and with the lxml library; but, in general, you will find that lxml is faster, more effective, and has an API which adheres closely to a Python standard (the ElementTre...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007949540_python.txt
Q: find a matching line in a txt with python I can test whether a string is in a text file with python like the following: if(pdfname in open(filename).read()): //do something But how I can I verify it? I want the matching line show up. Thanks. A: Just loop over the file: handle = open(filename, 'r') for line ...
find a matching line in a txt with python
I can test whether a string is in a text file with python like the following: if(pdfname in open(filename).read()): //do something But how I can I verify it? I want the matching line show up. Thanks.
[ "Just loop over the file:\nhandle = open(filename, 'r')\n\nfor line in handle:\n if pdfname in line:\n print line\n\nhandle.close()\n\n", "You can print out the relevant lines with the second for statement below, which I've added to your existing code for illustration:\npdfname = \"statementConcentrator\"\nif...
[ 1, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0007949739_python_string.txt
Q: Fast, thread-safe Python ORM? Can you recommend a high-performance, thread-safe and stable ORM for Python? The data I need to work with isn't complex, so SQLAlchemy is probably an overkill. A: If you are looking for something thats high performance, and based on one of your comments "something that can handle >5...
Fast, thread-safe Python ORM?
Can you recommend a high-performance, thread-safe and stable ORM for Python? The data I need to work with isn't complex, so SQLAlchemy is probably an overkill.
[ "If you are looking for something thats high performance, and based on one of your comments \"something that can handle >5k queries per second\". You need to keep in mind that an ORM is not built specifically for speed and performance, it is built for maintainability and ease of use. If the data is so basic that ev...
[ 6, 6, 1, 0 ]
[]
[]
[ "orm", "python" ]
stackoverflow_0003607285_orm_python.txt
Q: Trying to split on ":" and "," in Python, but failing with ValueError I have a file that I'm reading in and splitting and pushing into a dictionary. I keep getting an error and I think its because the street addresses contain a comma (,). Here is my file contents: axe99:315 W. 115th Street, Apt. 11B:New York:NY:1...
Trying to split on ":" and "," in Python, but failing with ValueError
I have a file that I'm reading in and splitting and pushing into a dictionary. I keep getting an error and I think its because the street addresses contain a comma (,). Here is my file contents: axe99:315 W. 115th Street, Apt. 11B:New York:NY:10027 jab44:23 Rivington Street, Apt. 3R:New York:NY:10002 ap172:19 Boxer Rd...
[ "You are getting the error because you are trying to push a list with 5 items into a dictionary constructor when it only takes two items (in the dict constructor python thinks you are using):\nhere is a list of possible constructors \ndict(one=1, two=2)\ndict({'one': 1, 'two': 2})\ndict(zip(('one', 'two'), (1, 2))...
[ 3, 1, 1, 0 ]
[]
[]
[ "python", "split" ]
stackoverflow_0007949986_python_split.txt
Q: strip ' from all members in a list Ok, so I converted each line in a text file into a member of a list by doing the following: chkseq=[line.strip() for line in open("sequence.txt")] So when I print chkseq I get this: ['3','3'] What I would like is for it to instead look like this: [3,3] I know this is possibl...
strip ' from all members in a list
Ok, so I converted each line in a text file into a member of a list by doing the following: chkseq=[line.strip() for line in open("sequence.txt")] So when I print chkseq I get this: ['3','3'] What I would like is for it to instead look like this: [3,3] I know this is possible, I'm just unsure of how! I need them t...
[ "It looks like you want to interpret the strings as integers. Use int to do this:\nchkseq = [int(line) for line in open(\"sequence.txt\")] \n\nIt can also be written using map instead of a list comprehension:\nchkseq = map(int, open(\"sequence.txt\"))\n\n", "iterate over the elements of your list and print them o...
[ 2, 1, 0, 0 ]
[]
[]
[ "formatting", "list", "python", "strip" ]
stackoverflow_0007950124_formatting_list_python_strip.txt
Q: Using pcolor to plot 3 arrays in python I read an satellite image, and got the data, lat and lon out of the image and put in an array. The dimension of the lat is (135,90) and lon is also (135,90). The dimension of the data was originally (135,90,4,9,8), which 4 represent the band of the image. After processing( w...
Using pcolor to plot 3 arrays in python
I read an satellite image, and got the data, lat and lon out of the image and put in an array. The dimension of the lat is (135,90) and lon is also (135,90). The dimension of the data was originally (135,90,4,9,8), which 4 represent the band of the image. After processing( which used a for loop to put all band in a sin...
[ "its me again... The documentation for matplotlib says here http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.pcolor that \n\nX and Y, if given, specify the (x, y) coordinates of the colored quadrilaterals; the quadrilateral for C[i,j] has corners at:\n\n (X[i, j], Y[i, j]),\n (X[...
[ 0 ]
[]
[]
[ "image_processing", "matplotlib", "numpy", "python" ]
stackoverflow_0007948510_image_processing_matplotlib_numpy_python.txt
Q: How to protect againt typos when setting value for class members? Consider the following example: class A(): def __init__(self): self.veryImportantSession = 1 a = A() a.veryImportantSession = None # ok # 200 lines below a.veryImportantSessssionnnn = 2 # I wanna exception here!! It is typo! How could...
How to protect againt typos when setting value for class members?
Consider the following example: class A(): def __init__(self): self.veryImportantSession = 1 a = A() a.veryImportantSession = None # ok # 200 lines below a.veryImportantSessssionnnn = 2 # I wanna exception here!! It is typo! How could I make it so that an exception will be raised if I try to set a member...
[ "You could override __setattr__ to only allow attribute names from a defined list.\nclass A(object):\n def __setattr__(self, name, value):\n allowed = ('x',)\n if name in allowed:\n self.__dict__[name] = value\n else:\n raise AttributeError('No attribute: %s' % name) \...
[ 7, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003079306_python.txt
Q: Find if a date is included in a copyright For validation, I need to see if a copyright line contains a 4-digit date. This would be a valid copyright: Copyright 2005, Fox However, this would not: Copyright Fox How could I use regular expressions to check if a string contains a four-digit date? Thank you. A: I w...
Find if a date is included in a copyright
For validation, I need to see if a copyright line contains a 4-digit date. This would be a valid copyright: Copyright 2005, Fox However, this would not: Copyright Fox How could I use regular expressions to check if a string contains a four-digit date? Thank you.
[ "I would use...\n\"Copyright @2003, Billy Moon\".match(/copyright\\W+\\d{4}/i)\n\nWhich means the word copyright followed by 1 or more non-word characters (\\W+) followed by four digits (\\d{4}) insensitive to case (i)\n", "m = re.group('[0-2][0-9][0-9][0-9]', copyright)\ntry:\n m.group(0)\nexcept AttributeErr...
[ 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007950497_python_regex.txt
Q: Is having multiple SQLAlchemy sessions in the same controller okay, or should I put them all into one session? So I have a controller that renders a page. In the controller, I call multiple functions from the model that create its own sessions. For example: def page(request): userid = authenticated_userid(requ...
Is having multiple SQLAlchemy sessions in the same controller okay, or should I put them all into one session?
So I have a controller that renders a page. In the controller, I call multiple functions from the model that create its own sessions. For example: def page(request): userid = authenticated_userid(request) user = User.get_by_id(userid) things = User.get_things() return {'user': user, 'things': things} ...
[ "Your first code is OK, if your DBSession is a ScopedSession. DBSession() is not a constructor then, but just an accessor function to thread-local storage. You might speed up things a bit by passing the session explicitly, but premature optimization is the root of all evil.\n" ]
[ 6 ]
[]
[]
[ "pyramid", "python", "sqlalchemy" ]
stackoverflow_0007950716_pyramid_python_sqlalchemy.txt
Q: How does the max() function work in Jython? I need this function to tell me the longest sequence of positive numbers in a list. def longestSequencePos(nums): index = 0 list = [] integ = 0 for obj in nums: if obj > 0: index = index +1 else: list.append(index) in...
How does the max() function work in Jython?
I need this function to tell me the longest sequence of positive numbers in a list. def longestSequencePos(nums): index = 0 list = [] integ = 0 for obj in nums: if obj > 0: index = index +1 else: list.append(index) index = 0 return max(list) list should contain...
[ "you are not appending anything to your list when you are exiting the loop and nums only has positive integers, you will need to do something like:\ndef longestSequencePos(nums): \n index = 0\n list = []\n integ = 0 \n\n for obj in nums:\n if obj > 0:\n index = index +1\n else: ...
[ 2, 1, 0 ]
[]
[]
[ "jython", "list", "python" ]
stackoverflow_0007949851_jython_list_python.txt
Q: Finding the static attributes of a class in Python This is an unusual question, but I'd like to dynamically generate the __slots__ attribute of the class based on whatever attributes I happened to have added to the class. For example, if I have a class: class A(object): one = 1 two = 2 __slots__ = ['o...
Finding the static attributes of a class in Python
This is an unusual question, but I'd like to dynamically generate the __slots__ attribute of the class based on whatever attributes I happened to have added to the class. For example, if I have a class: class A(object): one = 1 two = 2 __slots__ = ['one', 'two'] I'd like to do this dynamically rather than...
[ "At the point you're trying to define slots, the class hasn't been built yet, so you cannot define it dynamically from within the A class.\nTo get the behaviour you want, use a metaclass to introspect the definition of A and add a slots attribute.\nclass MakeSlots(type):\n\n def __new__(cls, name, bases, attrs):...
[ 3, 1 ]
[]
[]
[ "class_design", "python" ]
stackoverflow_0000667166_class_design_python.txt
Q: Python socket error resilience / workaround I have a script running that is testing a series of urls for availability. This is one of the functions. def checkUrl(url): # Only downloads headers, returns status code. p = urlparse(url) conn = httplib.HTTPConnection(p.netloc) conn.request('HEAD', p.path) ...
Python socket error resilience / workaround
I have a script running that is testing a series of urls for availability. This is one of the functions. def checkUrl(url): # Only downloads headers, returns status code. p = urlparse(url) conn = httplib.HTTPConnection(p.netloc) conn.request('HEAD', p.path) resp = conn.getresponse() return resp.stat...
[ "If you just want to handle this Network is unreachable 101, and let other exceptions throw an error, you can do following for example.\nfrom errno import ENETUNREACH\n\ntry:\n # tricky code goes here\n\nexcept IOError as e:\n # an IOError exception occurred (socket.error is a subclass)\n if e.errno == ENE...
[ 5, 4, 0 ]
[]
[]
[ "networking", "python", "sockets" ]
stackoverflow_0007950759_networking_python_sockets.txt
Q: list.append(something) unicode - ascii code a = "한글" #korean language a_list = [] a_list.append({'key': a}) print a_list result [{'key': u'"\ud55c\uae00"'}] I don't want to convert unicode. How can I stay in korean language I wish to print like this [{'key': '한글'}] A: Your code from the question produces:...
list.append(something) unicode - ascii
code a = "한글" #korean language a_list = [] a_list.append({'key': a}) print a_list result [{'key': u'"\ud55c\uae00"'}] I don't want to convert unicode. How can I stay in korean language I wish to print like this [{'key': '한글'}]
[ "Your code from the question produces:\n[{'key': '\\xed\\x95\\x9c\\xea\\xb8\\x80'}]\n\nThis output is different from what you have shown in the question.\nTo produce: [{\"key\": \"한글\"}] you could use json:\nprint json.dumps(a_list, ensure_ascii=False, encoding=your_source_code_encoding)\n\nFull example\n#!/usr/bin...
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007949605_python.txt
Q: Create a graph in a TKinter window? I'm working on writing a script that will run through data and create a graph. That is easy and done. Unfortunately the graphing modules I am using only create the graphs in a pdf format. I would like to have the graphs displayed in an interactive window, though. Is their any wa...
Create a graph in a TKinter window?
I'm working on writing a script that will run through data and create a graph. That is easy and done. Unfortunately the graphing modules I am using only create the graphs in a pdf format. I would like to have the graphs displayed in an interactive window, though. Is their any way to either add a graph created with PyX ...
[ "You need to convert the PyX output into a bitmap to include it in your Tkinter application. While there is no convenience method to get the PyX output as a PIL image directly, you can use the pipeGS method to prepare the bitmap and load it using the PIL. Here comes a rather minimal example:\nimport tempfile, os\n\...
[ 3 ]
[]
[]
[ "python", "pyx", "tkinter" ]
stackoverflow_0007950137_python_pyx_tkinter.txt
Q: Eclipse + Jython: Python module not found using one-to-one object factory I'm trying to get an Eclipse Java project using a Python module (in Eclipse) running, but I keep getting an error saying my Python module can't be found. I'm following the approach explained in The Definitive Guide to Python, "More Detailed ...
Eclipse + Jython: Python module not found using one-to-one object factory
I'm trying to get an Eclipse Java project using a Python module (in Eclipse) running, but I keep getting an error saying my Python module can't be found. I'm following the approach explained in The Definitive Guide to Python, "More Detailed One-to-One Object Factories". I think there's a problem with my project configu...
[ "For PyDev, in a Java project, you have to add the bin folder to the PYTHONPATH (i.e.: the folder with the .class files and not the one with the .java files). \nSee: http://pydev.org/manual_101_project_conf2.html (the last part) for a proper reference.\n" ]
[ 0 ]
[]
[]
[ "eclipse", "java", "jython", "pydev", "python" ]
stackoverflow_0007946700_eclipse_java_jython_pydev_python.txt
Q: Monitoring CPU Usage in App Engine with Python Is there a way to get the current cpu quota of app engine in python? (The value of CPU Time in the Dashboard Screen of Administrator Console) Thx in advance A: http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/api/quota.py If that ...
Monitoring CPU Usage in App Engine with Python
Is there a way to get the current cpu quota of app engine in python? (The value of CPU Time in the Dashboard Screen of Administrator Console) Thx in advance
[ "http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/api/quota.py\nIf that class is limited, then use trial and error or Jython (slow). \nIt appears to do what you want, though:\nimport logging\nfrom google.appengine.api import quota\n\nstart = quota.get_request_cpu_usage()\ndo_some...
[ 2 ]
[]
[]
[ "google_app_engine", "python", "quota" ]
stackoverflow_0007951659_google_app_engine_python_quota.txt
Q: DBus object error I'm trying to make a script to launch my custom script when my usb stick connected. I found nice python script here but when it calls GetAllProperties() method I get an exception: ERROR:dbus.connection:Exception in handler for D-Bus signal: Traceback (most recent call last): File "/usr/lib...
DBus object error
I'm trying to make a script to launch my custom script when my usb stick connected. I found nice python script here but when it calls GetAllProperties() method I get an exception: ERROR:dbus.connection:Exception in handler for D-Bus signal: Traceback (most recent call last): File "/usr/lib/python2.7/site-package...
[ "Your DBus method call failed due to access policy. It is probably because you called a method without specifying any interface. Looks like a bug in the script you tried to use (DBus methods should always be called via an interface).\nTry replacing:\ndef udi_to_device(self, udi):\n return self.bus.get_object(\"o...
[ 2 ]
[]
[]
[ "dbus", "linux", "opensuse", "python" ]
stackoverflow_0007951822_dbus_linux_opensuse_python.txt
Q: metaclass conflict with modelformset_factory in Django I'm using Django model inheritance to create two models - WorkAttachmentPicture and WorkAttachmentAudio class WorkAttachment(models.Model): """ Abstract class that holds all fields that are required in each attachment """ work = models.Fore...
metaclass conflict with modelformset_factory in Django
I'm using Django model inheritance to create two models - WorkAttachmentPicture and WorkAttachmentAudio class WorkAttachment(models.Model): """ Abstract class that holds all fields that are required in each attachment """ work = models.ForeignKey(Work) added = models.DateTimeField(defa...
[ "Solved it. If you look carefully\n# this has forms.ModelForm\nclass ImageAttachmentForm(forms.ModelForm):\n# this has forms.Form\nclass AudioAttachmentForm(forms.Form):\n\nI've changed forms.Form to forms.ModelForm and everything works now - this was a simple copy/paste error.\n" ]
[ 6 ]
[]
[]
[ "django", "metaclass", "python" ]
stackoverflow_0007951627_django_metaclass_python.txt
Q: Getting `django-registration` to send you to the page you were originally trying to visit django.contrib.auth has an awesome feature: When you try to access a page that's decorated by login_required, you get redirected to the login page with a next argument, so after you login you get redirected back to the page y...
Getting `django-registration` to send you to the page you were originally trying to visit
django.contrib.auth has an awesome feature: When you try to access a page that's decorated by login_required, you get redirected to the login page with a next argument, so after you login you get redirected back to the page you were originally trying to access. That's good for the user flow. But, apparently django-regi...
[ "If you look at the view responsible for the activation of an account via email (registration.views.activate) you'll see that it accepts a success_url parameter which is \"The name of a URL pattern to redirect to on successful activation.\"\nSo you simply have to overwrite the url that calls that view and provide t...
[ 12 ]
[ "You should use the same decorator @login_required, django-registration uses that too.\n" ]
[ -4 ]
[ "django", "django_authentication", "django_registration", "python" ]
stackoverflow_0007930526_django_django_authentication_django_registration_python.txt
Q: Python timedelta receiving unexpected results In a web application I'm writing for an existing database I need to calculate the difference between now and a timestamp stored in the database (in a text field, it's stupid, I know). Here's my sqlalchemy Ban class and the relevant method. class Ban(base): __tablen...
Python timedelta receiving unexpected results
In a web application I'm writing for an existing database I need to calculate the difference between now and a timestamp stored in the database (in a text field, it's stupid, I know). Here's my sqlalchemy Ban class and the relevant method. class Ban(base): __tablename__= 'bans' id= Column('banID', Integer, pri...
[ "The output is screwed up because your calculation to convert a number of seconds to days, hours, minutes and seconds is wrong. Since you didn't post that bit of code that's all I can say, but note that there are 86400 seconds in a day and all of the counts of seconds you output are smaller than this.\nThe values y...
[ 1, 1 ]
[]
[]
[ "datetime", "methods", "python", "time", "timedelta" ]
stackoverflow_0007951804_datetime_methods_python_time_timedelta.txt
Q: How to unpack 6 bytes as single integer using struct in Python I have the following 8 bytes: b'\x05\x00\x00\x00\x00\x00\x05\x00' I'm trying to get two integers using struct.unpack: one for the first 2 bytes, and one for the last 6. Getting the first two is easy using: struct.unpack("<H6B") But, that returns (5,...
How to unpack 6 bytes as single integer using struct in Python
I have the following 8 bytes: b'\x05\x00\x00\x00\x00\x00\x05\x00' I'm trying to get two integers using struct.unpack: one for the first 2 bytes, and one for the last 6. Getting the first two is easy using: struct.unpack("<H6B") But, that returns (5, 0, 0, 0, 0, 5, 0) I want it to return the following: (5, 5) How d...
[ "struct does not support integers with non-power-of-two size. This is common. C doesn't support such integers on your platform either (well, bitfields, but you can't make an array of those).\ndef unpack48(x):\n x1, x2, x3 = struct.unpack('<HHI', x)\n return x1, x2 | (x3 << 16)\n\n", "The standard struct m...
[ 12, 5 ]
[]
[]
[ "python", "struct" ]
stackoverflow_0007949912_python_struct.txt
Q: write regex equivalent to like statement in query i have sample query select c.name , c.id from company c where c.name like 'Hoder%' and c.name like 'Stock%' amd c.name like 'Colour%' and c.name like '%Delete' and c.name like '%Regular' and c.name like '%Filler' and c.name like '%wipe%' and c.name like '%palce...
write regex equivalent to like statement in query
i have sample query select c.name , c.id from company c where c.name like 'Hoder%' and c.name like 'Stock%' amd c.name like 'Colour%' and c.name like '%Delete' and c.name like '%Regular' and c.name like '%Filler' and c.name like '%wipe%' and c.name like '%palce%' and c.name like '%double%', and c.name in ('IT', 'W...
[ "Replace the % with .*. For example, to match words like %Delete use:\n>>> import re\n>>> re.match(r'\\b.*Delete\\b', 'NoDelete')\n<_sre.SRE_Match object at 0x100456100>\n>>> _.group()\n'NoDelete'\n>>> re.match(r'\\b.*Delete\\b', 'Mismatch')\n\n", "import re\nm = lambda regex: re.match(regex, name)\n\nm(r'.*Dele...
[ 1, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007950400_python_regex.txt
Q: Having issues creating a query with an inner join and an outer join I have the following model (simplified): class User(Base): __tablename__ = 'user' id = Column(Integer, primary_key=True) class Thing(Base): __tablename__ = 'thing' id = Column(Integer, primary_key=True) class Relationship(Base): ...
Having issues creating a query with an inner join and an outer join
I have the following model (simplified): class User(Base): __tablename__ = 'user' id = Column(Integer, primary_key=True) class Thing(Base): __tablename__ = 'thing' id = Column(Integer, primary_key=True) class Relationship(Base): __tablename__ = 'relationship' id = Column(Integer, primary_key=T...
[ "Just turn on SQL logging (echo=True) and you will see that the resulting SQL query for the first option is something like:\nSELECT relationship.id AS relationship_id, relationship.parent_id AS relationship_parent_id, relationship.child_id AS relationship_child_id, vote.id AS vote_id, vote.rel_id AS vote_rel_id, vo...
[ 2 ]
[]
[]
[ "pyramid", "python", "sqlalchemy" ]
stackoverflow_0007949291_pyramid_python_sqlalchemy.txt
Q: What is the PyQt4 equivalent of GTK set_keep_above(True) method? I would like to keep the PyQt4 window above like I do with GTK with set_keep_above(True). Is that possible ? Edit 20111101 : this is my code, I don't know how to force the window "above" : #!/usr/bin/python2 # -*- coding: utf8 -*- import os, sys, s...
What is the PyQt4 equivalent of GTK set_keep_above(True) method?
I would like to keep the PyQt4 window above like I do with GTK with set_keep_above(True). Is that possible ? Edit 20111101 : this is my code, I don't know how to force the window "above" : #!/usr/bin/python2 # -*- coding: utf8 -*- import os, sys, signal from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4....
[ "I use something like this:\nfrom PyQt4 import QtGui as qt\nfrom PyQt4 import QtCore as qc\n\nclass MainWin(qt.QMainWindow):\n def setKeepAbove(self, above):\n if above:\n self.setWindowFlags(self.windowFlags() | qc.Qt.WindowStaysOnTopHint)\n else:\n self.setWindowFlags(self.w...
[ 2 ]
[]
[]
[ "pygtk", "pyqt4", "python" ]
stackoverflow_0007949733_pygtk_pyqt4_python.txt
Q: How would I combine multiple .py files into one .exe with Py2Exe I used PyQt to make a GUI for my program, but it has multiple .py files, 2 are them are classes, and one launches the code. So I was wondering, how would I combine them into one whole program? Here is a download link to all the .py files I will be co...
How would I combine multiple .py files into one .exe with Py2Exe
I used PyQt to make a GUI for my program, but it has multiple .py files, 2 are them are classes, and one launches the code. So I was wondering, how would I combine them into one whole program? Here is a download link to all the .py files I will be combining: http://www.multiupload.com/CJDL639CTH
[ "Shed Skin can turn your program into a fast executable, but maybe that doesn't work for your program.\nWith py2exe and a setup.py like this you can easily turn your Python 2.x code in Windows into an executable with only one extra file, unlike cx_Freeze's flat output of 11 files. For Python 3, use cx_Freeze, or py...
[ 3, 0 ]
[]
[]
[ "py2exe", "pyqt", "python" ]
stackoverflow_0007950335_py2exe_pyqt_python.txt
Q: Python string formatting - Possible use of lambda? I'm doing some formatted table printing, and I was wondering how i could do something like this, I think it's a situation for lambda, but I've never used it before so I'm not sure :) print "{:^{}}|"*(self.size).format(for i in range(self.size),6) # self size is a...
Python string formatting - Possible use of lambda?
I'm doing some formatted table printing, and I was wondering how i could do something like this, I think it's a situation for lambda, but I've never used it before so I'm not sure :) print "{:^{}}|"*(self.size).format(for i in range(self.size),6) # self size is assumed to be 5 in this example, doesn't work, something ...
[ "Here's my best guess:\nprint '|'.join('{:^6}'.format(i) for i in range(self.size))\n...\nprint ''.join('{:^4}'.format(i) for i in humangrid[0])\n\nIf you really want to do it with a single call to string.format():\nprint '|'.join(['{:^6}'*self.size]).format(*range(self.size))\n...\nprint ('{:^4}'*len(humangrid[0])...
[ 2, 1, 0 ]
[]
[]
[ "lambda", "python", "string_formatting" ]
stackoverflow_0007952131_lambda_python_string_formatting.txt