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: Splitting arrays python I have a 2D array in Python either a normal one or a numpy array with dimensions (150, 5), I wish to split it into two arrays of dimensions (150, 3) and (150, 2) respectively. Somehow I haven't been able to do it. Any suggestions? A: for numpy arrays you can slice them like this: a, b = t...
Splitting arrays python
I have a 2D array in Python either a normal one or a numpy array with dimensions (150, 5), I wish to split it into two arrays of dimensions (150, 3) and (150, 2) respectively. Somehow I haven't been able to do it. Any suggestions?
[ "for numpy arrays you can slice them like this:\na, b = the_array[...,:3], the_array[...,3:]\n\nand with lists of lists (that's what I understand for \"normal arrays\")\na, b = [i[:3] for i in the_array], [i[3:] for i in the_array]\n\n" ]
[ 3 ]
[]
[]
[ "arrays", "list", "numpy", "python" ]
stackoverflow_0007426583_arrays_list_numpy_python.txt
Q: SMTP Email script doesn't work on Mac but works on Windows I have some code used to send emails. It works on windows but when I try run it on a mac (with the same user login as on the windows machine), it doesn't send an email or return any errors. Anyone have any experience with this kinda thing, or examples, tip...
SMTP Email script doesn't work on Mac but works on Windows
I have some code used to send emails. It works on windows but when I try run it on a mac (with the same user login as on the windows machine), it doesn't send an email or return any errors. Anyone have any experience with this kinda thing, or examples, tips, solutions pls? import smtplib import mimetypes from email im...
[ "The sendmail call returned nothing - just {}. And finally I don't know why but out of sheer annoyance I tried\nsmtp.starttls()\nsmtp.login('username', 'password')\n\nand it seemed to fix the problem. \nIt doesn't make sense to me that you would need to do this for the script to work on the mac as it worked perfect...
[ 0 ]
[]
[]
[ "email", "macos", "python", "smtplib" ]
stackoverflow_0007414397_email_macos_python_smtplib.txt
Q: How to write a list from an output in a message box usin wx python? we can write in a messsage box using msg = "Hello World" dlg = wx.MessageDialog(self, msg, "About", wx.OK) dlg.showmodal() dlg.Destroy() now the problem is writing a list using msg = list... where list is our output that we want ...
How to write a list from an output in a message box usin wx python?
we can write in a messsage box using msg = "Hello World" dlg = wx.MessageDialog(self, msg, "About", wx.OK) dlg.showmodal() dlg.Destroy() now the problem is writing a list using msg = list... where list is our output that we want to display in the msg box. i am geting an error that "string or unicode t...
[ "The message in a message box must be a string. Thus a list must be converted to a string. There is more than one way of doing this, but my recommendation is to do this.\nmylist = ['blah', 7, 'etc...']\n#make sure the values are strings\nmylist = [str(x) for x in mylist]\nmsg = ', '.join(mylist)\n\ndlg = wx.Messa...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0007426829_python.txt
Q: automaticly update `__version__` with mercurial? Possible Duplicate: How to display current working copy version of an hg repository on a PHP page Similar to How can I rewrite python __version__ with git?, what it is the best method to store an automatically updated version number inside a python file? How good ...
automaticly update `__version__` with mercurial?
Possible Duplicate: How to display current working copy version of an hg repository on a PHP page Similar to How can I rewrite python __version__ with git?, what it is the best method to store an automatically updated version number inside a python file? How good is my method of embedding version numbers into my app...
[ "You can always add a build system, no matter which language you write your program in. You might say \"but language X doesn't need a build system\", but this question shows that it does: it needs it for those repetitive tasks that needs to be done before any release. This is tasks like building the documentation, ...
[ 2 ]
[]
[]
[ "mercurial", "python" ]
stackoverflow_0007426341_mercurial_python.txt
Q: Does Python IDLE support sticky folder locations on File | Open? I frequently open Python scripts using IDLE's File | Open. The default location at which the file browser opens is about 5 clicks away from where my Python scripts are stored. I would like to know how to change that default location? Also, does IDLE ...
Does Python IDLE support sticky folder locations on File | Open?
I frequently open Python scripts using IDLE's File | Open. The default location at which the file browser opens is about 5 clicks away from where my Python scripts are stored. I would like to know how to change that default location? Also, does IDLE have any concept of sticky folders (i.e. open at the same folder you c...
[ "As I recall there are no such thing inside idle. But you probably could solve such inconvenience with some external tools.\nWhy don't just create simlinks to your desired locations in default idle dir? It'll be only 1 click away.\nOn win you could change working directory in IDLE label property's.\nNot sure about ...
[ 0 ]
[]
[]
[ "file", "python", "python_idle" ]
stackoverflow_0007427033_file_python_python_idle.txt
Q: Python Regex to match OpenWindow.document.write( [this] ) I've got a webpage which contains document.write javascript commands. These command are structured like: OpenWindow.document.write("text that I want") I would like to use a regular expression to return either a list or a match object of all [text that I wa...
Python Regex to match OpenWindow.document.write( [this] )
I've got a webpage which contains document.write javascript commands. These command are structured like: OpenWindow.document.write("text that I want") I would like to use a regular expression to return either a list or a match object of all [text that I want]. Could someone please help me? Sample code so far: f = open...
[ "You could try a regex like this:\nOpenWindow\\.document\\.write\\s*\\(\\s*\"((?:[^\"\\\\]+|\\\\.)*)\"\\s*\\)\n\nIf it's always a simple double quoted string.\nIt works with escapes, and matches things like:\nOpenWindow.document.write(\"foo(\\\"bar\\\") baz('')\")\n\nNote that it's not fool proof: JS comments, quot...
[ 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007427445_python_regex.txt
Q: RPy2 robjects.r.pie gives curious error "'x' values must be positive" I'm feeling awfully silly, but I can't seem to work this out. I'm trying to make a pie chart, using rpy2 in Python. from rpy2.robjects import r import os.path image = "test.png" values = [0.5, 0.5] print "using R" r.png(image, width=100, heigh...
RPy2 robjects.r.pie gives curious error "'x' values must be positive"
I'm feeling awfully silly, but I can't seem to work this out. I'm trying to make a pie chart, using rpy2 in Python. from rpy2.robjects import r import os.path image = "test.png" values = [0.5, 0.5] print "using R" r.png(image, width=100, height=100) r.pie(values) r.dev_off() Now, to do the same thing directly in R I...
[ "[note: your R code does not appear correct. You probably mean\nvalues <- c(0.5, 0.5)\n\nThe use of the function c() matters; see below]\nCurrently rpy2 does not try to guess how one wants to represent in R a Python list or tuple.\nThis can be found in the rpy2 documentation.\nUse either the R function c() or the r...
[ 1 ]
[]
[]
[ "python", "r", "rpy2" ]
stackoverflow_0007426275_python_r_rpy2.txt
Q: Install libraries in a different dir I want to install pygame on my system, but I don't want to mix the standard libraries with third-party libs. If I install pygame on a different path, how can I then modify sys.path so the interpreter would know where to look? A: It may be overkill, but did you consider using ...
Install libraries in a different dir
I want to install pygame on my system, but I don't want to mix the standard libraries with third-party libs. If I install pygame on a different path, how can I then modify sys.path so the interpreter would know where to look?
[ "It may be overkill, but did you consider using virtualenv? It would let you have a virtual Python installation that used the standard for everything except the libraries you want to keep separate.\n", "You can set PYTHONPATH to a directory with additional modules. And if you use Python 2.6 or newer, you can just...
[ 4, 3, 0 ]
[]
[]
[ "pygame", "python", "windows" ]
stackoverflow_0007427313_pygame_python_windows.txt
Q: Port a multi-version python application to Windows I have written a program in Python 3 that relies on another program in Python 2.7 for some core tasks. It works seamlessly on gnunux since most distribution have already 2.7 installed, I just have to require Python 3, and it's all good. But now I want to port the ...
Port a multi-version python application to Windows
I have written a program in Python 3 that relies on another program in Python 2.7 for some core tasks. It works seamlessly on gnunux since most distribution have already 2.7 installed, I just have to require Python 3, and it's all good. But now I want to port the bundle to Windows, and I don't know how to manage this. ...
[ "How about using PyInstaller? Never used it myself but:\n\nPyInstaller is a program that converts (packages) Python programs into stand-alone executables, under Windows, Linux, and Mac OS X.\n\nhttp://www.pyinstaller.org/\nSo you could convert both your programs to executables and then call one from inside the othe...
[ 1, 1 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0007349678_python_windows.txt
Q: How to start external program from Python script in the foreground? import os os.system("notepad macros.txt") or from subprocess import Popen Popen(["notepad", "macros.txt"]) both start notepad in the background. How to start it in the foreground? A: You can try to use the start command, maybe the /MAX option...
How to start external program from Python script in the foreground?
import os os.system("notepad macros.txt") or from subprocess import Popen Popen(["notepad", "macros.txt"]) both start notepad in the background. How to start it in the foreground?
[ "You can try to use the start command, maybe the /MAX option will force notepad to be in foreground, otherwise if you can wait untill notepad shutdown, use the /WAIT option/\nPopen([\"start\", \"/MAX\", \"notepad\", \"macros.txt\"], shell=True)\n\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0007427898_python.txt
Q: Organize my python project for MVC patern, Python is new for me, and I've got problems to organize my files codes. I want to do something like : ./ /views index.html // Django files /controlers main.py /models Greeting.py // I take the same classe exemple of Google App Engine Websit...
Organize my python project for MVC patern,
Python is new for me, and I've got problems to organize my files codes. I want to do something like : ./ /views index.html // Django files /controlers main.py /models Greeting.py // I take the same classe exemple of Google App Engine Website /libs xxx.py //some Lib and tools cla...
[ "Yes your structure works or if you find my example useful here's how I organize a smaller app engine app:\n.\n├── app.yaml\n├── conf.py\n├── main.py\n├── model.py\n├── static\n│   ├── 1.gif\n│   ├── 2.gif\n│   ├── 3.gif\n│   ├── 4.gif\n│   ├── anim.gif\n│   ├── main.css\n│   ├── main.js\n└── templates\n ├── bas...
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007427542_google_app_engine_python.txt
Q: Using ctypes to load a specific runtime library (MSVCRT80) We're using ctypes.windll to load a third-party library. This library uses 'MSVCRT80' and states that it's callers responsibility to free resources. Therefor we've tried using windll.msvcrt.free(pointer) to free resources returned by the external library. ...
Using ctypes to load a specific runtime library (MSVCRT80)
We're using ctypes.windll to load a third-party library. This library uses 'MSVCRT80' and states that it's callers responsibility to free resources. Therefor we've tried using windll.msvcrt.free(pointer) to free resources returned by the external library. This fails as windll.msvcrt is another runtime ('MSVCRT90.DLL' w...
[ "According to Hans' comment in your other question, you can use GetModuleHandle to get the handle to the already loaded CRT. Like this:\nhandle = windll.kernel32.GetModuleHandleA('msvcr80')\nmsvcr80 = WinDLL('', handle=handle)\nmsvcr80.free(...)\n\nFor what it's worth, windll.msvcrt actually refers to the Windows ...
[ 2, 1 ]
[]
[]
[ "ctypes", "python", "winapi" ]
stackoverflow_0007399774_ctypes_python_winapi.txt
Q: Fast Kernel matrix computation python I would like to compute a kernel matrix in python in the fastest way as possible: the input is a matrix X= nsamples, nfeatues and the output should be a symmetric matrix D =nsamples, nsapmles the method which I'm using right now, even though is based on iterators seems to be r...
Fast Kernel matrix computation python
I would like to compute a kernel matrix in python in the fastest way as possible: the input is a matrix X= nsamples, nfeatues and the output should be a symmetric matrix D =nsamples, nsapmles the method which I'm using right now, even though is based on iterators seems to be really slow do to the for loop... can anybod...
[ "You can half the running time by replacing the inner loop by\nfor i in range(nsamples):\n for j in range(i):\n D[i,j]=quadraticChiDist(X[i,:],X[j,:])\n D[j,i]=D[i,j]\n\nEven if quadraticChiDist is not symmetric, that does not matter as you symmetrize you matrix by (did you forget to divide by 2 ?)...
[ 1, 0 ]
[]
[]
[ "machine_learning", "numpy", "python", "svm" ]
stackoverflow_0007391779_machine_learning_numpy_python_svm.txt
Q: what's the right way to put *arg in a tuple that can be sorted? I want a dict or tuple I can sort based on attributes of the objects I'm using as arguments for *arg. The way I've been trying to do it just gives me AttributeErrors, which leads me to believe I'm doing it weird. def function(*arg): items = {} ...
what's the right way to put *arg in a tuple that can be sorted?
I want a dict or tuple I can sort based on attributes of the objects I'm using as arguments for *arg. The way I've been trying to do it just gives me AttributeErrors, which leads me to believe I'm doing it weird. def function(*arg): items = {} for thing in arg: items.update({thing.name:thing}) wh...
[ "arg already is a tuple you can sort by an attribute of each item:\ndef function(*args):\n for thing in sorted(args, key=attrgetter('attribute')):\n\nWhen you iterate over a dict, as sorted is doing, you just get the keys, not the values. So, if you want to use a dict, you need to do:\ndef function(*args):\n ...
[ 1, 0, 0 ]
[]
[]
[ "dictionary", "python", "sorting", "tuples" ]
stackoverflow_0007427296_dictionary_python_sorting_tuples.txt
Q: How to diff 2 a very big arrays? I have 2 very big arrays. Is this code going to be very slow to run? results1 = [1,2,3..] results2 = [1,2,3,4 ... ] for result1 in results1: if result1 not in results2: print result1 A: Use a set: hashed = set(results2) .... if result1 not in hashed: Note tha...
How to diff 2 a very big arrays?
I have 2 very big arrays. Is this code going to be very slow to run? results1 = [1,2,3..] results2 = [1,2,3,4 ... ] for result1 in results1: if result1 not in results2: print result1
[ "Use a set:\nhashed = set(results2)\n\n....\n\n if result1 not in hashed:\n\nNote that this needs a lot of memory if your array is really huge.\nAlternatively, sort both arrays and use two indexes. If both elements are the same, increment both indexes. If they are unequal, increment the index of the array which ...
[ 7, 1, 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0006937902_algorithm_python.txt
Q: Saving state of complex, scripted objects In C++ I have the following two classes that I expose (using Boost) to Python: struct Foo { // Empty }; struct FooContainer { // I use boost::shared_ptr for compatibility with Boost.Python vector<boost::shared_ptr<Foo>> foos_; }; In the Python side I might cr...
Saving state of complex, scripted objects
In C++ I have the following two classes that I expose (using Boost) to Python: struct Foo { // Empty }; struct FooContainer { // I use boost::shared_ptr for compatibility with Boost.Python vector<boost::shared_ptr<Foo>> foos_; }; In the Python side I might create a special type of Foo that actually does s...
[ "You can use boost::python/pickle, and save the data from python. I only have limited experience with the pickling suite, but it should work provided you override appropriate pickling methods in your classes derived in python (see my answer to this question).\n", "You already have python code that creates the Foo...
[ 2, 1 ]
[]
[]
[ "boost_python", "c++", "embedding", "python", "scripting" ]
stackoverflow_0007361944_boost_python_c++_embedding_python_scripting.txt
Q: How do I convert a base64 encoded string to a Stream that I can use with FileStorage from werkzeug.datastructures? I need this because I am using AJAX to transfer a file, hence I get an image file in a base64 encoded string. I would like to convert this nicely to the FileStorage object so I can use flask-uploads l...
How do I convert a base64 encoded string to a Stream that I can use with FileStorage from werkzeug.datastructures?
I need this because I am using AJAX to transfer a file, hence I get an image file in a base64 encoded string. I would like to convert this nicely to the FileStorage object so I can use flask-uploads library nicely. Any idea how I can do this? Thanks!
[ "Take a look at the pickle module, specifically the pickle.load function. This module assists with converting objects to and from byte streams.\nYou may also need to convert your string using binascii.\n", "def open_file(file_name):\n \"\"\"\n opens file in samples, and return base64 encoded streams.\n ...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007339833_python.txt
Q: Unresolved import in PyDev in package __init__ This is really a trivial problem, but it's driving me crazy. I created an essentially default PyDev project (PyDev 2.2.2, Eclipse 3.7.0) using the src folder option, so now I have something like this: mylib [project] src [folder] mylib [package] ...
Unresolved import in PyDev in package __init__
This is really a trivial problem, but it's driving me crazy. I created an essentially default PyDev project (PyDev 2.2.2, Eclipse 3.7.0) using the src folder option, so now I have something like this: mylib [project] src [folder] mylib [package] __init__.py mymod.py So now I want to...
[ "I have to take a look at the PyDev source, but it does seem weird that it works\nin Python (i.e.: inside the package mylib you're importing the mylib package\nagain, so, it seems to me it'd be a cyclic import -- I believe that the proper\nway of doing it should be using a relative import... i.e.: \"from . import m...
[ 1 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0007422425_eclipse_pydev_python.txt
Q: How to interface with another database effectively using python I have an application that needs to interface with another app's database. I have read access but not write. Currently I'm using sql statements via pyodbc to grab the rows and using python manipulate the data. Since I don't cache anything this can be ...
How to interface with another database effectively using python
I have an application that needs to interface with another app's database. I have read access but not write. Currently I'm using sql statements via pyodbc to grab the rows and using python manipulate the data. Since I don't cache anything this can be quite costly. I'm thinking of using an ORM to solve my problem. The q...
[ "I don't think an ORM is the solution to your problem of performance. By default ORMs tend to be less efficient than row SQL because they might fetch data that you're not going to use (eg. doing a SELECT * when you need only one field), although SQLAlchemy allows fine-grained control over the SQL generated.\nNow to...
[ 2 ]
[]
[]
[ "orm", "python", "sql", "sqlalchemy" ]
stackoverflow_0007426564_orm_python_sql_sqlalchemy.txt
Q: CDATA not rendering tags I'm trying to display XML tags mixed in with plain text on a web page. I do this from a python script that obtains it's data from a database. I've simplified my problem to the program below. #!/usr/local/bin/python print """Content-type: text/html;charset=utf-8\n\n""" print """<html><bod...
CDATA not rendering tags
I'm trying to display XML tags mixed in with plain text on a web page. I do this from a python script that obtains it's data from a database. I've simplified my problem to the program below. #!/usr/local/bin/python print """Content-type: text/html;charset=utf-8\n\n""" print """<html><body> start:<![CDATA[This is the ...
[ "CDATA is part of XML, not HTML, so the browser ignores it, and then treats any tags in it as it would any other tags - ignoring ones it doesn't recognise, and paying attention to those it does.\nI think there's no alternative but to use &lt; etc and convert to tags when editing and convert back when saving.\n", ...
[ 1, 0 ]
[]
[]
[ "html", "python" ]
stackoverflow_0007429433_html_python.txt
Q: Accessing MFC functions in python I have just recently started using python for using it with my mfc program and it has been a decent journey so far. At the moment, I am trying to access a function from my mfc dll program that has a format given below: void DLLDIR DrawEllipse ( CRect, CDC* ); I have used extern "...
Accessing MFC functions in python
I have just recently started using python for using it with my mfc program and it has been a decent journey so far. At the moment, I am trying to access a function from my mfc dll program that has a format given below: void DLLDIR DrawEllipse ( CRect, CDC* ); I have used extern "C" and everything and I am able to acce...
[ "You can't, you need to wrap those structures as Python objects - either make you own, or use the 'native' Python equivalent of a rectangle (if there is one, I don't know of any). Look at Python win32 packages such as win32all to do the heavy lifting, so that you won't have to re-implement it all yourself.\n" ]
[ 0 ]
[]
[]
[ "dll", "function", "mfc", "python" ]
stackoverflow_0007415910_dll_function_mfc_python.txt
Q: Eclipse + PyDev becomes extremely slow with large import I'm trying to use Eclipse + PyDev for studying OpenGL programming but when I type from OpenGL.GL import * from OpenGL.GLUT import * IDE becomes extremely slow! Ok. It isn't a smart idea import to much useless things but it's so useful for learning a new lib...
Eclipse + PyDev becomes extremely slow with large import
I'm trying to use Eclipse + PyDev for studying OpenGL programming but when I type from OpenGL.GL import * from OpenGL.GLUT import * IDE becomes extremely slow! Ok. It isn't a smart idea import to much useless things but it's so useful for learning a new library! Any help? PS: I use Ubuntu with Eclipse Galileo.
[ "You may want to disable Project -> Build Automatically on the menu. It makes no sense to continue building files with Python, and you've got an interactive console to test your code. This will not affect code-completion at all.\n", "I'm trying to reproduce your issue and I'm unable to do it here -- even with tho...
[ 2, 2 ]
[]
[]
[ "eclipse", "opengl", "pydev", "python" ]
stackoverflow_0002836315_eclipse_opengl_pydev_python.txt
Q: match a list of words in a line using regex in python I am looking for an expression to match strings against a list of words like ["xxx", "yyy", "zzz"]. The strings need to contain all three words but they do not need to be in the same order. E.g., the following strings should be matched: '"yyy" string of words ...
match a list of words in a line using regex in python
I am looking for an expression to match strings against a list of words like ["xxx", "yyy", "zzz"]. The strings need to contain all three words but they do not need to be in the same order. E.g., the following strings should be matched: '"yyy" string of words and than “zzz" string of words “xxx"' or 'string of words...
[ "Simple string operation:\nmywords = (\"xxx\", \"yyy\", \"zzz\")\nall(x in mystring for x in mywords)\n\nIf word boundaries are relevant (i. e. you want to match zzz but not Ozzzy): \nimport re\nall(re.search(r\"\\b\" + re.escape(word) + r\"\\b\", mystring) for word in mywords)\n\n", "I'd use all and re.search fo...
[ 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007430188_python.txt
Q: Is it possible to build a desktop based application using Twython without using Django? Oauth2 causing problem I downloaded the Twython source code and compiled it on my system. I am developing a desktop app, rather than a web-app. Thus, I don't see the use of Django-Oauth2 implementation in my little project. Th...
Is it possible to build a desktop based application using Twython without using Django? Oauth2 causing problem
I downloaded the Twython source code and compiled it on my system. I am developing a desktop app, rather than a web-app. Thus, I don't see the use of Django-Oauth2 implementation in my little project. This is being asked in twython.py self.request_token_url = 'http://twitter.com/oauth/request_token' self.acces...
[ "I'm the author of Twython.\nSadly, OAuth is a less than ideal method for authenticating in... well, anything outside of a web browser. While it's possible you could figure out some hacky method to make this work, if you're concerned about the user experience you may just want to request xAuth permission from Twitt...
[ 1 ]
[]
[]
[ "oauth_2.0", "python" ]
stackoverflow_0007429454_oauth_2.0_python.txt
Q: Processing a remote iCal with Python Hi I need to process a remote .ical file from another server on my own server and hand it back to the requesting user. So what I need to do is: Fetch the file (could do this with urllib2) Process the file with some regex (not the question) hand it back with a specific header <...
Processing a remote iCal with Python
Hi I need to process a remote .ical file from another server on my own server and hand it back to the requesting user. So what I need to do is: Fetch the file (could do this with urllib2) Process the file with some regex (not the question) hand it back with a specific header <-- my main problem I'd know how to do thi...
[ "Well, as with anything web-related, you start with a WSGI application.\ndef app(environ, start_response):\n calendar = get_processed_file()\n\n start_response('200 OK', [\n ('Content-Type', 'text/icalendar; charset=utf-8'),\n ('Content-Disposition', 'inline; filename=calendar.ics'),\n ])\n ...
[ 1 ]
[]
[]
[ "http", "icalendar", "python" ]
stackoverflow_0007429822_http_icalendar_python.txt
Q: Pickle and Unpickle dict w/list as value I have a dictionary with a list as a value such as: numlist = {'Person': ['2342342', '15:05']} I pickle it. outfile = open{"log.txt", "wb") pickle.dump(numlist, outfile) I unpickle it. infile = open("log.txt", "rb") pickle.load(infile) How do I convert this binary data b...
Pickle and Unpickle dict w/list as value
I have a dictionary with a list as a value such as: numlist = {'Person': ['2342342', '15:05']} I pickle it. outfile = open{"log.txt", "wb") pickle.dump(numlist, outfile) I unpickle it. infile = open("log.txt", "rb") pickle.load(infile) How do I convert this binary data back to it's original format? (a dictionary wit...
[ "OK, let's try it:\nIn [22]: import pickle\n\nIn [23]: numlist = {'Person': ['2342342', '15:05']}\n\nIn [24]: outfile = open(\"log.txt\", \"wb\")\n\nIn [25]: pickle.dump(numlist, outfile)\n\nIn [26]: outfile.close()\n\nIn [27]: infile = open(\"log.txt\", \"rb\")\n\nIn [28]: pickle.load(infile)\nOut[28]: {'Person': ...
[ 2 ]
[]
[]
[ "file", "pickle", "python" ]
stackoverflow_0007430573_file_pickle_python.txt
Q: adding a layer to a dictionary I have a global dictionary like the following in my code: param_values = { 'aa' : [(-1,-1), (-1,-1), (-1,-1), (-1,-1), (0.1,1.0), (-1,-1)], 'ae' : [(-1,-1), (-1,-1), (0.1,0.8), (-1,-1), (0.1,1.0), (-1,-1)], 'ah' : [(-1,-1...
adding a layer to a dictionary
I have a global dictionary like the following in my code: param_values = { 'aa' : [(-1,-1), (-1,-1), (-1,-1), (-1,-1), (0.1,1.0), (-1,-1)], 'ae' : [(-1,-1), (-1,-1), (0.1,0.8), (-1,-1), (0.1,1.0), (-1,-1)], 'ah' : [(-1,-1), (-1,-1), (-1,-1), (-1,-1),...
[ "If you want to go through your initial dictionary only once, you can do:\nvowels, consonants = {}, {}\nfor (letters, data) in param_values.iteritems():\n relevant_dict = vowels if is_vowel(letters) else consonants\n relevant_dict[letters] = data\nparam_values = {'vowels': vowels, 'consonants': consonants}\n\...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007430449_python.txt
Q: How to get the text after the tag How to get the text after the tag is found Example: #!/usr/bin/env python import lxml.html html = """ <b>Point1:</b> Text1 <br> <b>Point2:</b> Text2 <br> ... <b>PointN:</b> TextN <b>PointN+1:</b> TextN+1<br> """ dom = lxml.html.document_fromstring(html) el = dom.xpath('//b[text()...
How to get the text after the tag
How to get the text after the tag is found Example: #!/usr/bin/env python import lxml.html html = """ <b>Point1:</b> Text1 <br> <b>Point2:</b> Text2 <br> ... <b>PointN:</b> TextN <b>PointN+1:</b> TextN+1<br> """ dom = lxml.html.document_fromstring(html) el = dom.xpath('//b[text()="PointN:"]') print el tag el with the...
[ "Since TextN follows the <b> that you already found, you can use the XPath following axis:\ndom.xpath('//b[text() = \"PointN:\"]/following::node()')[0]\n\n", "Another way is:\nel = dom.xpath('//b[text()=\"PointN:\"]')[0]\nprint el.tail\n\n" ]
[ 3, 3 ]
[]
[]
[ "lxml", "python", "xpath" ]
stackoverflow_0007430579_lxml_python_xpath.txt
Q: Using reverse() in django forms I'm trying to use django's reverse() function in definition of django form for my custom widget, but am getting an error: ImproperlyConfigured The included urlconf urls doesn't have any patterns in it Here is the code: class WorkForm(forms.Form): # ... category = forms.Choi...
Using reverse() in django forms
I'm trying to use django's reverse() function in definition of django form for my custom widget, but am getting an error: ImproperlyConfigured The included urlconf urls doesn't have any patterns in it Here is the code: class WorkForm(forms.Form): # ... category = forms.ChoiceField( required=True, ...
[ "The problem might be that the form is defined before the urls have been loaded.\nDjango 1.4 will have a reverse_lazy feature that would solve this problem. You could implement it in your project yourself (see changeset 16121).\nAlternatively, you could set the widget in your forms __init__ method instead. Then the...
[ 14 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0007430502_django_django_forms_python.txt
Q: imap and ifilter vs. generator comprehensions I'm curious about the insignificant technical details -- differences between these two in python's internal representation, performance and stuff like that. A: Generally, using map and filter is discouraged, but you are mapping-filtering by just one function, they ar...
imap and ifilter vs. generator comprehensions
I'm curious about the insignificant technical details -- differences between these two in python's internal representation, performance and stuff like that.
[ "Generally, using map and filter is discouraged, but you are mapping-filtering by just one function, they are useful. But never use map or filter with lambda Consider this:\nPlaces where filter or map is better:\n(i for i in iterable if i), filter(bool, i)\n(int(i) for i in iterable), map(int, i)\n\nSee, they are s...
[ 1 ]
[]
[]
[ "filter", "iterator", "map", "python" ]
stackoverflow_0007430851_filter_iterator_map_python.txt
Q: list union with duplicates I need to unite two lists in Python3,where duplicates can exist,and for one set of these the resulting list will contain as many as max in both lists.An example might clarify it: [1,2,2,5]( some operator)[2,5,5,5,9]=[1,2,2,5,5,5,9] Ideas? A: You can use the collections.Counter class: ...
list union with duplicates
I need to unite two lists in Python3,where duplicates can exist,and for one set of these the resulting list will contain as many as max in both lists.An example might clarify it: [1,2,2,5]( some operator)[2,5,5,5,9]=[1,2,2,5,5,5,9] Ideas?
[ "You can use the collections.Counter class:\n>>> from collections import Counter\n>>> combined = Counter([1,2,2,5]) | Counter([2,5,5,5,9])\n>>> list(combined.elements())\n[1, 2, 2, 5, 5, 5, 9]\n\nIt functions as a multiset (an unordered collection where each element can appear multiple times). The | operator gives ...
[ 15, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007430934_python.txt
Q: Installing node.js on Windows cygwin error I tried to install node.js by following instructions here: https://github.com/joyent/node/wiki/Building-node.js-on-Cygwin-(Windows) I got these errors after running ./configure: $ ./configure Checking for program g++ or c++ : /usr/bin/g++ 2 [main] python 6768 ...
Installing node.js on Windows cygwin error
I tried to install node.js by following instructions here: https://github.com/joyent/node/wiki/Building-node.js-on-Cygwin-(Windows) I got these errors after running ./configure: $ ./configure Checking for program g++ or c++ : /usr/bin/g++ 2 [main] python 6768 C:\cygwin\bin\python.exe: *** fatal error - unab...
[ "You can follow the steps on this page:\nhttp://www.garethhunt.com/2008/02/11/cygwin-died-waiting-for-dll-loading/\nit worked perfectly for me.\n", "You can avoid installing node.js through Cygwin and try to use native Windows executable which would/should be preffered (unless you have some specific reasons to d...
[ 2, 0 ]
[]
[]
[ "configure", "cygwin", "g++", "node.js", "python" ]
stackoverflow_0007120157_configure_cygwin_g++_node.js_python.txt
Q: A positive result in if or Else? This is coding style based, was wondering if it's better to put a positive outcome from an if/else decision in the if or else block. For example is: yes_no = object.get() #Response will be 'yes' or 'no' if yes_no == 'yes': yes response else: no response ...
A positive result in if or Else?
This is coding style based, was wondering if it's better to put a positive outcome from an if/else decision in the if or else block. For example is: yes_no = object.get() #Response will be 'yes' or 'no' if yes_no == 'yes': yes response else: no response better than: yes_no = object.get(...
[ "I think that most depends on what the programmer wants to highlight. The IF condition should be either:\n\nthe most probable\nthe simplest\nthe one which leads to less calculation \nthe more readable\n...\n\nPersonally I always try to avoid this:\nif condition:\n ... tons of code ...\nelse:\n ... one line of...
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "coding_style", "if_statement", "python" ]
stackoverflow_0007431238_coding_style_if_statement_python.txt
Q: generating django admin console for a already existing mysql db schema I have a msql DB within with i have my tables.The tables has proper constraints like primary keys, foreign keys, auto increment.I love django admin console and i want to generate admin console for my db. Now my application is completely develop...
generating django admin console for a already existing mysql db schema
I have a msql DB within with i have my tables.The tables has proper constraints like primary keys, foreign keys, auto increment.I love django admin console and i want to generate admin console for my db. Now my application is completely developed in java.I want to run seperate django app which will use the same db and ...
[ "Read this: https://docs.djangoproject.com/en/1.3/howto/legacy-databases/\n" ]
[ 0 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0007431440_django_django_admin_python.txt
Q: Python: Create virtual import path Is there any way to create a virtual import path in Python? My directory structure is like this: / native scripts some.py another.py [Other unrelated dirs] The root is the directory from where the program is executed. Atm I add native/scripts/ to the search path so I can do...
Python: Create virtual import path
Is there any way to create a virtual import path in Python? My directory structure is like this: / native scripts some.py another.py [Other unrelated dirs] The root is the directory from where the program is executed. Atm I add native/scripts/ to the search path so I can do import some, another instead of fr...
[ "In /native/__init__.py, include:\nfrom scripts import some, another\n\n", "Why not move some.py and another.py out into the native directory so that everything Just Works and so that people returning to the source code later won't be confused about why things are and aren't importable? :)\nUpdate:\nThanks for yo...
[ 2, 2 ]
[]
[]
[ "import", "python" ]
stackoverflow_0007431492_import_python.txt
Q: Using SUDS Python WSDL client and Django Sentry, Exception with __sentry__ attribute When using SUDS in a Django app, alongside Sentry error logging, I hit a problem where SUDS raises an error and Sentry tries to handle it, fails horribly and causes a server 500: [Wed Sep 14 16:06:22 2011] [error] Unable to proces...
Using SUDS Python WSDL client and Django Sentry, Exception with __sentry__ attribute
When using SUDS in a Django app, alongside Sentry error logging, I hit a problem where SUDS raises an error and Sentry tries to handle it, fails horribly and causes a server 500: [Wed Sep 14 16:06:22 2011] [error] Unable to process log entry: plugin domain (__sentry__), invalid [Wed Sep 14 16:06:22 2011] [error] Traceb...
[ "Looks like SUDS is actually throwing the incorrect error type in its plugin file, and so Sentry is not able to handle it (Sentry tries to call __sentry__ on the object that raised the exception, and I guess expects an AttributeError to be returned. SUDS just raises an (old-style) Exception... \nsee: https://fedora...
[ 3 ]
[]
[]
[ "django", "python", "sentry", "suds" ]
stackoverflow_0007428295_django_python_sentry_suds.txt
Q: How to encrypt zip file on app engine blobstore I have a problem how to encrypt compressed blobs of type zip. Because of some reasons I cannot use chilkat module, zipfile module provides only decryption, so I do not know what to use to encrypt zips with a key. Could you please give me some suggestions how this pro...
How to encrypt zip file on app engine blobstore
I have a problem how to encrypt compressed blobs of type zip. Because of some reasons I cannot use chilkat module, zipfile module provides only decryption, so I do not know what to use to encrypt zips with a key. Could you please give me some suggestions how this problem is (could be) solved? ideal solution would look ...
[ "First of all, allow me to say that zip encryption is weak and obsolete. You shouldn't rely on it if you need a strong security. This has been proved on many papers (Google says that the most popular is \"Known Plaintext Attack on the PKZIP Stream Cipher\" by Eli Biham and Paul C. Kocher).\nSecond, GAE only works w...
[ 1 ]
[]
[]
[ "blobstore", "encryption", "google_app_engine", "python", "zip" ]
stackoverflow_0007431521_blobstore_encryption_google_app_engine_python_zip.txt
Q: Generate wxPython widget groups from lists This is one of those questions that is really frustrating for me to ask because I'm sure the answer is out there, I just haven't been able to word the searches correctly. Basically I am new to GUI programming (done a decent amount of embedded C/C++) and learning wxPython ...
Generate wxPython widget groups from lists
This is one of those questions that is really frustrating for me to ask because I'm sure the answer is out there, I just haven't been able to word the searches correctly. Basically I am new to GUI programming (done a decent amount of embedded C/C++) and learning wxPython to start out. I'm making an app to read and writ...
[ "I assume that the get button reads the parameter value from the config file and displays the value.\nWhy do you need one get button for each parameter? I would have just one get button for tham all. When the user clicks the get button, every parameter is read from the file and all the displays are updated.\nA si...
[ 2, 1, 0 ]
[]
[]
[ "linux", "python", "user_interface", "wxpython", "wxwidgets" ]
stackoverflow_0007411210_linux_python_user_interface_wxpython_wxwidgets.txt
Q: What is the equivalent of python's file.read() in objective C / iOS? Say that I have the Python code: someString = file("filename.jpg").read() How can I replicate this line of code in Objective C on iOS? I'm trying to convert a jpg into a string, for eventual url encoding so I can pass it on to the Tumblr API. ...
What is the equivalent of python's file.read() in objective C / iOS?
Say that I have the Python code: someString = file("filename.jpg").read() How can I replicate this line of code in Objective C on iOS? I'm trying to convert a jpg into a string, for eventual url encoding so I can pass it on to the Tumblr API. I tried base64 encoding to convert the image to a string initially, but t...
[ "I figured the answer out by simply logging the string -- it looks like it's a hexadecimal format, with \\xXX where XX is the hexadecimal code for each byte, with ASCII substitutions for certain easily-printed characters.\n\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00 \\x00\\x00\\x00\\x1d\\x08\\x06\\x...
[ 1, 0 ]
[]
[]
[ "ios", "objective_c", "python", "tumblr" ]
stackoverflow_0007400666_ios_objective_c_python_tumblr.txt
Q: Python: how can I import the namespace of some object to current namespace? I have a Python class, which contains several nested parameter groups: class MyClass(object): #some code to set parameters def some_function(self): print self.big_parameter_group.small_parameter_group.param_1 print...
Python: how can I import the namespace of some object to current namespace?
I have a Python class, which contains several nested parameter groups: class MyClass(object): #some code to set parameters def some_function(self): print self.big_parameter_group.small_parameter_group.param_1 print self.big_parameter_group.small_parameter_group.param_2 print self.big_pa...
[ "I would start the function with\nspg = self.big_parameter_group.small_parameter_group\n\nand then use that abbreviation. You could define abbreviations like this in __init__(), I suppose, if you wanted to use them everywhere with self on the front.\n", "One way is to create properties for each of them:\n@propert...
[ 6, 2, 1 ]
[]
[]
[ "namespaces", "parameters", "python", "self" ]
stackoverflow_0007431672_namespaces_parameters_python_self.txt
Q: Mako template inheritance error TypeError: 'Undefined' object is not callable I have 2 files base_table.html table_body.html base_table.html <%block name="bodytable"> <table cellspacing="0" cellpadding="0" border="1" width="100%"> <%block name="bodytabletbody"> <tbody> <%b...
Mako template inheritance error TypeError: 'Undefined' object is not callable
I have 2 files base_table.html table_body.html base_table.html <%block name="bodytable"> <table cellspacing="0" cellpadding="0" border="1" width="100%"> <%block name="bodytabletbody"> <tbody> <%block name="innerbodytabletbody"> <tr> <...
[ "It looks as if you're never passing any data into your template. In your code, you have in your base template...\n<td>\n ${_('User name')}\n</td>\n\nThat middle line basically says, \"get the value from data with the key \"_\", and call it with an argument of 'User name'.\" It seems as if you're not passing any...
[ 2 ]
[]
[]
[ "mako", "python" ]
stackoverflow_0007416772_mako_python.txt
Q: Going nuts with executing python script via crontab on debian! This is what my crontab file looks like: * * * * * root /usr/bin/python /root/test.py >> /root/classwatch.log 2>&1 This is what my python script looks like: #!/usr/bin/python print "hello" The cronjob creates the log file. But it is empty. I am also...
Going nuts with executing python script via crontab on debian!
This is what my crontab file looks like: * * * * * root /usr/bin/python /root/test.py >> /root/classwatch.log 2>&1 This is what my python script looks like: #!/usr/bin/python print "hello" The cronjob creates the log file. But it is empty. I am also pretty certain that the python file is not being executed. Apprecia...
[ "There are two ways to create a crontab -- per user or globally. For the global crontab (/etc/crontab) you specify the user, as per:\n# m h dom mon dow user command\n17 * * * * root cd / && run-parts --report /etc/cron.hourly\n\nFor user crontabs you don't, as per:\naj@wherever:~$ crontab -l\n0 * *...
[ 4, 1, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "cron", "crontab", "debian", "python" ]
stackoverflow_0000712124_cron_crontab_debian_python.txt
Q: RDP using python I want to create a Python script that allows me to connect to a Remote Machine via an RDP connection. I would really like to know if there are certain APIs in python I can exploit. A: Not any I know, however you might be able to write a cython wrapper around libxrdp, which contains library funct...
RDP using python
I want to create a Python script that allows me to connect to a Remote Machine via an RDP connection. I would really like to know if there are certain APIs in python I can exploit.
[ "Not any I know, however you might be able to write a cython wrapper around libxrdp, which contains library functions for an rdp client. However the library is sparsely documented. There is also FreeRDP (which I don't know), but I'm not sure it's a much better alternative.\n" ]
[ 3 ]
[]
[]
[ "python", "rdp", "remote_desktop" ]
stackoverflow_0007304333_python_rdp_remote_desktop.txt
Q: Python - Inheritance - Facebook application I have a question about how the code run in inheritance in Python. It might look like a dummy question somehow, but I a new to Python. This a code snippet from some Facebook application I am working on: class BaseHandler(webapp.RequestHandler): facebook = None us...
Python - Inheritance - Facebook application
I have a question about how the code run in inheritance in Python. It might look like a dummy question somehow, but I a new to Python. This a code snippet from some Facebook application I am working on: class BaseHandler(webapp.RequestHandler): facebook = None user = None def initialize(self, request, resp...
[ "Probably not. Perhaps you should def initialize to def __init__? Python objects get instantiated through the __init__ method, not through any initialize() method. Since you don't seem to have any explicit calls to initialize(), it will probably not be called.\n" ]
[ 0 ]
[]
[]
[ "facebook", "python" ]
stackoverflow_0007430987_facebook_python.txt
Q: Python recursive find files and move to one destination directory The script should recursively go through the rootpath directory and find all files with *.mp4 extension. Print the list of files with the directory structure. Then move the files to the destDir directory. The problem I run into is when trying to mov...
Python recursive find files and move to one destination directory
The script should recursively go through the rootpath directory and find all files with *.mp4 extension. Print the list of files with the directory structure. Then move the files to the destDir directory. The problem I run into is when trying to move the files to the new directory. Only files in the rootPath directory ...
[ "Congratulations! You have already found os.path.join(). You even use it, on your print call. So you only have to use it with move():\nshutil.move(os.path.join(root, filename), os.path.join(destDir, filename))\n\n(But take care not to overwrite anything in destDir.)\n", "Change the root + filename in the last lin...
[ 8, 2 ]
[]
[]
[ "python", "recursion", "shutil" ]
stackoverflow_0007432197_python_recursion_shutil.txt
Q: Django tests fail on Postgresql (8.4) - Flushing DB causes error I'm dealing with a very annoying problem when trying to run DJ tests for a project on PostgreSQL backend. It starts running the tests and when the first DB flush should happen it fails with a strange error: ..Error: Database dbname couldn't be flushe...
Django tests fail on Postgresql (8.4) - Flushing DB causes error
I'm dealing with a very annoying problem when trying to run DJ tests for a project on PostgreSQL backend. It starts running the tests and when the first DB flush should happen it fails with a strange error: ..Error: Database dbname couldn't be flushed. Possible reasons: * The database isn't running or isn't configure...
[ "OK, looks like this is not actually a problem from Django, instead it's related to the test runner from djangosanetesting, for which flushing seems to be broken in some way.\nFor now I don't have a better solution than just using django-nose test runner.\n" ]
[ 1 ]
[]
[]
[ "database", "django", "postgresql", "python", "testing" ]
stackoverflow_0007335555_database_django_postgresql_python_testing.txt
Q: How to get the function name as string in Python? Possible Duplicate: How to get the function name as string in Python? I know that I can do that : def func_name(): print func_name.__name__ which will return the name of the function as 'my_func'. But as I am into the function, is there a way to directly cal...
How to get the function name as string in Python?
Possible Duplicate: How to get the function name as string in Python? I know that I can do that : def func_name(): print func_name.__name__ which will return the name of the function as 'my_func'. But as I am into the function, is there a way to directly call it generically ? Something like : def func_name(): ...
[ "Not generically, but you can leverage inspect\nimport inspect\n\ndef callee():\n return inspect.getouterframes(inspect.currentframe())[1][1:4][2]\n\ndef my_func():\n print callee() // string my_func\n\nSource http://code.activestate.com/recipes/576925-caller-and-callee/\n", "AFAIK, there isn't. Besides, ev...
[ 9, 6, 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007432438_python.txt
Q: Regular expression that matches the third instance of something? (python) I'm trying to create a regular expression that will match the third instance of a / in a url, i.e. so that only the website's name itself will be recorded, nothing else. So http://www.stackoverflow.com/questions/answers/help/ after being put...
Regular expression that matches the third instance of something? (python)
I'm trying to create a regular expression that will match the third instance of a / in a url, i.e. so that only the website's name itself will be recorded, nothing else. So http://www.stackoverflow.com/questions/answers/help/ after being put through the regex will be http://www.stackoverflow.com I've been playing about...
[ "I suggest you use urlparse for parsing URLs:\nIn [1]: from urlparse import urlparse\n\nIn [2]: urlparse('http://www.stackoverflow.com/questions/answers/help/').netloc\nOut[2]: 'www.stackoverflow.com'\n\n.netloc includes the port number if present (e.g. www.stackoverflow.com:80); if you don't want the port number, ...
[ 9, 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007432908_python_regex.txt
Q: Problem adding triples in rdflib.store.IOMemory Whenever I try to add triple into the store using following code it gives me following error. Could you please help me in this regard. Thanks in advance. store = plugin.get('IOMemory',Store)() store.add((abc, FOAF['knows'],def)) Error: Traceback (most recent call l...
Problem adding triples in rdflib.store.IOMemory
Whenever I try to add triple into the store using following code it gives me following error. Could you please help me in this regard. Thanks in advance. store = plugin.get('IOMemory',Store)() store.add((abc, FOAF['knows'],def)) Error: Traceback (most recent call last): File "C:\Python27\internetcode.py", line 114,...
[ "It seems you have to pass at least 3 arguments. In the documentation of that module you can see what arguments needs add method:\n(abc, FOAF['knows'],def) is your triple? in that case you need two more: context and quoted\nadd(self, triple, context, quoted) \n\nI've found some more information here\n\nadd(self, (s...
[ 1, 0 ]
[]
[]
[ "python", "rdflib" ]
stackoverflow_0007432833_python_rdflib.txt
Q: Is using Python modules main function for validation testing a bad idea? I'll quickly explain exactly what I mean by this. I'm working on a project using python, where I have multiple modules doing segments of work. Let's say for example I have a module called Parser.py and this module has a function parseFile() ...
Is using Python modules main function for validation testing a bad idea?
I'll quickly explain exactly what I mean by this. I'm working on a project using python, where I have multiple modules doing segments of work. Let's say for example I have a module called Parser.py and this module has a function parseFile() which my main module Main.py calls in order to parse some files. As of right n...
[ "I think it's a good idea, and it does seem to be a common use case for if __name__ == '__main__' construct. Though this is a more usual structure:\ndef main(argv=None):\n if argv is None:\n argv = sys.argv\n # etc.\n\nif __name__ == \"__main__\":\n sys.exit(main() or 0)\n\nThis gives you the addit...
[ 2, 1 ]
[]
[]
[ "batch_file", "module", "program_entry_point", "python" ]
stackoverflow_0007424690_batch_file_module_program_entry_point_python.txt
Q: Minimising reading from and writing to disk in Python for a memory-heavy operation Background I am working on a fairly computationally intensive project for a computational linguistics project, but the problem I have is quite general and hence I expect that a solution would be interesting to others as well. Requir...
Minimising reading from and writing to disk in Python for a memory-heavy operation
Background I am working on a fairly computationally intensive project for a computational linguistics project, but the problem I have is quite general and hence I expect that a solution would be interesting to others as well. Requirements The key aspect of this particular program I must write is that it must: Read th...
[ "take a look at pytables. One of the advantages is you can work with very large amounts of data, stored on disk, as if it were in memory.\nedit: Because the I/O performance will be a bottleneck (if not THE bottleneck), you will want to consider SSD technology: high I/O per second and virtually no seeking times. The...
[ 5, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "io", "memory", "python" ]
stackoverflow_0007381258_io_memory_python.txt
Q: Python Pychart color I have a little problem. When I add a dataset (that is a list) to a chart (pychart), i can only give to data one color on the final chart. I would have different colors depending on list element's value. How can I do that ? I attach my code. c = self._setAxis(xy=(750, 430 + ystep), tuplot=(150...
Python Pychart color
I have a little problem. When I add a dataset (that is a list) to a chart (pychart), i can only give to data one color on the final chart. I would have different colors depending on list element's value. How can I do that ? I attach my code. c = self._setAxis(xy=(750, 430 + ystep), tuplot=(150, 50, 400, 200 + ystep), l...
[ "I assume COL_PREN is your color? You could try separating your hotels into separate datasets. Something like:\nfor hotel in results:\n lay.addDataSet([hotel['Percentuale'][0]], get_color_for_hotel(hotel))\n\n" ]
[ 0 ]
[]
[]
[ "pychart", "python" ]
stackoverflow_0007431728_pychart_python.txt
Q: CPU usage increasing over time I have a python program that is running for many days. Memory usage does not increase by very much, however the program becomes slower and slower. Is there a tool or utility that will list all function calls and how long they take to complete? Something like guppy/heapy but for CP...
CPU usage increasing over time
I have a python program that is running for many days. Memory usage does not increase by very much, however the program becomes slower and slower. Is there a tool or utility that will list all function calls and how long they take to complete? Something like guppy/heapy but for CPU usage.
[ "Edit2\nI just saw your actual question is answered as in 'How can you profile a Python script?'\n\nSure, use profile.py.\nimport profile\n\ndef myfunction():\n bla bla bla\n\nprofile.run('myfunction()')\n\nsee also profilers and tips on performance.\nEdit:\nAbove example is for one function.\nYou can profile an...
[ 2, 0 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0007433780_performance_python.txt
Q: Python, Lists - Use 'Item' as integer variable Sorry for the poor title, basically I want to access a list item based on another list item: catList = [john, james, jack] dateList = [1y, 2y, 3m] for item in catList: if item in typeList[1]: calendar += 1 if item in typeList[2]: connector += ...
Python, Lists - Use 'Item' as integer variable
Sorry for the poor title, basically I want to access a list item based on another list item: catList = [john, james, jack] dateList = [1y, 2y, 3m] for item in catList: if item in typeList[1]: calendar += 1 if item in typeList[2]: connector += 1 print dateList[item] It's the last line t...
[ "If the keys to catDict are numeric strings you can use print dateDict[int(item)]. Otherwise, I'm uncertain - we need to see what the declaration of catDict looks like.\nIf you're using lists you want to do this:\nfor idx, val in enumerate(catList):\n print dateList[idx]\n\n" ]
[ 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007434095_list_python.txt
Q: How to run a C program and get output of the program using Twisted Python I have a Python Bot written using Twisted framework and I have a C program that outputs certain text. How would I be able to run have Twisted run the C program using a command, collect the output, then print the output back to me? A: The ...
How to run a C program and get output of the program using Twisted Python
I have a Python Bot written using Twisted framework and I have a C program that outputs certain text. How would I be able to run have Twisted run the C program using a command, collect the output, then print the output back to me?
[ "The easiest way is getProcessOutput:\nfrom twisted.internet.utils import getProcessOutput\ndf = getProcessOutput('ls', args=('/home','-lah'))\ndf.addCallback( printOutput )\n\nAlso see http://twistedmatrix.com/documents/current/core/howto/process.html in case you need something more complex.\n" ]
[ 6 ]
[]
[]
[ "c", "irc", "linux", "python", "twisted" ]
stackoverflow_0007433797_c_irc_linux_python_twisted.txt
Q: Can Pickle handle multiple object references If I have objects a and b and both reference object obj, what happens when I Pickle and then restore the objects? Will the pickled data 'know' that a and b both referenced the same object and restore everything accordingly, or will the two get two different — and initia...
Can Pickle handle multiple object references
If I have objects a and b and both reference object obj, what happens when I Pickle and then restore the objects? Will the pickled data 'know' that a and b both referenced the same object and restore everything accordingly, or will the two get two different — and initially equal — objects?
[ "Yes, shared objects will only get serialized once (the pickle protocol can even handle circular references).\nFrom the documentation:\n\nThe pickle module keeps track of the objects it has already\n serialized, so that later references to the same object won’t be\n serialized again. marshal doesn’t do this.\nThi...
[ 18, 10 ]
[]
[]
[ "pickle", "python" ]
stackoverflow_0007433963_pickle_python.txt
Q: Fatal Python error: PyEval_RestoreThread: NULL tstate Does somebody knows what this error means? Fatal Python error: PyEval_RestoreThread: NULL tstate In my application when I destroy the main window this error is printed. I am using multiples threads to run differents jobs in the same time. I really dont have an...
Fatal Python error: PyEval_RestoreThread: NULL tstate
Does somebody knows what this error means? Fatal Python error: PyEval_RestoreThread: NULL tstate In my application when I destroy the main window this error is printed. I am using multiples threads to run differents jobs in the same time. I really dont have any ideia what is this.. If someone ever lived the same probl...
[ "What version of gtk are you using? This link seems to indicate it's a threading bug that was fixed in 2.0.1.\n" ]
[ 1 ]
[]
[]
[ "fatal_error", "python" ]
stackoverflow_0007434408_fatal_error_python.txt
Q: Binary search over an "infinite" sequence. Where do I start? I have an interesting problem. I'm faced with a function that takes a long time to compute a value based on some index. Call it takes_a_long_time(index). The values returned from this function are guaranteed to have a global minimum, but there are no gua...
Binary search over an "infinite" sequence. Where do I start?
I have an interesting problem. I'm faced with a function that takes a long time to compute a value based on some index. Call it takes_a_long_time(index). The values returned from this function are guaranteed to have a global minimum, but there are no guarantees that the index associated with will be close to zero. Sinc...
[ "From the comments to the question, the curve is well-behaved and you could use something like ternary search. The only problem then is how to handle the inconvenient behavior as your approach zero. So don't start at zero: define a new function g from your function f with g(x) = f(1/x). Search this starting from x=...
[ 2, 1 ]
[]
[]
[ "binary_search", "language_agnostic", "python" ]
stackoverflow_0007434192_binary_search_language_agnostic_python.txt
Q: Increment Numpy multi-d array with repeated indices I'm interested in the multi-dimensional case of Increment Numpy array with repeated indices. I have an N-dimensional array and a set N index arrays, who's values I want to increment. The index arrays might have have repeated entries. Without repeats, the solution...
Increment Numpy multi-d array with repeated indices
I'm interested in the multi-dimensional case of Increment Numpy array with repeated indices. I have an N-dimensional array and a set N index arrays, who's values I want to increment. The index arrays might have have repeated entries. Without repeats, the solution is a = arange(24).reshape(2,3,4) i = array([0,0,1]) j = ...
[ "How about this:\nimport numpy as np\na = np.zeros((2,3,4))\ni = np.array([0,0,1])\nj = np.array([0,0,1])\nk = np.array([0,0,3])\n\nijk = np.vstack((i,j,k)).T\nH,edge = np.histogramdd(ijk,bins=a.shape)\na += H \n\n", "I don't know if there is an easier solution with direct array indexing, but this works:\nfor x,...
[ 3, 0 ]
[]
[]
[ "arrays", "indexing", "numpy", "python" ]
stackoverflow_0007433142_arrays_indexing_numpy_python.txt
Q: Trigger ImportError to test Coverage of Fallback Code Given code like this in somemod.py: try: Import cStringIO as StringIO except ImportError: import StringIO How can one test the 'fallback' branch? (Use case: trying to achieve 100% coverage. Agreed that this is a bit of a silly goal :) ) Complications...
Trigger ImportError to test Coverage of Fallback Code
Given code like this in somemod.py: try: Import cStringIO as StringIO except ImportError: import StringIO How can one test the 'fallback' branch? (Use case: trying to achieve 100% coverage. Agreed that this is a bit of a silly goal :) ) Complications: code runs from test_somemod.py which has import somemod ...
[ "First, create a function to use for testing:\n>>> def somecode():\n... try:\n... import cStringIO as StringIO\n... print 'got cStringIO'\n... except ImportError:\n... import StringIO\n... print 'got StringIO'\n>>> somecode()\ngot cStringIO\n\nNow, as explained here, you can hook in to...
[ 3 ]
[]
[]
[ "code_coverage", "importerror", "python", "testing" ]
stackoverflow_0007435336_code_coverage_importerror_python_testing.txt
Q: Python design guidance: I'm a very experienced developer - done a lot of heavy duty work with Delphi, C# and C++ for years. I have always adhered very closely to the guidelines for structured programming, OOP, loosely coupled modular designs etc - and since all the languages I've used have built-in ways of enforci...
Python design guidance:
I'm a very experienced developer - done a lot of heavy duty work with Delphi, C# and C++ for years. I have always adhered very closely to the guidelines for structured programming, OOP, loosely coupled modular designs etc - and since all the languages I've used have built-in ways of enforcing these concepts - access co...
[ "On design pattern support:\nThere is a proposition that also puts that Design Patterns as a crude metric of gaps in a programming language. It would be an interesting read and counterpoint to your suggestion that design patterns are constraints supported by language. \n\nhttp://www.oscon.com/oscon2008/public/sched...
[ 2, 2 ]
[]
[]
[ "encapsulation", "interface", "oop", "python" ]
stackoverflow_0007435511_encapsulation_interface_oop_python.txt
Q: Suggestions for obtaining Google search results and cleaning HTML tags I am working on a project to get Google search web pages and then clean HTML tags to obtain pure text content. Any suggestion for available tools (esp. Python tools) many thanks. A: I'd check out Pattern, which is a Python web mining module p...
Suggestions for obtaining Google search results and cleaning HTML tags
I am working on a project to get Google search web pages and then clean HTML tags to obtain pure text content. Any suggestion for available tools (esp. Python tools) many thanks.
[ "I'd check out Pattern, which is a Python web mining module providing a suite of text retrieval, analysis, and viz tools. I haven't personally used it but looks powerful. \nModule pattern.web is a web toolkit that bundles various API's (Google, Gmail, Bing, Twitter, Wikipedia, Flickr) with a robust HTML parser and...
[ 2, 0, 0 ]
[]
[]
[ "html", "nlp", "python" ]
stackoverflow_0005199552_html_nlp_python.txt
Q: How can I get all of the django foreignkey objects in one shot? Context: Foo is a class that has a foreignKey field pointing to a Bar object. Several Foos may refer to the same Bar. (Many to one) I need to reference several fields of a Foo object's foreignkey (Bar.field and Bar.field2), but it seems that each time...
How can I get all of the django foreignkey objects in one shot?
Context: Foo is a class that has a foreignKey field pointing to a Bar object. Several Foos may refer to the same Bar. (Many to one) I need to reference several fields of a Foo object's foreignkey (Bar.field and Bar.field2), but it seems that each time I do so it runs a separate query. As a result, referencing these fi...
[ "foo_list = Foo.objects.filter(params).select_related()\n\ndoes the job. The rest of the code would remain the same, but\nfor f in foo_list:\n f.bar\n\nwould use the cached objects\n", "Yes, you can use the select_related method on your queryset (https://docs.djangoproject.com/en/dev/ref/models/querysets/#djan...
[ 3, 1, 0 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0007435510_django_mysql_python.txt
Q: sqlalchemy Evalulate Criteria based on list of tuple, searching? I want to apply some access rule type of mechanism, for that I'm planning to use list of tuple for specifying rules for restrictions like below ['|',('name','=','root'), ('role','=','admin')] using postfix notations... is there any existing mechanism...
sqlalchemy Evalulate Criteria based on list of tuple, searching?
I want to apply some access rule type of mechanism, for that I'm planning to use list of tuple for specifying rules for restrictions like below ['|',('name','=','root'), ('role','=','admin')] using postfix notations... is there any existing mechanism in python that may help me to convert such domain into sqlalchemy que...
[ "Here's a start of one:\nI'm going to rewrite your expression in terms of prefix notation; the operator is first and the other values follow, so:\ntest_expression = ['|',('=','name','root'), ('=','role','admin')]\n\nbut, you could probably add some more operator specific checks to handle operators in other location...
[ 2 ]
[]
[]
[ "eval", "python", "search", "sqlalchemy" ]
stackoverflow_0007425992_eval_python_search_sqlalchemy.txt
Q: Why is my JSONP returning Invalid JSON I'm currently puling data from an external XML file and converting it to JSON via Python/Django. The problem I'm encountering is that when I pull the JSON in JQUERY, I'm getting the error of "Invalid JSON" however when I put my JSON through a validator such as JSONFormatter I...
Why is my JSONP returning Invalid JSON
I'm currently puling data from an external XML file and converting it to JSON via Python/Django. The problem I'm encountering is that when I pull the JSON in JQUERY, I'm getting the error of "Invalid JSON" however when I put my JSON through a validator such as JSONFormatter I am being told that my JSON is valid. Python...
[ "You need to tell jQuery that this is JSONP (which is actually just a script. It's a call to a function with your JSON data), not JSON data itself. It said 'invalid JSON' because jQuery was trying to parse the function call.\n$.ajax({\n url: \"http://www.urltomydomain.com\",\n dataType: \"jsonp\",\n succ...
[ 4, 0 ]
[]
[]
[ "django", "jquery", "json", "jsonp", "python" ]
stackoverflow_0007435707_django_jquery_json_jsonp_python.txt
Q: why a new process entry then the events of old process stop running when sharing a listening socket for multiple processes? The problem happened in my proxy program, Considering G10K I use gevent in my program and I use the low-level gevent.core to run all my function. Before I change my program into multiple proc...
why a new process entry then the events of old process stop running when sharing a listening socket for multiple processes?
The problem happened in my proxy program, Considering G10K I use gevent in my program and I use the low-level gevent.core to run all my function. Before I change my program into multiple processes. everything is OK. But when I changed it, the problem appears. I find the problem is that when process NO.2 accept the sock...
[ "I think that the problem is in your code, because this code is working fine, with the same shared socket. \nWhen you accept sa ocket with EV_READ, you must get the client socket and free the control over the main socket; you must not write to it. You should use code similar to the following one:\ntry:\n client_...
[ 1 ]
[]
[]
[ "gevent", "multiprocessing", "python", "sockets" ]
stackoverflow_0007173987_gevent_multiprocessing_python_sockets.txt
Q: Plone Content Type-Specific Portlet Assignment I'm developing a content type for Plone 4, and I'd like to block all user, group, and context portlets it may inherit from its parent object. I'm thoroughly confused by the documentation at this point–in portlets.xml, <blacklist/> only seems to address path-specific b...
Plone Content Type-Specific Portlet Assignment
I'm developing a content type for Plone 4, and I'd like to block all user, group, and context portlets it may inherit from its parent object. I'm thoroughly confused by the documentation at this point–in portlets.xml, <blacklist/> only seems to address path-specific blocking. <assignment/> seems like what I want, but i...
[ "to prevent the portlet aquisition and maintain the possibility of adding portlert you can add an event listener on the creation of your contents that auto blocks the aquisition.\nLike this:\n <subscriber\n for=\"my.package.interfaces.IMyContent\n zope.app.container.interfaces.IObjectAddedEven...
[ 6, 1 ]
[]
[]
[ "plone", "portlet", "python" ]
stackoverflow_0007432317_plone_portlet_python.txt
Q: Sending an SMS message using Python; Time delay considering timezone So I have a code that receives relevant information for a mobile device, such as phone number, name, and message, through which it can send an SMS message. Also, there is a function which delays the SMS. So a user can choose to send a message at ...
Sending an SMS message using Python; Time delay considering timezone
So I have a code that receives relevant information for a mobile device, such as phone number, name, and message, through which it can send an SMS message. Also, there is a function which delays the SMS. So a user can choose to send a message at a later time using a drop-down menu. Furthermore the delay function checks...
[ "To accurately know the time zone of the owner of the phone is impossible unless you have some code of yours running on his phone as the owner of the phone could be travelling across time zones. \nTo address this concern you can do one of two things....\nBest Guess: This is, use a reverse phone lookup API, like see...
[ 0, 0, 0 ]
[]
[]
[ "python", "timezone" ]
stackoverflow_0007435275_python_timezone.txt
Q: Fractal Koch Curve My project that involves antenna design, in which Python generates the .nec file that allows me to model fractal antennas in the software and optimize them for the best performance. The program is intended to work with multiple fractal antennas, including all of the following: Koch Curve Hilber...
Fractal Koch Curve
My project that involves antenna design, in which Python generates the .nec file that allows me to model fractal antennas in the software and optimize them for the best performance. The program is intended to work with multiple fractal antennas, including all of the following: Koch Curve Hilbert Curve Koch Snowflake ...
[ "Perhaps you should try to reimplement your iterative calculation being more canonical.\nAn answer to a request for a good Koch Curve algorithm in Python is here:\nImplementing the Koch Curve?\n(and also the original code in the question could help you a lot)\nEDIT:\nI created a script which uses code from the prov...
[ 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007409938_python.txt
Q: Working Plone contact form into main_template.pt I'm trying to work the contact form that is baked into plone into my site's main_template. I'm doing so to make the functionality present in "get in touch" nav button on this site work in a plone setting. My approach to doing this was by slightly reworking contact-i...
Working Plone contact form into main_template.pt
I'm trying to work the contact form that is baked into plone into my site's main_template. I'm doing so to make the functionality present in "get in touch" nav button on this site work in a plone setting. My approach to doing this was by slightly reworking contact-info.cpt to make it a macro and using that macro within...
[ "You cannot use a Controller Page Template (.cpt) as a macro, unchanged.\nFirst of all, a Controller Python Script expects a few parameters in it's \"environment\" (the options/state structure is one of these) that you don't have present when re-using it's TAL statements. You'll have to rework the template to not r...
[ 4, 0 ]
[]
[]
[ "plone", "python" ]
stackoverflow_0007395538_plone_python.txt
Q: Installing python 2.7.2 on Debian 5.0 I'm having some trouble running the ./make command in my debian command line to install python 2.7.2. I untarred my download from Python.org and ran ./configure which appeared to have worked fine. Unfortunately when I type in ./make I get the following error: ./make: No such ...
Installing python 2.7.2 on Debian 5.0
I'm having some trouble running the ./make command in my debian command line to install python 2.7.2. I untarred my download from Python.org and ran ./configure which appeared to have worked fine. Unfortunately when I type in ./make I get the following error: ./make: No such file or directory Not sure why this occurs...
[ "its not ./make\ntry\n\"make\"\nas it is\n", "When you type ./configure, it runs a executable script in the current directory (labeled with a .) called configure. \nMake is an executable file, usually located somewhere like /usr/bin, which uses a file in the directory to run a bunch of commands depending on wheth...
[ 2, 2 ]
[]
[]
[ "debian", "python" ]
stackoverflow_0007435593_debian_python.txt
Q: Integrate Qt with Windows 7 taskbar using python? I'm looking for a way to using some of the Windows 7 task bar features - specifically progressbar and jump lists - in a python application that uses Qt for the UI. The questions I've seen on SO are all 1-2 years old and either say Qt isn't there yet but the next ve...
Integrate Qt with Windows 7 taskbar using python?
I'm looking for a way to using some of the Windows 7 task bar features - specifically progressbar and jump lists - in a python application that uses Qt for the UI. The questions I've seen on SO are all 1-2 years old and either say Qt isn't there yet but the next version will have it (which has since been released) or p...
[ "For C++ there is something called EcWin7, just look: http://code.google.com/p/dukto/source/browse/trunk/src/ecwin7.cpp\nMaybe it's not so hard to make Python bindings for it but I'm not sure.\nHope it helps anyhow :)\n" ]
[ 2 ]
[]
[]
[ "pyqt", "pyside", "python", "qt", "taskbar" ]
stackoverflow_0007136179_pyqt_pyside_python_qt_taskbar.txt
Q: Changing display order of tags in a table (Google App Engine-Python) I have a table in UserAdminPage where tags are listed by alpha order (code below). I want to add a link that will change the order to by date. I know I will change the query.order(owner_tag") to query.order("-date") but do I need to create a new ...
Changing display order of tags in a table (Google App Engine-Python)
I have a table in UserAdminPage where tags are listed by alpha order (code below). I want to add a link that will change the order to by date. I know I will change the query.order(owner_tag") to query.order("-date") but do I need to create a new handler? I don't understand what the link should be where the question ma...
[ "There are a number of ways to optimize your approach to this, but to answer your specific question - rather than duplicate your handler you could add a GET parameter to the link and then check for that while constructing your query:\nclass UserAdminPage(webapp.RequestHandler):\n def get(self):\n order_by...
[ 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007436500_google_app_engine_python.txt
Q: Looking for non-Boost::Python C++ Python embedding framework I have a project of mine, written in C++, that has now progressed to a stage where I require an embedded programming language. I've chosen Python for several reasons, and have been playing around with revealing an API to a dynamically-loaded Python modul...
Looking for non-Boost::Python C++ Python embedding framework
I have a project of mine, written in C++, that has now progressed to a stage where I require an embedded programming language. I've chosen Python for several reasons, and have been playing around with revealing an API to a dynamically-loaded Python module. It works well, and I think I will stick with Python for the for...
[ "I was facing nearly the same problem but at the end I sticked Boost::Python ;) However an option to Boost::Python is Swig. If you use Swig you also, don't have to write so much boilerplate code than you have to with Boost::Python.\n" ]
[ 3 ]
[]
[]
[ "c++", "python", "python_embedding" ]
stackoverflow_0007436828_c++_python_python_embedding.txt
Q: Do Python equal types have different values ever? In Python, if I have the following code: r = Numeric(str) i = int(r) if r == i : return i return r Is this equivalent to: r = Numeric(str) return r Or do the == values of different types r and i give different return values r and i? A: It all depends if the...
Do Python equal types have different values ever?
In Python, if I have the following code: r = Numeric(str) i = int(r) if r == i : return i return r Is this equivalent to: r = Numeric(str) return r Or do the == values of different types r and i give different return values r and i?
[ "It all depends if the class implements an adequate __eq__ method to override == operator.\nEdit: Added a little example:\n>>> class foo:\n... def __init__(self,x):\n... self.x = x\n... def __eq__(self,y):\n... return int(self.x)==int(y)\n... \n>>> f = foo(5)\n>>> f == '5'\nTrue\n>>> 5 == '5...
[ 4, 2, 1 ]
[]
[]
[ "floating_point", "integer", "language_lawyer", "python", "type_conversion" ]
stackoverflow_0007436902_floating_point_integer_language_lawyer_python_type_conversion.txt
Q: How to stop python.exe window from closing when running Fabric Preface: Using Windows 7, Python 2.7, Fabric 1.2.2 I am trying to run Fabric script on windows, from a simple tutorial. I have my "fabfile.py" with a simple hello world program, and then I execute: fab hello However, every time a python.exe window pop...
How to stop python.exe window from closing when running Fabric
Preface: Using Windows 7, Python 2.7, Fabric 1.2.2 I am trying to run Fabric script on windows, from a simple tutorial. I have my "fabfile.py" with a simple hello world program, and then I execute: fab hello However, every time a python.exe window pops up and immediately closes! I have no way of actually seeing what t...
[ "On Windows, you can use python with or without the command shell. This is useful when you are running a GUI program and you do not want a associated terminal to open up.\nThis is possible if the python executable you are referring to is associated with pythonw.exe which is used to surpress the terminal. \nFab is a...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0007436145_python.txt
Q: Http protocol, Content-Length, get page content Python I'm trying to code my own Python 3 http library to learn more about sockets and the Http protocol. My question is, if a do a recv(bytesToRead) using my socket, how can I get only the header and then with the Content-Length information, continue recieving the p...
Http protocol, Content-Length, get page content Python
I'm trying to code my own Python 3 http library to learn more about sockets and the Http protocol. My question is, if a do a recv(bytesToRead) using my socket, how can I get only the header and then with the Content-Length information, continue recieving the page content? Isn't that the purpose of the Content-Length he...
[ "In the past to accomplish this, I will read a portion of the socket data into memory, and then read from that buffer until a \"\\r\\n\\r\\n\" sequence is encountered (you could use a state machine to do this or simply use the string.find() function. Once you reach that sequence you know all of the headers have be...
[ 2 ]
[]
[]
[ "http_headers", "python" ]
stackoverflow_0007437147_http_headers_python.txt
Q: How to generate a `kwargs` list? From an external file I generate the following dictionary: mydict = { 'foo' : 123, 'bar' : 456 } Given a function that takes a **kwargs argument, how can generate the keyword-args from that dictionary? A: def foo(**kwargs): pass foo(**{ 'foo' : 123, 'bar' : 456 })
How to generate a `kwargs` list?
From an external file I generate the following dictionary: mydict = { 'foo' : 123, 'bar' : 456 } Given a function that takes a **kwargs argument, how can generate the keyword-args from that dictionary?
[ "def foo(**kwargs):\n pass\n\nfoo(**{ 'foo' : 123, 'bar' : 456 })\n\n" ]
[ 34 ]
[]
[]
[ "keyword_argument", "python" ]
stackoverflow_0007437213_keyword_argument_python.txt
Q: TypeError for optional start parameter in string.find() I'm having a bit of trouble understanding how this is happening. When I run the following: def find_in_string(string, ch): count = 0 index = 0 while 0 <= index < len(string): if string.find(string, ch, index) != -1: return True...
TypeError for optional start parameter in string.find()
I'm having a bit of trouble understanding how this is happening. When I run the following: def find_in_string(string, ch): count = 0 index = 0 while 0 <= index < len(string): if string.find(string, ch, index) != -1: return True find_in_string('asdfasdf', 's') Here's what is I get: Type...
[ "Your misunderstanding seems to come from importing the string module as well as naming your variable string. \nYou don't need to import the module to use find, and you could name your variable something else if you do need to import the module to do something else.\nThe type is str not string.\nfind doesn't work l...
[ 1 ]
[]
[]
[ "python", "python_2.x", "string" ]
stackoverflow_0007437283_python_python_2.x_string.txt
Q: Can I open a text file in one script, then write to that file in a child script? This is a little bit of a strange question, but I have a bunch of automation scripts (using Sikuli/Jython), that i want to run from a parent script for regression purposes. Now I also have a method of capturing exceptions that I want...
Can I open a text file in one script, then write to that file in a child script?
This is a little bit of a strange question, but I have a bunch of automation scripts (using Sikuli/Jython), that i want to run from a parent script for regression purposes. Now I also have a method of capturing exceptions that I want to log to a text file. SO here's how it currently works: Master Script --> specific ...
[ "\nNow I also have a method of capturing exceptions that I want to log to a text file.\n\nUse logging. http://docs.python.org/library/logging.html\nThe problem has already been solved by them. No work for you.\n" ]
[ 2 ]
[]
[]
[ "jython", "python", "sikuli" ]
stackoverflow_0007437156_jython_python_sikuli.txt
Q: Can Python be used for client side web development? If yes are there any frameworks/Tutorials/tips/etc recommended? N00b at Python but I have tons of PHP experience and wanted to expand my skill set. I know Python is great at server side execution, just wanted to know about client side as well. A: Have you seen...
Can Python be used for client side web development?
If yes are there any frameworks/Tutorials/tips/etc recommended? N00b at Python but I have tons of PHP experience and wanted to expand my skill set. I know Python is great at server side execution, just wanted to know about client side as well.
[ "Have you seen Skulpt?\n\nSkulpt is an entirely in-browser implementation of Python.\nNo preprocessing, plugins or server-side support required, just write Python and reload.\n\n", "You can use pyjamas to convert Python code to JS code that runs in the browser (note that pyjamas also offers much more). So YES, yo...
[ 47, 21, 8, 7, 6, 3, 2 ]
[ "No. Browsers don't run Python.\n" ]
[ -1 ]
[ "client_side", "python" ]
stackoverflow_0001540214_client_side_python.txt
Q: Tricky Logic Need help? wah I tried it but stucked up here I get instr and split on mind but my both approaches arent able to make it Here 7,2,3,4,9,2 I mean its length of substrings 1234567 89 'if its 7(length of sub-string) and 2(next sub-string length) then 1233456789 ' append into one 123456 123 ' i...
Tricky Logic Need help?
wah I tried it but stucked up here I get instr and split on mind but my both approaches arent able to make it Here 7,2,3,4,9,2 I mean its length of substrings 1234567 89 'if its 7(length of sub-string) and 2(next sub-string length) then 1233456789 ' append into one 123456 123 ' if its 6(length of sub-string)...
[ "All I can suggest to you is to start by writing some simple testcases while improving your implementation:\n#/usr/bin/env python\n# this file is tester.py for testing my super-complicated algorithm\ndef algorithm(data):\n items = split(data)\n out = items[0]\n while item in items[1:]:\n if len(item...
[ 0 ]
[]
[]
[ "excel", "perl", "python", "vba" ]
stackoverflow_0007436410_excel_perl_python_vba.txt
Q: Pythonic way to get `package.module.Class` Given a string a the form 'package.module.Class', is there any simple way in Python to get the class object directly (assuming the module isn't yet imported)? If not, what is the cleanest way to separate the 'package.module' part from the 'Class' part, __import__() the mo...
Pythonic way to get `package.module.Class`
Given a string a the form 'package.module.Class', is there any simple way in Python to get the class object directly (assuming the module isn't yet imported)? If not, what is the cleanest way to separate the 'package.module' part from the 'Class' part, __import__() the module, and then get the class from that?
[ "import sys\ndef str_to_obj(astr):\n '''\n str_to_obj('scipy.stats.stats') returns the associated module\n str_to_obj('scipy.stats.stats.chisquare') returns the associated function\n '''\n # print('processing %s'%astr)\n try:\n return globals()[astr]\n except KeyError:\n try:\n ...
[ 3, 3 ]
[]
[]
[ "import", "module", "python", "string" ]
stackoverflow_0007437948_import_module_python_string.txt
Q: Python blocking recv returns less data than asked for I have an echo server in C and a test client in Python. The server has a limited read buffer, eg 16bytes. When a client send more than 16 bytes, it will first read 16, write back to client and then read again. I tested the server with telnet, and I got back th...
Python blocking recv returns less data than asked for
I have an echo server in C and a test client in Python. The server has a limited read buffer, eg 16bytes. When a client send more than 16 bytes, it will first read 16, write back to client and then read again. I tested the server with telnet, and I got back the same string as my input, even it's longer than 16 bytes. ...
[ "The length you give to recv is a maximum, not a target. There's no guarantee that recv will wait for Len bytes to be received - it can return as soon as it's read any data at all.\nThe man page for recv says: The receive calls normally return any data available, up to the requested amount, rather than waiting for...
[ 8 ]
[]
[]
[ "python", "recv" ]
stackoverflow_0007438013_python_recv.txt
Q: emacs switch from Shell to gdb or pdb mode Let's say I have an open gdb or pdb session in an emacs shell. So the major mode is "Shell:run" Now I want to convert that buffer to gdb or pdb (python debugger) major mode. I tried M-X gud-mode and that switched the mode to "Debugger:run". But it does not actually wor...
emacs switch from Shell to gdb or pdb mode
Let's say I have an open gdb or pdb session in an emacs shell. So the major mode is "Shell:run" Now I want to convert that buffer to gdb or pdb (python debugger) major mode. I tried M-X gud-mode and that switched the mode to "Debugger:run". But it does not actually work; for example when I type "up", "down", or "n" ...
[ "If all you're looking for is source code line tracking, my emacs does pdb source line tracking in M-x shell buffers just fine. No need to enable any other mode.\n" ]
[ 0 ]
[]
[]
[ "c++", "emacs", "gdb", "python" ]
stackoverflow_0007435366_c++_emacs_gdb_python.txt
Q: Python QtWebKit save webpage to file What's the best and simplest way to save a webpage displayed with QWebView() to file? from PyQt4.QtCore import * from PyQt4.QtWebKit import * from PyQt4.QtGui import * from PyQt4.QtScript import * import sys import time currentfile = "test.htm" app = QApplication(sys.argv) web...
Python QtWebKit save webpage to file
What's the best and simplest way to save a webpage displayed with QWebView() to file? from PyQt4.QtCore import * from PyQt4.QtWebKit import * from PyQt4.QtGui import * from PyQt4.QtScript import * import sys import time currentfile = "test.htm" app = QApplication(sys.argv) web = QWebView() web.load(QUrl("http://news.g...
[ "As the page loading is asynchronous, you have to wait for the loadFinished signal before trying to save it.\nThen you can retrieve the page content with web.page().currentFrame().toHtml() which returns a python unicode string, which you can write to a file with the codecs module:\nfrom PySide.QtCore import *\nfrom...
[ 6, 0 ]
[]
[]
[ "pyqt4", "python", "qtwebkit" ]
stackoverflow_0007433232_pyqt4_python_qtwebkit.txt
Q: PropertyError while sorting by date (Google App Engine - Python) See my previous question. I updated the code as per Kevin P's answer but now I am not able to sort with newest tag on top. My comments are below at query.order("date"). Do you know why date with a minus sign works but it does not work without minus s...
PropertyError while sorting by date (Google App Engine - Python)
See my previous question. I updated the code as per Kevin P's answer but now I am not able to sort with newest tag on top. My comments are below at query.order("date"). Do you know why date with a minus sign works but it does not work without minus sign? my model is: class Owner(db.Model): owner = db.UserProperty()...
[ "Right now you are relying on the fact that keys typically generate in sequence, which isn't always the case. Add a date property to your model:\ndate= db.DateTimeProperty(auto_now_add=True)\n\nAlso fix your GET parameter so that it's consistent. Here:\n<a href=\"/useradminpage?order=xyz\"><span id=small>most rec...
[ 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007438428_google_app_engine_python.txt
Q: i am getting error "no schemaLocation attribute in import" when using Python client accessing JIRA via SOAP here is the sample code : #!/usr/bin/env python # Sample Python client accessing JIRA via SOAP. By default, accesses # http://jira.atlassian.com with a public account. Methods requiring # more than basic u...
i am getting error "no schemaLocation attribute in import" when using Python client accessing JIRA via SOAP
here is the sample code : #!/usr/bin/env python # Sample Python client accessing JIRA via SOAP. By default, accesses # http://jira.atlassian.com with a public account. Methods requiring # more than basic user-level access are commented out. Change the URL # and project/issue details for local testing. # # Note: This ...
[ "I changed the JIRA Python CLI code to use suds instead of SOAPpy a while ago and haven't looked back. SOAPpy is pretty old and seems unsupported now.\n" ]
[ 0 ]
[]
[]
[ "jira", "python", "soap", "soappy" ]
stackoverflow_0007434578_jira_python_soap_soappy.txt
Q: need to run python script via cron job using cpanel I need urgent help in this regard. I am trying to run a Python script via cron job on cPanel. The web hosting server is using cPanel Version 11.30.3 (build 5). The cron job is set successfully and it is executing the file, but the file failed because of the follo...
need to run python script via cron job using cpanel
I need urgent help in this regard. I am trying to run a Python script via cron job on cPanel. The web hosting server is using cPanel Version 11.30.3 (build 5). The cron job is set successfully and it is executing the file, but the file failed because of the following error which I recieved on email: /bin/sh: /home/some...
[ "Note that in the error message, there is a line break after /usr/bin/python and before the : that clarifies the message. This suggests that the operating system is seeking the file not at /usr/bin/python but at /usr/bin/python<newline>.\nMost likely, you copied the python file from a Windows system which has a st...
[ 3 ]
[]
[]
[ "cpanel", "python" ]
stackoverflow_0007438760_cpanel_python.txt
Q: Python Generators and yield : How to know which line the program is at Suppose you have a simple generator in Python like this : Update : def f(self): customFunction_1(argList_1) yield customFunction_2(argList_2) yield customFunction_3(argList_3) yield ... I call f() in another...
Python Generators and yield : How to know which line the program is at
Suppose you have a simple generator in Python like this : Update : def f(self): customFunction_1(argList_1) yield customFunction_2(argList_2) yield customFunction_3(argList_3) yield ... I call f() in another script like : h=f() while True: try: h.next() ...
[ "You can use enumerate() to count: \ndef f():\n\n ...\n yield\n ...\n yield\n ... \n\n\nfor step, value in enumerate(f()):\n try:\n time.sleep(2)\n except KeyboardInterrupt:\n print(step) # step holds the number of the last executed function\n\n(because in your example yield does ...
[ 4, 2, 1, 1 ]
[]
[]
[ "generator", "python", "yield" ]
stackoverflow_0007437751_generator_python_yield.txt
Q: setup.py and source control repository I am about to build a new python lib and I was seeking information concerning packaging in Python. I understand that "setup.py" is the script that controls everything. I wonder how to deal with it when there are external libraries in svn for instance. How to download automat...
setup.py and source control repository
I am about to build a new python lib and I was seeking information concerning packaging in Python. I understand that "setup.py" is the script that controls everything. I wonder how to deal with it when there are external libraries in svn for instance. How to download automatically a given version from the repository u...
[ "docs for this are at the cheese shop \nuse the requires keyword\n", "I may not have understood the problem correctly.\nFor any additional dependencies, you mention them in setup.py as\n\ninstall_requires=['module1 >= 1.3', 'module2 >=1.8.2']\n\nWhen you use setuptools, easy_install oo pip, these external depende...
[ 1, 0 ]
[]
[]
[ "packaging", "python", "setup.py" ]
stackoverflow_0007434837_packaging_python_setup.py.txt
Q: Bootstrapping tests and using Python test discovery A problem I continue to have it "bootstrapping" my tests. The problem that I have is exactly what this guy has. The top solution talks about creating a "boostrap" script. I presume that I must then enumerate all of the tests to be run, or use test manifests in t...
Bootstrapping tests and using Python test discovery
A problem I continue to have it "bootstrapping" my tests. The problem that I have is exactly what this guy has. The top solution talks about creating a "boostrap" script. I presume that I must then enumerate all of the tests to be run, or use test manifests in the __init__.py files using the __all__ keyword. However,...
[ "I got it! \nUsing this one script that I wrote and called it \"runtests.py\" and placed in my project root, I was able to \"bootstrap\" that is to run some initialization code AND use discovery. Woot!\nIn my case, the \"bootstrap\" code is the two lines that say:\nimport sys\nsys.path.insert(0, 'lib.zip')\n\nTha...
[ 4, 0 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0007432359_python_unit_testing.txt
Q: Sorting python dictionary by the keys >>> the_values = [u'abc', u'kfc', u'listproperty', u'models', u'new', u'newer', u'note', u'order', u'tag', u'test', u'type'] >>> the_keys = [1, 2, 1, 2, 1, 1, 1, 1, 2, 1, 1] d2 = dict(zip(the_keys, the_values)) >>> d2 {1: u'type', 2: u'tag'} Can you give me a clue why only "t...
Sorting python dictionary by the keys
>>> the_values = [u'abc', u'kfc', u'listproperty', u'models', u'new', u'newer', u'note', u'order', u'tag', u'test', u'type'] >>> the_keys = [1, 2, 1, 2, 1, 1, 1, 1, 2, 1, 1] d2 = dict(zip(the_keys, the_values)) >>> d2 {1: u'type', 2: u'tag'} Can you give me a clue why only "type" and "tag" are taken? I am trying to so...
[ "Keys must be unique, so using 1 and 2 as the only keys means you can only have two values associated with them.\nWhen you're creating the dictionary, you're setting the key to correspond to a value. So first, 1 -> abc, 2 -> kfc. But then you're continually overriding the keys to give them different values. In the ...
[ 3, 3, 2 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0007439439_python_sorting.txt
Q: Python: Return list result problem in a function If I do this with print function def numberList(items): number = 1 for item in items: print(number, item) number = number + 1 numberList(['red', 'orange', 'yellow', 'green']) I get this 1 red 2 orange 3 yellow 4 green if I then change...
Python: Return list result problem in a function
If I do this with print function def numberList(items): number = 1 for item in items: print(number, item) number = number + 1 numberList(['red', 'orange', 'yellow', 'green']) I get this 1 red 2 orange 3 yellow 4 green if I then change the print function to return function I get just only...
[ "return ends the function, while yield creates a generator that spits out one value at a time:\ndef numberList(items):\n number = 1\n for item in items:\n yield str((number, item))\n number = number + 1\n\nitem_lines = '\\n'.join(numberList(['red', 'orange', 'yellow', 'green']))\n\nalternati...
[ 8, 1, 0 ]
[]
[]
[ "function", "list", "python", "return" ]
stackoverflow_0007439513_function_list_python_return.txt
Q: python - Count number of occurrences of each number I have a long string of numbers separated by commas. I can search and count the number of occurrences of most numbers, or more accurately, 2 digit numbers. IF I have a number sequences like: 1,2,3,4,5,1,6,7,1,8,9,10,11,12,1,1,2 and I want to count how many times ...
python - Count number of occurrences of each number
I have a long string of numbers separated by commas. I can search and count the number of occurrences of most numbers, or more accurately, 2 digit numbers. IF I have a number sequences like: 1,2,3,4,5,1,6,7,1,8,9,10,11,12,1,1,2 and I want to count how many times the number 1 appears I should really get 5. However, beca...
[ "On 2.7+, just split and use the collections.Counter:\nfrom collections import Counter\nnumstring = \"1,2,3,4,5,1,6,7,1,8,9,10,11,12,1,1,2\"\nnumcount = Counter(numstring.split(','))\n\nor, Pre-2.7:\nfrom collections import defaultdict\nnumstring = \"1,2,3,4,5,1,6,7,1,8,9,10,11,12,1,1,2\"\nnumcount = defaultdict(in...
[ 8 ]
[]
[]
[ "json", "python" ]
stackoverflow_0007439578_json_python.txt
Q: What are some good Python ORM solutions? I'm evaluating and looking at using CherryPy for a project that's basically a JavaScript front-end from the client-side (browser) that talks to a Python web service on the back-end. So, I really need something fast and lightweight on the back-end that I can implement using ...
What are some good Python ORM solutions?
I'm evaluating and looking at using CherryPy for a project that's basically a JavaScript front-end from the client-side (browser) that talks to a Python web service on the back-end. So, I really need something fast and lightweight on the back-end that I can implement using Python that then speaks to the PostgreSQL DB v...
[ "If you're looking for lightweight and are already familiar with django-style declarative models, check out peewee: \nhttps://github.com/coleifer/peewee\nExample:\nimport datetime\nfrom peewee import *\n\nclass Blog(Model):\n name = CharField()\n\nclass Entry(Model):\n blog = ForeignKeyField(Blog)\n title ...
[ 132, 127, 84, 29, 17, 10, 6, 1, 1, 0 ]
[ "SQLAlchemy is very, very powerful. However it is not thread safe make sure you keep that in mind when working with cherrypy in thread-pool mode. \n", "I'd check out SQLAlchemy \nIt's really easy to use and the models you work with aren't bad at all. Django uses SQLAlchemy for it's ORM but using it by itself lets...
[ -2, -7 ]
[ "orm", "python" ]
stackoverflow_0000053428_orm_python.txt
Q: Error "wrong ELF class" using ctypes after changing from a 32 to 64Bit Ubuntu installation my python+ctypes+c99 code is broken. I read so far, that the error ./libfoo.so: wrong ELF class: ELFCLASS32 means, that my libfoo.so[1] is a 32Bit library and that python wants a 64Bit version. How do I tell gcc/ctypes to ge...
Error "wrong ELF class" using ctypes
after changing from a 32 to 64Bit Ubuntu installation my python+ctypes+c99 code is broken. I read so far, that the error ./libfoo.so: wrong ELF class: ELFCLASS32 means, that my libfoo.so[1] is a 32Bit library and that python wants a 64Bit version. How do I tell gcc/ctypes to generate the library as 32Bit? Thanks for an...
[ "You need to compile the object file as 64 bit and position independent, then link the object file to the shared library with 64 bit options. Something like:\ngcc -c -fPIC -m64 -std=c99 -lm -D_GNU_SOURCE -Wall -pedantic -fopenmp -o foo.o foo.c\ngcc -m64 -shared -Wl,-soname,libfoo.so -o libfoo.so foo.o\n\nThat shoul...
[ 3, 0 ]
[ "Reinstall the crypto. \nThat is how I solved this problem.\nhttp://www.amk.ca/python/code/crypto.html\n" ]
[ -1 ]
[ "32bit_64bit", "ctypes", "gcc", "python" ]
stackoverflow_0006126005_32bit_64bit_ctypes_gcc_python.txt
Q: python : ValueError: invalid literal for int() with base 10: ' ' I have a text file which contains entry like 70154::308933::3 UserId::ProductId::Score I wrote this program to read: (Sorry the indendetion is bit messed up here) def generateSyntheticData(fileName): dataDict = {} # rowDict = [] innerDict = {} ...
python : ValueError: invalid literal for int() with base 10: ' '
I have a text file which contains entry like 70154::308933::3 UserId::ProductId::Score I wrote this program to read: (Sorry the indendetion is bit messed up here) def generateSyntheticData(fileName): dataDict = {} # rowDict = [] innerDict = {} try: # for key in range(5): # count = 0 myFile = open(fil...
[ "The \"spaces\" thay you are seeing appear to be NULs (\"\\x00\"). There is a 99.9% chance that your file is encoded in UTF-16, UTF-16LE, or UTF-16BE. If this is a one-off file, just open it with Notepad and save as \"ANSI\", not \"Unicode\" and not \"Unicode bigendian\". If however you need to process it as is, yo...
[ 3, 2 ]
[]
[]
[ "file", "python" ]
stackoverflow_0007439025_file_python.txt
Q: how would i have python check to see if a list was sent to/from socket server? I'm trying to have a pickle file "server side" store a list of player coordinates. Server then sends that pickle file to the client. Also, i need a way for the client to look in the pickled file, for those coordinates. How would i have ...
how would i have python check to see if a list was sent to/from socket server?
I'm trying to have a pickle file "server side" store a list of player coordinates. Server then sends that pickle file to the client. Also, i need a way for the client to look in the pickled file, for those coordinates. How would i have the client look in the pickle file that would have all sorts of different informatio...
[ "Just unpickle it at the client end and check for what you need to verify.\nc = pickle.load( open( \"fromserver.p\" ) )\n\nI am assuming that you are written or writing both the server and the client part. And in which case, you decided upfront what you store and retrieve. For e.g. if you stored a list named l in ...
[ 0 ]
[]
[]
[ "list", "pickle", "python", "sockets" ]
stackoverflow_0007439830_list_pickle_python_sockets.txt
Q: Can't import django packages with nosegae I am trying to get started with using nosegae, however I run into the issue that I can't seem to get it to pass even the simplest of cases when using django. when running without the --without-sandbox flag both the following tests fail def test_import_django (): impor...
Can't import django packages with nosegae
I am trying to get started with using nosegae, however I run into the issue that I can't seem to get it to pass even the simplest of cases when using django. when running without the --without-sandbox flag both the following tests fail def test_import_django (): import django def test_import_django_http (): ...
[ "Read https://docs.djangoproject.com/en/dev/topics/testing/ about Django testing.\nAs I know it's better to use unittest or doctest shipped with django as it have several improvements for django-specific testing like form field output testing and some database features. Hovewer it's not essential and if you want to...
[ 0 ]
[]
[]
[ "google_app_engine", "nose", "python" ]
stackoverflow_0007439536_google_app_engine_nose_python.txt