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: How to store the int of specific bits(24bits, 16bits, etc) in Python? When I do the compress the data with compact code, I don't know how to deal with the integer, I need to store an integer into 1bytes, 2bytes, 3bytes, etc, memory, How can I do this in Python. Or, how to change the tuple (1, 0, 1, ..., 1) (24bits...
How to store the int of specific bits(24bits, 16bits, etc) in Python?
When I do the compress the data with compact code, I don't know how to deal with the integer, I need to store an integer into 1bytes, 2bytes, 3bytes, etc, memory, How can I do this in Python. Or, how to change the tuple (1, 0, 1, ..., 1) (24bits) into exact 3bytes storage
[ "The struct module in the standard library packs data into bytes.\n", "If you need to pack in arbitrary numbers of bytes then it might be better to use a bytearray than rely on the struct module, for example:\n>>> a = bytearray(3) # create 3 byte array\n>>> a[0] = 0x3e\n>>> a[1] = 0xff\n>>> a[2] = 0x00\n\nNote t...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007078278_python.txt
Q: IPython iterate main loop manually? Can i somehow instance ipython (or even better, ipython-qtconsole) and step trough its's (IPython's) main loop manually? I want to edit panda3d programs on the fly. EDIT1: Here is code sample which should clarify a bit what i want to do. import sys from PyQt4.QtCore import * fr...
IPython iterate main loop manually?
Can i somehow instance ipython (or even better, ipython-qtconsole) and step trough its's (IPython's) main loop manually? I want to edit panda3d programs on the fly. EDIT1: Here is code sample which should clarify a bit what i want to do. import sys from PyQt4.QtCore import * from PyQt4.QtGui import * from direct.showb...
[ "By \"edit panda3d programs on the fly\", do you just mean changing things in order to test your running program? Or actually making persistent edits to your program's structure in the interactive environment?\nSimply stepping over your loop in an interactive python session is quite easy. You can just replace while...
[ 2, 1 ]
[]
[]
[ "ipython", "python" ]
stackoverflow_0007020161_ipython_python.txt
Q: launch a PyQT window from a main PyQt window, and get the user input? I have a main PyQt window, from which I need to get a string of User Input when they hit a certain button. Here is my code for the User Input window: class InputDialog(QtGui.QDialog): ''' this is for when you need to get some user input t...
launch a PyQT window from a main PyQt window, and get the user input?
I have a main PyQt window, from which I need to get a string of User Input when they hit a certain button. Here is my code for the User Input window: class InputDialog(QtGui.QDialog): ''' this is for when you need to get some user input text ''' def __init__(self, parent=None, title='user input', label='co...
[ "Use\ninputter.exec_()\n\ninstead of\ninputter.show()\n\nFrom: http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qdialog.html#exec\n\nThis method is also a Qt slot with the C++ signature int exec().\nShows the dialog as a modal dialog, blocking until the user closes it.\n The function returns a DialogCode...
[ 5, 3 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0007046882_pyqt_python.txt
Q: Lambda instead of "if" statement I've heard that it is possible to substitute an if statement by using a lambda. Is this possible in Python? If so, how? A: Perhaps you are referring to something like this (Lambda calculus)? If = lambda test, x, y: test(x, y) True = lambda x, y: x False = lambda x, y: y Which y...
Lambda instead of "if" statement
I've heard that it is possible to substitute an if statement by using a lambda. Is this possible in Python? If so, how?
[ "Perhaps you are referring to something like this (Lambda calculus)?\nIf = lambda test, x, y: test(x, y)\nTrue = lambda x, y: x\nFalse = lambda x, y: y\n\nWhich you could use like...\n# I guess you have to convert them sometimes... oh well\nC = lambda b: [False, True][b]\n\nx = If(C(2 > 3), \"Greater\", \"Less\")\n...
[ 6, 4, 3, 1, 0 ]
[]
[]
[ "if_statement", "lambda", "lambda_calculus", "python" ]
stackoverflow_0007076703_if_statement_lambda_lambda_calculus_python.txt
Q: CertificateValidationUnsupported using oauth2/httplib2 on Python 2.4 At a first look, python-ouath2 seemed to have many problems with Python 2.4, so I managed to get a patch on that by Googling. But I'm still getting an error from httplib2 as follows: CertificateValidationUnsupported: SSL certificate validation...
CertificateValidationUnsupported using oauth2/httplib2 on Python 2.4
At a first look, python-ouath2 seemed to have many problems with Python 2.4, so I managed to get a patch on that by Googling. But I'm still getting an error from httplib2 as follows: CertificateValidationUnsupported: SSL certificate validation is not supported without the ssl module installed. To avoid this error, i...
[ "For Python 2.3-2.5, you need to install the ssl module from PyPI. If you have setuptools installed, you should be able to just do easy_install ssl. The documentation for the library is the Python ssl docs, there are no separate docs for the external version.\n" ]
[ 2 ]
[]
[]
[ "django", "httplib2", "oauth_2.0", "python", "ssl" ]
stackoverflow_0007079007_django_httplib2_oauth_2.0_python_ssl.txt
Q: In python, when you pass internally defined functions into other functions, how does it keep the variables? For example, why does this work? def func1(func1var): def innerfunc(innerfuncvar): if func1var == 1: print innerfuncvar else: print 5 func2(innerfunc) def f...
In python, when you pass internally defined functions into other functions, how does it keep the variables?
For example, why does this work? def func1(func1var): def innerfunc(innerfuncvar): if func1var == 1: print innerfuncvar else: print 5 func2(innerfunc) def func2(function): function(9) When innerfunc is called in func2, how does it know the values of func1var?
[ "You've created a closure. Basically, think of it like this, from the point of view of the inner function:\nfunc1var = whatever\n\ndef func2(function):\n function(9)\n\ndef innerfunc(innerfuncvar):\n if func1var = 1:\n print innerfuncvar\n else:\n print 5\n\nfunc2(innerfunc)\n\nIt doesn't c...
[ 7, 6, 2 ]
[]
[]
[ "function", "function_pointers", "python" ]
stackoverflow_0007078840_function_function_pointers_python.txt
Q: How can I iterate through a list of proxies with Socksipy For some reason I can get this to work, using single proxy everything seems fine. #This works import socks import urllib2 socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '68.xx.193.xx', 666) socks.wrapmodule(urllib2) print urllib2.urlopen('http://automation...
How can I iterate through a list of proxies with Socksipy
For some reason I can get this to work, using single proxy everything seems fine. #This works import socks import urllib2 socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '68.xx.193.xx', 666) socks.wrapmodule(urllib2) print urllib2.urlopen('http://automation.whatismyip.com/n09230945.asp').read() & #This doesn't import...
[ "Run this:\nproxies=['68.xx.193.xx','xx.178.xx.70','98.xx.84.xx','83.xx.86.xx']\nports=[666,1080,859,910]\nfor i in range(len(proxies)):\n print (repr(proxies[i]), ports[i])\n\nYou'll get\n(\"'68.xx.193.xx'\", 666)\n(\"'xx.178.xx.70'\", 1080)\n(\"'98.xx.84.xx'\", 859)\n(\"'83.xx.86.xx'\", 910)\n\nYou're adding q...
[ 0 ]
[]
[]
[ "proxy", "python", "sockets" ]
stackoverflow_0007079184_proxy_python_sockets.txt
Q: How to set folder write permissions for application add-on with python I have python script that works fine but only when run as stand-alone, while I need it as a script. It uses external .exe compiled C library in such manner: # trigger the shell command import subprocess p = subprocess.Popen('qvoronoi TI data.t...
How to set folder write permissions for application add-on with python
I have python script that works fine but only when run as stand-alone, while I need it as a script. It uses external .exe compiled C library in such manner: # trigger the shell command import subprocess p = subprocess.Popen('qvoronoi TI data.txt TO results.txt p FN Fv QJ', shell=True) p.wait() # open the results file...
[ "Try print os.getcwd(). \nYour current working directory is not the directory where results.txt is being created. \nThe IOError is on the line where you read the file, not write it, because you're not specifying where to look for results.txt.\n" ]
[ 1 ]
[]
[]
[ "path", "permissions", "python" ]
stackoverflow_0007078541_path_permissions_python.txt
Q: Python - Multiprocessing.processes become copies of the main process when run from executable I just discovered a bizarre bug in my program related to its use of Python's multiprocessing module. Everything works fine when I run the program from the source on my machine. But I've been building it into an executable...
Python - Multiprocessing.processes become copies of the main process when run from executable
I just discovered a bizarre bug in my program related to its use of Python's multiprocessing module. Everything works fine when I run the program from the source on my machine. But I've been building it into an executable using pyinstaller, and for some reason the behavior of multiprocessing changes drastically when I ...
[ "On Windows, multiprocessing tries to emulate the Unix fork() system call by starting new instances of your executable, and execute its child process routine (multiprocessing.forking.main()) therein. With the standard Python interpreter (python.exe), multiprocessing can pass the -c parameter to run custom code. F...
[ 11 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0007067787_multiprocessing_python.txt
Q: Is there python code in the Python standard library that uses variable names that shadow builtins? [Excluding any test code that just mocks a builtin] Given that many builtins have been added over time, if there are multiple occurrences, I'd accept an answer showing a module or some code that was created after tha...
Is there python code in the Python standard library that uses variable names that shadow builtins?
[Excluding any test code that just mocks a builtin] Given that many builtins have been added over time, if there are multiple occurrences, I'd accept an answer showing a module or some code that was created after that builtin existed. My rationale for asking is that after posting a question on the python mailing list, ...
[ "The builtin I most often shadow is id, both because it's so useful as a variable name, and the builtin is so rarely called anyway. A quick look in the 2.7 standard library turned up a number of uses:\naifc.py: if id == marker[0]:\naifc.py: id = _read_short(chunk)\naifc.py: if ...
[ 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007079519_python.txt
Q: QApplication Font Color I'm writing a PyQt systemtray script. It simply a switch for system services. I'm adding QActions to QMenu via this code, my purpose is showing running services green and stopped services red: .... for service, started in s.services.items(): action = self.menu.addAction(service) if...
QApplication Font Color
I'm writing a PyQt systemtray script. It simply a switch for system services. I'm adding QActions to QMenu via this code, my purpose is showing running services green and stopped services red: .... for service, started in s.services.items(): action = self.menu.addAction(service) if started: #It is my purpose, ...
[ "The only simpler way I can see is to make your QActions checkable (and define for instance that \"service is active\" should check the item), and then play with Qt style sheets to get your desired effect.\nExamples of styling menu items can be found here: Qt Style Sheets - Customizing QMenu\n", "Not exactly what...
[ 1, 1 ]
[]
[]
[ "pyqt", "python", "qt" ]
stackoverflow_0007071796_pyqt_python_qt.txt
Q: ctypes on windows: depending dlls not found I try to load a shared libraray "R.dll" which depends on "Rblas.dll", both are in the same directory. When I load R.dll with ctypes (a python module which loads shared libraries) import ctypes lib = ctypes.CDLL("/path_to_r/bin/i386/R.dll") I get an error message sayin...
ctypes on windows: depending dlls not found
I try to load a shared libraray "R.dll" which depends on "Rblas.dll", both are in the same directory. When I load R.dll with ctypes (a python module which loads shared libraries) import ctypes lib = ctypes.CDLL("/path_to_r/bin/i386/R.dll") I get an error message saying that "Rblas.dll" is not found. What can I do ?...
[ "You may need to add the path that the dlls are located at to the %PATH% environmental variable. While R.DLL is loadng with an explicit path, the search for it's requested RBLAS.DLL is still searching %PATH% for it's location. Since that's a Windows level operation, there's no (easy) way to intercept and modify it ...
[ 4 ]
[]
[]
[ "ctypes", "dll", "python", "windows" ]
stackoverflow_0007079408_ctypes_dll_python_windows.txt
Q: sorting large text data I have a large file (100 million lines of tab separated values - about 1.5GB in size). What is the fastest known way to sort this based on one of the fields? I have tried hive. I would like to see if this can be done faster using python. A: Have you considered using the *nix sort program?...
sorting large text data
I have a large file (100 million lines of tab separated values - about 1.5GB in size). What is the fastest known way to sort this based on one of the fields? I have tried hive. I would like to see if this can be done faster using python.
[ "Have you considered using the *nix sort program? in raw terms, it'll probably be faster than most Python scripts. \nUse -t $'\\t' to specify that it's tab-separated, -k n to specify the field, where n is the field number, and -o outputfile if you want to output the result to a new file.\nExample:\nsort -t $'\\t' -...
[ 19, 5, 4, 2 ]
[]
[]
[ "bigdata", "python", "sorting" ]
stackoverflow_0007079473_bigdata_python_sorting.txt
Q: Copy all files and folders from some root In python, is there an easy method for copying all files and folders from some root to some destination root? Creating all non-existent directories along the way, of course.. edit how does this change if the root destination directory already exists? A: distutils.dir_ut...
Copy all files and folders from some root
In python, is there an easy method for copying all files and folders from some root to some destination root? Creating all non-existent directories along the way, of course.. edit how does this change if the root destination directory already exists?
[ "distutils.dir_util.copy_tree\n", "shutil.copytree(src, dst[, symlinks=False[, ignore=None]])\n", "Read this http://docs.python.org/library/shutil.html\nThere are some functions there which you can use, like copytree\n" ]
[ 6, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007079961_python.txt
Q: How to register multiple KeyEvent triggers in wxPython I'm currently using wxPython to develop an interactive application; in which, I would like to retain and repeat the last used key pressed. An example of what I'm trying to attain is: [key 'a' pressed and held][key 'b' pressed and held][key 'b' released][key '...
How to register multiple KeyEvent triggers in wxPython
I'm currently using wxPython to develop an interactive application; in which, I would like to retain and repeat the last used key pressed. An example of what I'm trying to attain is: [key 'a' pressed and held][key 'b' pressed and held][key 'b' released][key 'a' released] aaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbaa...
[ "One option in cases like this is to poll the key state yourself in a loop. If key 'a' is pressed then call your action\n", "When you want to catch multi-key events, you have two options. You can catch EVT_CHAR or you can create an Accelerator Table. Here's an article where I attempted to explain how EVT_CHAR wor...
[ 3, 2, 0 ]
[]
[]
[ "event_handling", "python", "wxpython" ]
stackoverflow_0007070431_event_handling_python_wxpython.txt
Q: Python ORM for mongodb in django that doesnt use db.eval() I am using a ExtJS frontend and for a back end I'm using django, mongodb, and mongoengine (ORM - between the two). Everything works until i decide to shard my mongo database, turns out db.eval() (uses datbase to run commands) doesn't work with a sharded da...
Python ORM for mongodb in django that doesnt use db.eval()
I am using a ExtJS frontend and for a back end I'm using django, mongodb, and mongoengine (ORM - between the two). Everything works until i decide to shard my mongo database, turns out db.eval() (uses datbase to run commands) doesn't work with a sharded database. So I have to switch out the ORM. I found several other ...
[ "MongoEngine has now been updated not to use db.eval for the 2 areas that used it where map_reduce should have been used: sum and average. item_frequencies has been updated to default to using map_reduce over using exec_js & db.eval. \nIn the end it was a small update: https://github.com/hmarr/mongoengine/pull/256...
[ 2 ]
[]
[]
[ "django", "mongodb", "orm", "python" ]
stackoverflow_0007067887_django_mongodb_orm_python.txt
Q: Unexpected output from Newton's method I have this code for solving Newton's method and in the last iteration, the output values have come wrong. Those values should not be negative as I checked it manually on paper. As far as I know the code is right but I cannot figure out why is it displaying negative values an...
Unexpected output from Newton's method
I have this code for solving Newton's method and in the last iteration, the output values have come wrong. Those values should not be negative as I checked it manually on paper. As far as I know the code is right but I cannot figure out why is it displaying negative values and also the final u value should ideally be a...
[ "Ah, I see now.\nJust as you say,\nfloat(poly_substitute(poly, x))\n\nevaluates to -0.015. Then,\nfloat(poly_substitute(poly_diff, x))\n\nevaluates to -0.01. Thus, substituting for these values and for x,\nx_n = 0.5 - ( (-0.015) / (-0.01) )\nx_n = 0.5 - 0.6666666...\nx_n = -0.166666...\n\nYour manual math was wha...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007078244_python.txt
Q: NameError for built-in Python functions in Django when working with uWSGI I'm running Django 1.3 + Python 2.6 on Ubuntu 10.10 (64bit) with uWSGI (0.9.8). However, occasionally I can find some strange logs in uwsgi.log, reporting that 'getattr', 'isinstance' is not defined. But aren't they Python's built-in fun...
NameError for built-in Python functions in Django when working with uWSGI
I'm running Django 1.3 + Python 2.6 on Ubuntu 10.10 (64bit) with uWSGI (0.9.8). However, occasionally I can find some strange logs in uwsgi.log, reporting that 'getattr', 'isinstance' is not defined. But aren't they Python's built-in functions? Why Django unable to find them? This happens not often when traffic is ...
[ "Can you try with the latest tip ? It looks like a reference counting bug that should be fixed in 0.9.9-dev\nIf you can confirm it solves your problem i will release an updated release with only this fix applied.\nMany thanks for the report\n" ]
[ 1 ]
[]
[]
[ "django", "nameerror", "python", "uwsgi" ]
stackoverflow_0007008083_django_nameerror_python_uwsgi.txt
Q: Python - Raising an exception or not? Here's a description of my problem: I have the task to take a bunch of tablenames and put a prefix in front of them, like so: PREFIX = 'foo_'; prefixed_tablename = "".join([PREFIX, tablename[:27]]) (The tablename must never exceed 30 characters (some Oracle DB restriction), ...
Python - Raising an exception or not?
Here's a description of my problem: I have the task to take a bunch of tablenames and put a prefix in front of them, like so: PREFIX = 'foo_'; prefixed_tablename = "".join([PREFIX, tablename[:27]]) (The tablename must never exceed 30 characters (some Oracle DB restriction), this is why I only take the first 27 chars)...
[ "27 + 4 = 31.\nWhy wouldn't you use an exception? If you later don't want to just exit, but instead catch the exception and do something with it at an outer scope, you've got less to change than if you use sys.exit.\n", "Exceptions in Python are actually used somewhat more liberally than in Java (for example, ite...
[ 4, 2, 1 ]
[]
[]
[ "python", "python_2.5" ]
stackoverflow_0007080516_python_python_2.5.txt
Q: Determine sequential numbers in a list (Python) I'm trying to find the most pythonic way to find out if numbers in a list are sequential. To give some background, I have a list of numbers gathered that exist in a folder, and I need to find out which numbers are missing. I gather all of the numbers, and then make a...
Determine sequential numbers in a list (Python)
I'm trying to find the most pythonic way to find out if numbers in a list are sequential. To give some background, I have a list of numbers gathered that exist in a folder, and I need to find out which numbers are missing. I gather all of the numbers, and then make another list from the range(beginning, end+1) of what ...
[ "Try something like this \nmissing=[]\nnumbers.insert(0, 0) # add the minimum value on begining of the list\nnumbers.append(41) # add the maximum value at the end of the list\nfor rank in xrange(0, len(numbers)-1):\n if numbers[rank+1] - numbers[rank] > 2:\n missing.append(\"%s-%s\"%(numbers[rank] +1 , numb...
[ 4, 1 ]
[]
[]
[ "list", "python", "sequential" ]
stackoverflow_0007079619_list_python_sequential.txt
Q: How to parse a html file and get the text which is in between the tags by using Python? Possible Duplicate: Parsing HTML in Python I have searched more over on the internet for get the text which is in between the tags by using Python. Can you guys please explain? A: Here is an example of using BeautifulSoup t...
How to parse a html file and get the text which is in between the tags by using Python?
Possible Duplicate: Parsing HTML in Python I have searched more over on the internet for get the text which is in between the tags by using Python. Can you guys please explain?
[ "Here is an example of using BeautifulSoup to parse HTML:\nfrom BeautifulSoup import BeautifulSoup\nsoup = BeautifulSoup(\"\"\"<html><body>\n <div id=\"a\" class=\"c1\">\n We want to get this\n </div>\n <div id=\"b\">\n ...
[ 2 ]
[ "The htmlparser provided in the link in the comments above is probably the more robust way to go. But if you have a simple bit of content that is between particular tags you can use regular expressions\nimport re\nhtml = '<html><body><div id='blah-content'>Blah</div><div id='content-i-want'>good stuff</div></body><...
[ -1 ]
[ "html_parsing", "python" ]
stackoverflow_0007080506_html_parsing_python.txt
Q: Guidance in using rpy2 eval expression I am new to both R and rpy2. I am trying to port the following example library(MASS) # for eqscplot data(topo, package="MASS") topo.kr <- surf.ls(2, topo) trsurf <- trmat(topo.kr, 0, 6.5, 0, 6.5, 50) to rpy2. So far I have import rpy2.robjects as robjects robjects...
Guidance in using rpy2 eval expression
I am new to both R and rpy2. I am trying to port the following example library(MASS) # for eqscplot data(topo, package="MASS") topo.kr <- surf.ls(2, topo) trsurf <- trmat(topo.kr, 0, 6.5, 0, 6.5, 50) to rpy2. So far I have import rpy2.robjects as robjects robjects.r('library(spatial)') f1 = robjects.r['su...
[ "Then the question is more: how do I convert an R list to a Python dictionary (little to do with evaluating expressions).\nWith rpy2-2.2.x (and 2.3-dev):\nfrom rpy2.robjects.vectors import ListVector\n# make an R list\nl = ListVector({'a': 1, 'b': 'b'})\n\n# get a Python dict out of an R list\ndict(l.iteritems())\n...
[ 2, 1 ]
[]
[]
[ "cran", "python", "r", "rpy2" ]
stackoverflow_0007034526_cran_python_r_rpy2.txt
Q: Inserts with Mongoengine work only from shell, but not from Django view I am having strange situation - creating some Mongoengine object from Django shell is successful, but creating the same object from Django view looks like successful but without any data appeared in MongoDB. I.e. the same code like that - from...
Inserts with Mongoengine work only from shell, but not from Django view
I am having strange situation - creating some Mongoengine object from Django shell is successful, but creating the same object from Django view looks like successful but without any data appeared in MongoDB. I.e. the same code like that - from myapp.mongomodels import MyModel m = MyModel(a=1, b=2, c=3) m.save() produ...
[ "You should be able to do that but force the save using:\nfrom myapp.mongomodels import MyModel\n\nm = MyModel(a=1, b=2, c=3)\nm.save(force_insert=True)\n\n", "As I've told before, the problem was in that I am assigning a primary key value BEFORE saving.\nI have a system with some data stored in MySQL and some co...
[ 1, 0 ]
[]
[]
[ "django", "mongodb", "mongoengine", "python" ]
stackoverflow_0006692035_django_mongodb_mongoengine_python.txt
Q: My Django view says it only takes one argument and two is given but there is only one I am working on a django project and when I try to run this function it returns that there can only be one argument given, but there is only one argument given. from django.http import HttpResponse, Http404 from django.template i...
My Django view says it only takes one argument and two is given but there is only one
I am working on a django project and when I try to run this function it returns that there can only be one argument given, but there is only one argument given. from django.http import HttpResponse, Http404 from django.template import Context from django.template.loader import get_template from django.contrib.auth.mode...
[ "I suspect that your URL pattern captures some other variable. If you attach a URL pattern to a view and that URL pattern captures any values, you need to have that view set up to take an argument for each captured value on top of the request argument, which is always first. So, let's say you've got a pattern\n(r'^...
[ 10, 1, 0 ]
[]
[]
[ "django", "django_views", "python", "web_frameworks" ]
stackoverflow_0007081311_django_django_views_python_web_frameworks.txt
Q: Python max recursion, question about sys.setrecursionlimit() I have one question about sys.setrecursionlimit() From the python docs this function: Set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. The ...
Python max recursion, question about sys.setrecursionlimit()
I have one question about sys.setrecursionlimit() From the python docs this function: Set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. The highest possible limit is platform-dependent. A user may need to s...
[ "It's poorly named. It should say Stack Depth, not Recursion depth. Recursion implies it's the same thread over and over again that it's limiting. In reality, you could have actual code that just has calls 100 deep. I wouldn't recommend it, but you could. They can get away with it because in the practical world, th...
[ 20, 5, 4 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0007081448_python_recursion.txt
Q: Python search path - python can't find my modules I'm trying to run a script from the commandline, and python is having absolutely none of it: [graffias:~/testing.tustincommercial.com]$ export PYTHONPATH=`pwd`:$PYTHONPATH [graffias:~/testing.tustincommercial.com]$ python ...
Python search path - python can't find my modules
I'm trying to run a script from the commandline, and python is having absolutely none of it: [graffias:~/testing.tustincommercial.com]$ export PYTHONPATH=`pwd`:$PYTHONPATH [graffias:~/testing.tustincommercial.com]$ python -c 'import oneclickcos.mainapp; mainapp.mail.worker_loo...
[ "Do you have a __init__.py in oneclickcos/ and in oneclickcos/mainapp/? If not, put one in and try again — that could cause the problem you're seeing.\nFor more, see http://docs.python.org/tutorial/modules.html\n", "In order to import from folders like that, they have to be setup as packages. Do oneclickcos and m...
[ 6, 3 ]
[]
[]
[ "environment_variables", "python" ]
stackoverflow_0007081544_environment_variables_python.txt
Q: Search for value in a key from list of dictionaries and return a different key value Continued from this stackoverflow question. I have the following data structure: data = [ {'site': 'Stackoverflow', 'id': 1}, {'site': 'Superuser', 'id': 2}, {'site': 'Serverfault', 'id': 3} ] I want to search all 'site' ...
Search for value in a key from list of dictionaries and return a different key value
Continued from this stackoverflow question. I have the following data structure: data = [ {'site': 'Stackoverflow', 'id': 1}, {'site': 'Superuser', 'id': 2}, {'site': 'Serverfault', 'id': 3} ] I want to search all 'site' keys for a specific value, and return that dictionary's 'id' value. For example, searchin...
[ "No tricks here. Just do:\ndef find_id(data, name):\n for d in data:\n if d['site'] == name:\n return d['id'] \n\n" ]
[ 0 ]
[]
[]
[ "dictionary", "key", "list", "python", "search" ]
stackoverflow_0007081567_dictionary_key_list_python_search.txt
Q: Trac SvnAuthzAdminPlugin not showing users I'm using Trac v0.12.2 with the SvnAuthzAdminPlugin and AccountManagerPlugin. I'm sharing a HtDigest auth file between Trac and Apache/Svn. trac.ini [trac] authz_file = /trac/svnaccess repository_type = svn [account-manager] password_store = HtDigestStore password_file ...
Trac SvnAuthzAdminPlugin not showing users
I'm using Trac v0.12.2 with the SvnAuthzAdminPlugin and AccountManagerPlugin. I'm sharing a HtDigest auth file between Trac and Apache/Svn. trac.ini [trac] authz_file = /trac/svnaccess repository_type = svn [account-manager] password_store = HtDigestStore password_file = /trac/trac.htdigest htdigest_realm = TracRealm...
[ "Based on this ticket filed against the svnauthz plugin, it looks like this may be a limitation in the plugin itself. According to a comment on that ticket:\n\nThe list of users that is shown comes from the list of users (or\n groups) in Trac that have been assigned at least one permission.\nSo, if you want to gi...
[ 2 ]
[]
[]
[ "python", "trac", "ubuntu" ]
stackoverflow_0007027094_python_trac_ubuntu.txt
Q: Python 3.2 TypeError: unsupported operands(s) for %: 'NoneType' and 'str' Just getting started with python and tried the following bit of code my_name = 'Joe Bloggs' my_age = 25 my_height = 71 # inches my_weight = 203 #lbs approximate, converted from ~14.5 stones my_eyes = 'Blue' my_teeth = 'White' my_hair = 'Brow...
Python 3.2 TypeError: unsupported operands(s) for %: 'NoneType' and 'str'
Just getting started with python and tried the following bit of code my_name = 'Joe Bloggs' my_age = 25 my_height = 71 # inches my_weight = 203 #lbs approximate, converted from ~14.5 stones my_eyes = 'Blue' my_teeth = 'White' my_hair = 'Brown' print("Let's talk about %s") % my_name print ("He's %d inches tall.") % my_...
[ "You want to move the close paren to the end of the line: print (\"He's %d inches tall.\" % my_height)\nThat's because in Python 3, print is a function, so you are applying the % operator to the results of the print function, which is None. What you want is to apply the % operator to the format string and the strin...
[ 9 ]
[]
[]
[ "python", "python_3.x", "typeerror" ]
stackoverflow_0007081905_python_python_3.x_typeerror.txt
Q: Python 3 regular expression to find multiline comment I'm trying to find comment blocks in PHP source code using regular expressions in Python 3. The PHP comments are in this format: /** * This is a very short block comment */ Now I came up with the following regular expression: '/\*\*[.]+?\*/' I figure that -...
Python 3 regular expression to find multiline comment
I'm trying to find comment blocks in PHP source code using regular expressions in Python 3. The PHP comments are in this format: /** * This is a very short block comment */ Now I came up with the following regular expression: '/\*\*[.]+?\*/' I figure that -in combination with the DOTALL flag- should do it, but no. ...
[ "You can use the re.DOTALL flag to make the . character match newlines:\nre.compile(r'/\\*\\*.+?\\*/', re.DOTALL)\n\n(As a side note, PHP block comments can start with /*, not just /**.)\n", "Try this:\nr'\\/\\*\\*[^*]*\\*+([^/][^*]*\\*+)*\\/'\n\n(this is the regex used by some CSS parsers for /* CSS comments */,...
[ 5, 0 ]
[]
[]
[ "comments", "python", "python_3.x", "regex" ]
stackoverflow_0007081882_comments_python_python_3.x_regex.txt
Q: does Python for windows ever insert '\r\n' when told to insert '\n'? I use a PC at home and a Mac at work. I've never had any problems with line breaks in python script or their outputs, but whenever i send something to my boss i get an angry e-mail back about windows line breaks in it. The most recent was the ou...
does Python for windows ever insert '\r\n' when told to insert '\n'?
I use a PC at home and a Mac at work. I've never had any problems with line breaks in python script or their outputs, but whenever i send something to my boss i get an angry e-mail back about windows line breaks in it. The most recent was the output of a python script where i'd told it to end every line with '\n', but...
[ "This is because you have files opened in text mode and Python is normalizing the newlines in accordance with the platform you're using (Windows used \\r\\n and Linux just uses \\n). You need to open files in binary mode like this:\nf = open(\"myfile.txt\",\"wb\")\n\nIt does the same thing in reverse when you read ...
[ 10, 1 ]
[]
[]
[ "line_breaks", "python", "python_2.x", "windows" ]
stackoverflow_0007077355_line_breaks_python_python_2.x_windows.txt
Q: python 2.7 vs 2.6 speed on Windows I just installed python 2.7 and find it to be 25-30% slower than 2.6 . When I run a program of mine under 2.7, it takes 1m17s, while under 2.6 that same prog takes 0m57s. Is this common? Included in the upgrade are numpy 1.6.1 (from 1.6.0), pandas 0.4 (from 0.3), and maybe other...
python 2.7 vs 2.6 speed on Windows
I just installed python 2.7 and find it to be 25-30% slower than 2.6 . When I run a program of mine under 2.7, it takes 1m17s, while under 2.6 that same prog takes 0m57s. Is this common? Included in the upgrade are numpy 1.6.1 (from 1.6.0), pandas 0.4 (from 0.3), and maybe other things.
[ "My code make heavy use of the pandas module. I wrote to its creator, Wes McKinney, and sent him profiles of code from Python2.6/Pandas0.3 and Python2.7/Pandas0.4. He found it was pandas that had changed (and slowed for my use, though perhaps not in general) and added some optimizations to help me out. Now my 2....
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007060245_python.txt
Q: Assigning xml structured output from webservice method in python I'm calling a method called getNewReports() of a webservice. This method takes in a username and password and outputs xml structured data. How can I assign this xml output to a variable in python. If I just do: reportxml = client.service.GetNewRep...
Assigning xml structured output from webservice method in python
I'm calling a method called getNewReports() of a webservice. This method takes in a username and password and outputs xml structured data. How can I assign this xml output to a variable in python. If I just do: reportxml = client.service.GetNewReports(username=user,password=pw) print reportxml It's printing this: ...
[ "The datatype you recieve from calling GetNewReports is an ArrayOfString. The problem is, I don't know what methods this type supports.\nCall help(reportxml) or print dir(reportxml) to see a list of it's methods and attributes or take a look into the client.service documentation (if any) to get information about th...
[ 0 ]
[]
[]
[ "python", "suds", "xml" ]
stackoverflow_0007081675_python_suds_xml.txt
Q: POSTing file to Jenkins fails I'm trying to POST a file to Jenkins from Python, via multipart/form-data. The request body looks like this: --===============1849003312== Content-Type: application/octet-stream Content-Transfer-Encoding: base64 Content-Disposition: file; name="file0"; filename="meta.xml" PHhtbD4NCjw...
POSTing file to Jenkins fails
I'm trying to POST a file to Jenkins from Python, via multipart/form-data. The request body looks like this: --===============1849003312== Content-Type: application/octet-stream Content-Transfer-Encoding: base64 Content-Disposition: file; name="file0"; filename="meta.xml" PHhtbD4NCjwveG1sPg0K --===============1849003...
[ "I believe the Content-Disposition: file; should be replaced with Content-Disposition: attachment;. The source code of FileUploadBase does not mention \"file\", and RFC 2183 does not list \"file\" as a value for content-disposition.\n" ]
[ 0 ]
[]
[]
[ "http_post", "jenkins", "multipartform_data", "python" ]
stackoverflow_0007078561_http_post_jenkins_multipartform_data_python.txt
Q: How to debug long running python scripts or services remotely? Pretty much what the title says, I would like to be able to connect to a python process running under paster or uwsgi and utilize pdb functionality. A: Using winpdb, you can attach to a running process like this: Insert import rpdb2; rpdb2.star...
How to debug long running python scripts or services remotely?
Pretty much what the title says, I would like to be able to connect to a python process running under paster or uwsgi and utilize pdb functionality.
[ "Using winpdb, you can attach to a running process like this:\n\nInsert \nimport rpdb2; rpdb2.start_embedded_debugger('mypassword')\n\ninside your script.\nLaunch your script (through paster or uwsgi) as usual.\nRun winpdb\nClick File>Attach\nType in password (e.g. \"mypassword\"), select the process.\nTo detac...
[ 2 ]
[]
[]
[ "debugging", "paster", "python", "uwsgi" ]
stackoverflow_0007082093_debugging_paster_python_uwsgi.txt
Q: Zipfile python module bytesize difference I'm using zipfile module for python to extract a zipfile I retrieved from the internet using urllib.urlretrieve() the files in the zip file are patch files created by bsdiff, however when I let python extract the zip file and try to use bspatch it says corrupted patch fil...
Zipfile python module bytesize difference
I'm using zipfile module for python to extract a zipfile I retrieved from the internet using urllib.urlretrieve() the files in the zip file are patch files created by bsdiff, however when I let python extract the zip file and try to use bspatch it says corrupted patch file. When I manually extract the zip file using 7...
[ "Is this on Windows? Maybe try f = open(dest, 'wb')\nOn Windows only, the b makes the filesystem treat the file as binary as opposed to plain text, and not mess with the line endings. On other systems, there's no difference (and the b is silently ignored).\n" ]
[ 5 ]
[]
[]
[ "byte", "python", "python_zipfile", "zip" ]
stackoverflow_0007082454_byte_python_python_zipfile_zip.txt
Q: Python: Infinite loop and GUI I'm trying to write a python program with wxPython GUI. Program must to collect some information in background (infinite loop), but GUI should be active at this time. Like, if I click on the some button, some variable or another information must change, and at the new cycle this varia...
Python: Infinite loop and GUI
I'm trying to write a python program with wxPython GUI. Program must to collect some information in background (infinite loop), but GUI should be active at this time. Like, if I click on the some button, some variable or another information must change, and at the new cycle this variable should be used instead of the o...
[ "You definitely need to use threads to accomplish this. Then when you get some data from the non-GUI thread, you can use one of wxPython's thread-safe methods to let it know that it needs to update. Here's a little tutorial: http://www.blog.pythonlibrary.org/2010/05/22/wxpython-and-threads/\nOr the perennial favori...
[ 2, 0, 0 ]
[]
[]
[ "infinite", "loops", "python", "wxpython" ]
stackoverflow_0007082529_infinite_loops_python_wxpython.txt
Q: In matplotlib, how do you change the fontsize of a single figure? The code: # changes the fontsize of matplotlib, not just a single figure matplotlib.rcParams.update({'font.size': 22}) Is there a better way than setting it for a figure, and then setting it back later? A: This covers every possible text object a...
In matplotlib, how do you change the fontsize of a single figure?
The code: # changes the fontsize of matplotlib, not just a single figure matplotlib.rcParams.update({'font.size': 22}) Is there a better way than setting it for a figure, and then setting it back later?
[ "This covers every possible text object and sets the font size for each. (Note this routine has been updated from the original posting). It uses the findobj method of the Artist base class. The match keyword accepts a boolean function that performs a test on each object that is a child of the figure. I use this to ...
[ 3 ]
[]
[]
[ "figure", "matplotlib", "python" ]
stackoverflow_0007082597_figure_matplotlib_python.txt
Q: django python collation error What is the reason for the following error? when i try to filter with: if MyObject.objects.filter(location = aDictionary['address']): where location is defined as: location = models.CharField(max_length=100, blank=True, default='') I get the following error when aDictionary['addres...
django python collation error
What is the reason for the following error? when i try to filter with: if MyObject.objects.filter(location = aDictionary['address']): where location is defined as: location = models.CharField(max_length=100, blank=True, default='') I get the following error when aDictionary['address'] contains a string with a non-al...
[ "Alter the database in MySQL like so:\nALTER TABLE foo CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;\n\nWhen creating a new database, remember to create with the right collate settings:\nCREATE DATABASE foo CHARACTER SET utf8 COLLATE utf8_general_ci;\n\nMore discussion here.\n", "Python is using Unicode ...
[ 7, 1 ]
[]
[]
[ "django", "mysql", "mysql_error_1267", "python", "unicode" ]
stackoverflow_0007083421_django_mysql_mysql_error_1267_python_unicode.txt
Q: Python NameError when using an imported function When I import and use a function in a python(2.6.5) program, I get an error: from Localization import MSGR title = Localization.MSGR("Logfile from Ctf2Rrl.") NameError: global name 'Localization' is not defined Could you please explain why? Regards, A: If you i...
Python NameError when using an imported function
When I import and use a function in a python(2.6.5) program, I get an error: from Localization import MSGR title = Localization.MSGR("Logfile from Ctf2Rrl.") NameError: global name 'Localization' is not defined Could you please explain why? Regards,
[ "If you import your method like this, you can user MSGR but not Localization.MSGR :)\nIf you want to use Localization.MSGR, you can just import Localization\n", "The import statement of the form:\nfrom foo import bar\n\nDoesn't introduce the module name (foo) from which the imports (bar) are taken into the module...
[ 4, 2 ]
[]
[]
[ "function", "import", "nameerror", "python" ]
stackoverflow_0007083496_function_import_nameerror_python.txt
Q: python mysql problem using string as query So I'm at the point in my program where I have a string containing the query I want to use to insert a row into a database: query = '"INSERT INTO new_test (test_name, IP, test_run_date, results_query_time, run_time) VALUES (%s, %s, %s, %s, %s)", ("new_test", "192.168.17.1...
python mysql problem using string as query
So I'm at the point in my program where I have a string containing the query I want to use to insert a row into a database: query = '"INSERT INTO new_test (test_name, IP, test_run_date, results_query_time, run_time) VALUES (%s, %s, %s, %s, %s)", ("new_test", "192.168.17.194", "143917160811", "12.4847829342", "46.126832...
[ "You have an extra \" at the beginning of the query. That will definitely break it. It looks like you wanted:\n# notice the extra ' around the %s\nquery = \"\"\"INSERT INTO new_test \n (test_name, IP, test_run_date, results_query_time, run_time) \n VALUES ('%s', '%s', '%s', '%s', '%s')\"\"\" ...
[ 5 ]
[]
[]
[ "mysql", "mysql_error_1064", "python" ]
stackoverflow_0007083694_mysql_mysql_error_1064_python.txt
Q: Updating records in MongoDB through pymongo leads to deletion of most of them Im working with a remote mongodb database in my python code.The code accessing the database and the database itself are on two different machines. The pymongo module version im using is 1.9+. The script consists of the following code: f...
Updating records in MongoDB through pymongo leads to deletion of most of them
Im working with a remote mongodb database in my python code.The code accessing the database and the database itself are on two different machines. The pymongo module version im using is 1.9+. The script consists of the following code: for s in coll.find({ "somefield.a_date" : { "$exists":False }, ...
[ "\nWhat could have been other reasons for this and any ways i can find out what exactly happened ?\n\nThe first thing to check is \"were there any exceptions\"?\nIn coll.update(), you are not setting the safe variable. If there is an exception on the update, it will not be thrown.\nIn your code you not do not catch...
[ 0 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0007083291_mongodb_pymongo_python.txt
Q: Is there anything wrong with importing a python module into a routine or class definition? Possible Duplicate: Should Python import statements always be at the top of a module? I recently answered a SO question and provided this routine as a solution: def set_fontsize(fig,fontsize): import matplotlib """...
Is there anything wrong with importing a python module into a routine or class definition?
Possible Duplicate: Should Python import statements always be at the top of a module? I recently answered a SO question and provided this routine as a solution: def set_fontsize(fig,fontsize): import matplotlib """ For each text object of a figure fig, set the font size to fontsize """ if not isi...
[ "there's nothing wrong with importing inside functions and classes - it's a useful way of handling mutually recursive imports (where two files each imports the other), for example.\nhowever, there is something wrong with checking the type of an argument. idiomatic python would not check the type of fig. instead, ...
[ 2, 1 ]
[]
[]
[ "import", "instance", "module", "python" ]
stackoverflow_0007083843_import_instance_module_python.txt
Q: `while y < x` loop never ends I'm trying out Python, and, in my very tired state, can't seem to find the problem with the code below: import sys def printNum(x): y = 0 while y < x: print "Number: ", y y = y + 1 printNum(sys.argv[1]) So, I'm trying to get it to print out y x times. x is p...
`while y < x` loop never ends
I'm trying out Python, and, in my very tired state, can't seem to find the problem with the code below: import sys def printNum(x): y = 0 while y < x: print "Number: ", y y = y + 1 printNum(sys.argv[1]) So, I'm trying to get it to print out y x times. x is passed as a parameter. The loop neve...
[ "Ouch!\nYour problem is that sys.argv[1] gives you a str, and a str is always greater than an int.\nFor example:\n>>> '2' < 1\nFalse\n>>> '1' < 2\nFalse\n\nSo what you'll need to do is change your last line to\nprintNum(int(sys.argv[1]))\n\n", "The x value that you get as a command line parameter is passed in as ...
[ 4, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007084545_python.txt
Q: Make an object a "character buffer object" I have a custom class, which has some string data. I wish to be able to save this string data to a file, using a file handle's write object. I have implemented __str__(), so i can do str(myobject), what is the equivalent method for making python consider my object to be a...
Make an object a "character buffer object"
I have a custom class, which has some string data. I wish to be able to save this string data to a file, using a file handle's write object. I have implemented __str__(), so i can do str(myobject), what is the equivalent method for making python consider my object to be a character buffer object?
[ "There isn't a single function, but a whole range of them - read, seek, etc.\nWhy don't you subclass StringIO.StringIO, which is already a string buffer?\n", "If you are trying to use your object with library code, that expects to be able to write what you give it to a file, then you may have to resort to impleme...
[ 0, 0 ]
[]
[]
[ "object", "python" ]
stackoverflow_0007084430_object_python.txt
Q: In PHP classes, what is the equivalent of self from python classes? In PHP, how can I achieve something like this from Python? class CrowdProcess(): def __init__(self,variable): self.variable = variable def otherfunc(self): print self.variable A: PHP uses $this as a reference to the inst...
In PHP classes, what is the equivalent of self from python classes?
In PHP, how can I achieve something like this from Python? class CrowdProcess(): def __init__(self,variable): self.variable = variable def otherfunc(self): print self.variable
[ "PHP uses $this as a reference to the instance:\nclass CrowdProcess\n{\n public $variable;\n\n public function __construct($variable)\n {\n $this->variable = $variable;\n }\n\n public function otherfunc()\n {\n echo $this->variable, PHP_EOL;\n }\n}\n\nFor more information, see htt...
[ 8, 2 ]
[]
[]
[ "class", "php", "python", "self" ]
stackoverflow_0007084564_class_php_python_self.txt
Q: Mac: Error importing scikits while it has been installed I installed the scikits package but can't import it, I am on Macbook, please let me know what is missing here bash-3.2$ sudo port install py26-scikits-learn ---> Computing dependencies for py26-scikits-learn ---> Fetching archive for py26-scikits-learn -...
Mac: Error importing scikits while it has been installed
I installed the scikits package but can't import it, I am on Macbook, please let me know what is missing here bash-3.2$ sudo port install py26-scikits-learn ---> Computing dependencies for py26-scikits-learn ---> Fetching archive for py26-scikits-learn ---> Attempting to fetch py26-scikits-learn-0.8_0.darwin_10.x8...
[ "Unfortunately I don't know how port commnad works (I guess it comes from MacPorts) but you should use Python to maintain Python packages (which is encouraged eg. by homebrew). You can try pip:\nsudo pip install scikits.learn\n\nIn OS X Lion default version of Python is 2.7, if you want to use 2.6 you have to:\nsu...
[ 0 ]
[]
[]
[ "machine_learning", "python", "scikits" ]
stackoverflow_0007084558_machine_learning_python_scikits.txt
Q: sqlalchemy dates filter in raw sql I used to create dynamic filters like q = Session.query(Table) search_conditions = "%s ILIKE '%s%s%s'" % (str(nm), '%', val ,'%') q = q.filter(search_conditions) It work ok for string and int statements, but now I need to filter dates the way like this. I have a date colum...
sqlalchemy dates filter in raw sql
I used to create dynamic filters like q = Session.query(Table) search_conditions = "%s ILIKE '%s%s%s'" % (str(nm), '%', val ,'%') q = q.filter(search_conditions) It work ok for string and int statements, but now I need to filter dates the way like this. I have a date column and trying to filter it like this date...
[ "That doesn't look like terribly idiomatic sqlalchemy. You already have a Table object you're using to build your query, you can also use it to express the predicates in the generated WHERE clause, even dynamically:\ndate = '01.01.2011'\nfrom_date = dt.datetime.strptime(date, \"%d.%m.%Y\").date()\nq = session.quer...
[ 4, 2, 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0007084045_python_sqlalchemy.txt
Q: Conditional logging in python I want to include logging in a module, but I don't want the module to create a new log object/file, I want it to use the callers log object, whatever that may be, but only if they pass one. I know I could put all my log calls in a try block, but that's awkward. What I finally came u...
Conditional logging in python
I want to include logging in a module, but I don't want the module to create a new log object/file, I want it to use the callers log object, whatever that may be, but only if they pass one. I know I could put all my log calls in a try block, but that's awkward. What I finally came up with seems to work, but it seems ...
[ "Most loggers use the factory pattern to let some centralized resource manage which classes (if any) get loggers which actually log (instead of calling dummy functions). This means that there is a centralized API, centralized control, and there becomes no need to have loggers defined on a class-by-class basis. \nIt...
[ 2, 1, 0 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0007083249_logging_python.txt
Q: Using Python "json" module to make a class serializable I am working in Python with an Email() class that I would like to extend into a SerializeEmail() class, which simply adds two further methods, .write_email() and .read_email(). I would like this sort of behaviour: # define email my_email = SerializeEmail() my...
Using Python "json" module to make a class serializable
I am working in Python with an Email() class that I would like to extend into a SerializeEmail() class, which simply adds two further methods, .write_email() and .read_email(). I would like this sort of behaviour: # define email my_email = SerializeEmail() my_email.recipients = 'link@hyrule.com' my_email.subject = 'RE:...
[ "While you could jump through a number of hoops to load serialized content into an existing instance, I wouldn't recommend doing so. It's an unnecessary complication which really gains you nothing; it means that the extra step of creating a dummy instance is required every time you want to load an e-mail from JSON...
[ 2 ]
[]
[]
[ "json", "python" ]
stackoverflow_0007084851_json_python.txt
Q: Trouble concatenating two strings I am having trouble concatenating two strings. This is my code: info = infl.readline() while True: line = infl.readline() outfl.write(info + line) print info + line The trouble is that the output appears on two different lines. For example, output text looks like this...
Trouble concatenating two strings
I am having trouble concatenating two strings. This is my code: info = infl.readline() while True: line = infl.readline() outfl.write(info + line) print info + line The trouble is that the output appears on two different lines. For example, output text looks like this: 490250633800 802788.0 953598.2 802781...
[ "There must be a '\\n' character at the end of info. You can remove it with:\ninfo = infl.readline().rstrip()\n\n", "You should remove line breaks in the line and info variables like this :\nline=line.replace(\"\\n\",\"\")\n", "readline will return a \"\\n\" at the end of the string 99.99% of the time. You can ...
[ 7, 1, 1 ]
[]
[]
[ "concatenation", "python", "string" ]
stackoverflow_0007084937_concatenation_python_string.txt
Q: How to use c structure in python "? I have a simple C function. typedef struct { long unsigned int First; long unsigned int Second; int c; } FRAGMENTS; struct out { long unsigned int Four; FRAGMENTS fragments[10000]; }; struct out test() { struct out *out = (struct out *)malloc(sizeof(str...
How to use c structure in python "?
I have a simple C function. typedef struct { long unsigned int First; long unsigned int Second; int c; } FRAGMENTS; struct out { long unsigned int Four; FRAGMENTS fragments[10000]; }; struct out test() { struct out *out = (struct out *)malloc(sizeof(struct out)); ... return *out } How...
[ "Do you have the data already \"in\" Python (i.e. from the network or a binary file)? Than you an use the struct module.\n", "The easiest way is to use SWIG to generate a Python wrapper around your C code. You can also use it to generate bindings/wrappers for lots of other scripting languages to.\n" ]
[ 1, 1 ]
[]
[]
[ "c", "python", "wrapper" ]
stackoverflow_0007084726_c_python_wrapper.txt
Q: Does it make sense to make a class in python when it would never get instantiated? I have some methods in a file and all of them are defined in the global scope (a module). I did not bother to make a class because the class would never get instantiated and everything would still have to be accessed statically if I...
Does it make sense to make a class in python when it would never get instantiated?
I have some methods in a file and all of them are defined in the global scope (a module). I did not bother to make a class because the class would never get instantiated and everything would still have to be accessed statically if I defined a class. Does it make sense to leave it as it is, or is it better design to mak...
[ "Python is not Java, use module-level methods without worry.\n" ]
[ 9 ]
[]
[]
[ "encapsulation", "python" ]
stackoverflow_0007085184_encapsulation_python.txt
Q: How do you execute a server-side Python script using jQuery? I have a very simple Python file, called python1.py, whose contents are: f = open('C:\\Temp\\test.txt', 'w') f.write('Succeeded') f.close() I wish to execute this from JavaScript, like so: jQuery.ajax({ type: "POST", url: "/cgi-bin/python1.py", ...
How do you execute a server-side Python script using jQuery?
I have a very simple Python file, called python1.py, whose contents are: f = open('C:\\Temp\\test.txt', 'w') f.write('Succeeded') f.close() I wish to execute this from JavaScript, like so: jQuery.ajax({ type: "POST", url: "/cgi-bin/python1.py", success: function (msg) { alert("Data Saved: " + msg); ...
[ "You simply need to configure your web server to execute your *.py scripts, instead of serving them as plain text.\nIf you are using Apache as a web server, you need to enable mod_python or mod_wsgi.\n\nEDIT:\nSince you are using using Apache, you may want to check the following article, which briefly describes how...
[ 7, 7, 4, 1 ]
[]
[]
[ "ajax", "javascript", "jquery", "python" ]
stackoverflow_0002201561_ajax_javascript_jquery_python.txt
Q: Not receiving order placed notice in Satchmo I was wondering if there are any settings I need to do to enable Satchmo sending me an email (to the store config email address) each time an order is placed? I have set up the template: templates/shop/email/order_placed_notice.html and enabled Send HTML Email in the se...
Not receiving order placed notice in Satchmo
I was wondering if there are any settings I need to do to enable Satchmo sending me an email (to the store config email address) each time an order is placed? I have set up the template: templates/shop/email/order_placed_notice.html and enabled Send HTML Email in the settings. The site is sending the order placed and o...
[ "I managed to find the solution for this. It was a setting under the Satchmo /settings/ page, under the Payment section:\nEmail Owner? Needs to be ticked.\nFeel like a bit of an idiot for missing this, but the reason I skipped over the payment section is that I'm using a custom payment module so didn't think it wou...
[ 1 ]
[]
[]
[ "django", "python", "satchmo" ]
stackoverflow_0007071829_django_python_satchmo.txt
Q: Python equivalent function to cvCalcEigenObjects I'm trying 'translate' the sample code in here, but i can't find equivalent python function to cvCalcEigenObjects written in c language from cvaux.h. A: My solution was to use the functions of numpy library for linear algebra.
Python equivalent function to cvCalcEigenObjects
I'm trying 'translate' the sample code in here, but i can't find equivalent python function to cvCalcEigenObjects written in c language from cvaux.h.
[ "My solution was to use the functions of numpy library for linear algebra.\n" ]
[ 2 ]
[]
[]
[ "face_recognition", "image_processing", "opencv", "python" ]
stackoverflow_0005711618_face_recognition_image_processing_opencv_python.txt
Q: How to resize QMainWindow after removing all DockWidgets? I’m trying to make an application consisting of a QMainWindow, the central widget of which is a QToolBar (it may not be usual, but for my purpose the toolbar’s well suited). Docks are allowed below only. I added a QDockWidget to it, and a QAction on the QTo...
How to resize QMainWindow after removing all DockWidgets?
I’m trying to make an application consisting of a QMainWindow, the central widget of which is a QToolBar (it may not be usual, but for my purpose the toolbar’s well suited). Docks are allowed below only. I added a QDockWidget to it, and a QAction on the QToolBar toggles the QDockWidget on and off with removeDockWidget(...
[ "Options \na) You can overload sizeHint() a virtual function. Let it return the size you want for your main window. \nb) In the main window's constructor you can call setMinimumSize() and setMaximumSize() one after another, both with the the desired main window size. If you keep both same you get a fixed size. \nc)...
[ 2, 1 ]
[]
[]
[ "pyqt", "python", "qdockwidget", "qmainwindow", "qt4" ]
stackoverflow_0007031787_pyqt_python_qdockwidget_qmainwindow_qt4.txt
Q: Request and basic profiling information for Flask Most web frameworks let you know the amount of time that it took to process a certain page request. I'm starting to work with Flask framework now and am very much in need of this information but can't find any good way of getting it. Using the werkzeug Midleware ...
Request and basic profiling information for Flask
Most web frameworks let you know the amount of time that it took to process a certain page request. I'm starting to work with Flask framework now and am very much in need of this information but can't find any good way of getting it. Using the werkzeug Midleware profiler is an option, but it is very verbose and provi...
[ "You should have a look at flask-debugtoolbar, it's basically the same as the django-debug-toolbar (if you ever used it) ported to Flask.\n" ]
[ 10 ]
[]
[]
[ "flask", "logging", "performance", "python", "sqlite" ]
stackoverflow_0007085311_flask_logging_performance_python_sqlite.txt
Q: Should I Return None or (None, None)? We have a object method that returns a city/state tuple, i.e. ('Boston', 'MA'). Under some valid circumstances, there is no valid city/state to return. Stylistically, does it make more sense to return None, or a two element tuple containing (None, None) in that case? A: I wo...
Should I Return None or (None, None)?
We have a object method that returns a city/state tuple, i.e. ('Boston', 'MA'). Under some valid circumstances, there is no valid city/state to return. Stylistically, does it make more sense to return None, or a two element tuple containing (None, None) in that case?
[ "I would return None. If there is no result, why return something that looks like a result?\nIt is also easier to test:\nresult = getCity()\nif result:\n # do something\n\nI would only return (None, None) if it were possible that only one of the two values is None (i.e. ('Boston', None)). It would be more consist...
[ 58, 46, 12, 11, 6, 4, 2, 1, 1 ]
[]
[]
[ "coding_style", "python", "python_3.x" ]
stackoverflow_0007082966_coding_style_python_python_3.x.txt
Q: Check what number a string ends with in Python Such as "example123" would be 123, "ex123ample" would be None, and "123example" would be None. A: You can use regular expressions from the re module: import re def get_trailing_number(s): m = re.search(r'\d+$', s) return int(m.group()) if m else None The r...
Check what number a string ends with in Python
Such as "example123" would be 123, "ex123ample" would be None, and "123example" would be None.
[ "You can use regular expressions from the re module:\nimport re\ndef get_trailing_number(s):\n m = re.search(r'\\d+$', s)\n return int(m.group()) if m else None\n\nThe r'\\d+$' string specifies the expression to be matched and consists of these special symbols:\n\n\\d: a digit (0-9)\n+: one or more of the pre...
[ 31, 15 ]
[ "Oops, correcting (sorry, I missed the point)\nyou should do something like this ;)\nImport the RE module\nimport re\n\nThen write a regular expression, \"searching\" for an expression.\ns = re.search(\"[a-zA-Z+](\\d{3})$\", \"string123\")\n\nThis will return \"123\" if match or NoneType if not.\ns.group(0)\n\n" ]
[ -2 ]
[ "numbers", "python", "string" ]
stackoverflow_0007085512_numbers_python_string.txt
Q: Emacs Lisp: Open a new frame, start IPython, run previous buffer I want to write an ELisp function to start a Python interpreter (IPython) in a new frame and then run the contents of the previous buffer in the IPython interpreter. I am using Emacs 23.3.1, python-mode 6.0 and ipython.el. Here's my function so far:...
Emacs Lisp: Open a new frame, start IPython, run previous buffer
I want to write an ELisp function to start a Python interpreter (IPython) in a new frame and then run the contents of the previous buffer in the IPython interpreter. I am using Emacs 23.3.1, python-mode 6.0 and ipython.el. Here's my function so far: (defun python-run () "Use to run Python programs." (interactive) ...
[ "Not sure about that python output but in the elisp code you are not setting my-buffer-name to anything (it will be nil). It should be:\n(let ((my-buffer-name (buffer-name))\n ....\n\n" ]
[ 0 ]
[]
[]
[ "elisp", "emacs", "ipython", "python" ]
stackoverflow_0007075742_elisp_emacs_ipython_python.txt
Q: Assigning multiple array indices at once in Python/Numpy I'm looking to quickly (hopefully without a for loop) generate a Numpy array of the form: array([a,a,a,a,0,0,0,0,0,b,b,b,0,0,0, c,c,0,0....]) Where a, b, c and other values are repeated at different points for different ranges. I'm really thinking of someth...
Assigning multiple array indices at once in Python/Numpy
I'm looking to quickly (hopefully without a for loop) generate a Numpy array of the form: array([a,a,a,a,0,0,0,0,0,b,b,b,0,0,0, c,c,0,0....]) Where a, b, c and other values are repeated at different points for different ranges. I'm really thinking of something like this: import numpy as np a = np.zeros(100) a[0:3,9:11...
[ "If you have the values and repeat counts fully specified, you can do it this way:\n>>> import numpy\n>>> values = numpy.array([1,0,2,0,3,0])\n>>> counts = numpy.array([4,5,3,3,2,2])\n>>> numpy.repeat(values, counts)\narray([1, 1, 1, 1, 0, 0, 0, 0, 0, 2, 2, 2, 0, 0, 0, 3, 3, 0, 0])\n\n", "you can use numpy.r_:\n>...
[ 4, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007085627_numpy_python.txt
Q: How to avoid enormous additional memory consumption when using numpy vectorize? This code below best illustrates my problem: The output to the console (NB it takes ~8 minutes to run even the first test) shows the 512x512x512x16-bit array allocations consuming no more than expected (256MByte for each one), and look...
How to avoid enormous additional memory consumption when using numpy vectorize?
This code below best illustrates my problem: The output to the console (NB it takes ~8 minutes to run even the first test) shows the 512x512x512x16-bit array allocations consuming no more than expected (256MByte for each one), and looking at "top" the process generally remains sub-600MByte as expected. However, while t...
[ "It is a basic problem of vectorisation that all intermediate values are also vectors. While this is a convenient way to get a decent speed enhancement, it can be very inefficient with memory usage, and will be constantly thrashing your CPU cache. To overcome this problem, you need to use an approach which has expl...
[ 3, 2 ]
[]
[]
[ "memory", "numpy", "python", "vectorization" ]
stackoverflow_0007078371_memory_numpy_python_vectorization.txt
Q: Inheritance in Python? Suppose that I have the following python base class: class BaseClass(object): def a(): """This method uses method b(), defined in the inheriting class""" And also a class that inherites BaseClass: class UsedByUser(BaseClass): def b(): """b() is defined here, yet is u...
Inheritance in Python?
Suppose that I have the following python base class: class BaseClass(object): def a(): """This method uses method b(), defined in the inheriting class""" And also a class that inherites BaseClass: class UsedByUser(BaseClass): def b(): """b() is defined here, yet is used by the base class""" My...
[ "I would define the b method in the BaseClass too:\nclass BaseClass(object):\n def b(self):\n raise NotImplementedError('b must be implemented by a subclass')\n\nRemember: explicit is better than implicit and given that the method a needs the method b anyways, better raise a meaningful exception rather th...
[ 7, 0, 0 ]
[ "BaseClass can't assume that a UsedByUser object exists, so it can't use a B() method from it. You probably want to define a B() in BaseClass, that either does nothing (if it's sensible to attempt B() with something that doesn't support it) or raises an exception (if it's not sensible to attempt B()). \nIf you tell...
[ -1 ]
[ "python" ]
stackoverflow_0007086348_python.txt
Q: Python recursive function exceeds recursion limit. How can I convert it to iteration I have created a function that reads lists of ID pairs (i.e. [("A","B"),("B","C"),("C","D"),...] and sequences the ID's from start to finish including any branches. Each list of ordered ID's is held in a class called an Alignment ...
Python recursive function exceeds recursion limit. How can I convert it to iteration
I have created a function that reads lists of ID pairs (i.e. [("A","B"),("B","C"),("C","D"),...] and sequences the ID's from start to finish including any branches. Each list of ordered ID's is held in a class called an Alignment and this function uses recursion to handle branches by creating a new alignment starting a...
[ "your code is a disorganised muddle. i can't tell what it is supposed to be doing in detail. if you were more careful (neater, clearer) then you would probably also find it easier to refactor.\nanyway, this may do something like what you want:\nfrom collections import defaultdict\n\ndef expand(line, links, known)...
[ 15 ]
[]
[]
[ "iteration", "python", "recursion", "refactoring", "sequencing" ]
stackoverflow_0007083011_iteration_python_recursion_refactoring_sequencing.txt
Q: Proper way to organize testcases that involve a data file for each testcase? I'm writing a module that involves parsing html for data and creating an object from it. Basically, I want to create a set of testcases where each case is an html file paired with a golden/expected pickled object file. As I make changes t...
Proper way to organize testcases that involve a data file for each testcase?
I'm writing a module that involves parsing html for data and creating an object from it. Basically, I want to create a set of testcases where each case is an html file paired with a golden/expected pickled object file. As I make changes to the parser, I would like to run this test suite to ensure that each html page is...
[ "I've done similar things with the unittest framework by writing a function which creates and returns a test class. This function can then take in whatever parameters you want and customise the test class accordingly. You can also customise the __doc__ attribute of the test function(s) to get customised messages wh...
[ 4, 3 ]
[]
[]
[ "python", "testing", "unit_testing" ]
stackoverflow_0007086295_python_testing_unit_testing.txt
Q: Efficient 2D edge detection in Python I know that this problem has been solved before, but I've been great difficulty finding any literature describing the algorithms used to process this sort of data. I'm essentially doing some edge finding on a set of 2D data. I want to be able to find a couple points on an ey...
Efficient 2D edge detection in Python
I know that this problem has been solved before, but I've been great difficulty finding any literature describing the algorithms used to process this sort of data. I'm essentially doing some edge finding on a set of 2D data. I want to be able to find a couple points on an eye diagram (generally used to qualify high s...
[ "Have you tried OpenCV (Open Computer Vision)? It's widely used and has a Python binding.\nNot to be a PITA, but are you sure you wouldn't be better off with a numerical approach? All the tools I've seen for eye-diagram analysis go the numerical route; I haven't seen a single one that analyzes the image itself. \nY...
[ 3, 1 ]
[]
[]
[ "image_processing", "numpy", "python", "scipy" ]
stackoverflow_0007084339_image_processing_numpy_python_scipy.txt
Q: Does whoosh require all strings to be unicode? I am redoing my search app in Whoosh from Solr. I am now learning from the quick start. But I kept running into problems each time I had to deal with strings >>>writer.add_document(iden=fil, content=F2T.file_to_text(fil_path)) ValueError: 'File Name.doc' is not unicod...
Does whoosh require all strings to be unicode?
I am redoing my search app in Whoosh from Solr. I am now learning from the quick start. But I kept running into problems each time I had to deal with strings >>>writer.add_document(iden=fil, content=F2T.file_to_text(fil_path)) ValueError: 'File Name.doc' is not unicode or sequence and then: >>>query = QueryParser("cont...
[ "Yes, it requires strings are in Unicode.\n query = QueryParser(\"content\", ix.schema).parse(\"first\")\n\nChange that to:\nquery = QueryParser(\"content\", ix.schema).parse(u\"first\")\n\n" ]
[ 9 ]
[]
[]
[ "python", "whoosh" ]
stackoverflow_0006897042_python_whoosh.txt
Q: Could as_view() (for class-based views) be implemented in a decorator? Django's as_view() syntax for Class-based views has been bugging me. Basically, I am tired of having to do a my_view = MyView.as_view() for every class-based view that I want to use (or putting as_view() in every line of every url conf I use c...
Could as_view() (for class-based views) be implemented in a decorator?
Django's as_view() syntax for Class-based views has been bugging me. Basically, I am tired of having to do a my_view = MyView.as_view() for every class-based view that I want to use (or putting as_view() in every line of every url conf I use c-based views in). I think a class decorator would be a cleaner way to implem...
[ "One approach that comes to mind is to have the class decorator just setattr some object which will contain all the as_views you want defined. You could then use that in your urls.py\nimport re\n\nclass Views(object):\n \"\"\"Empty object for holding as_view method\"\"\"\nviews = Views()\n\ndef convert_name(name...
[ 1 ]
[]
[]
[ "decorator", "django", "django_views", "python" ]
stackoverflow_0007086272_decorator_django_django_views_python.txt
Q: Can a python script decrypt a HASH that was created in a C++ program? I have a competition that people can enter with a secret code they discover in an Android app. The method I have chosen to ensure only people who have purchased the app can enter the competition is to use shared secret encoded(encrypted?) with H...
Can a python script decrypt a HASH that was created in a C++ program?
I have a competition that people can enter with a secret code they discover in an Android app. The method I have chosen to ensure only people who have purchased the app can enter the competition is to use shared secret encoded(encrypted?) with HMAC SHA256. So my secret will be encrypted in C in the Android app (using C...
[ "When using a hash that way, normally you would pass the secret code (in plaintext) and the hash of both the secret code and the shared secret to your web site. The web site can then perform the same hash (as it knows the shared secret), and verify that the result is the same.\n'Cracking' the hash on your server is...
[ 0 ]
[]
[]
[ "c++", "encryption", "hash", "hmac", "python" ]
stackoverflow_0007086825_c++_encryption_hash_hmac_python.txt
Q: Boost.Python: Callbacks to class functions I have an EventManager class written in C++ and exposed to Python. This is how I intended for it to be used from the Python side: class Something: def __init__(self): EventManager.addEventHandler(FooEvent, self.onFooEvent) def __del__(self): EventM...
Boost.Python: Callbacks to class functions
I have an EventManager class written in C++ and exposed to Python. This is how I intended for it to be used from the Python side: class Something: def __init__(self): EventManager.addEventHandler(FooEvent, self.onFooEvent) def __del__(self): EventManager.removeEventHandler(FooEvent, self.onFooEv...
[ "Without weakref.ref(self.onFooEvent) you will never get your expected behaviour! See my comment.\n" ]
[ 0 ]
[]
[]
[ "boost", "c++", "python" ]
stackoverflow_0006899108_boost_c++_python.txt
Q: How to represent geographical locations I make the user interface appear adding integration with facebook and enabling combining a search with a category and a location: This poses some problems to me not only with the facebook integration but also with locations. I don't fetch the locations from the datastore, I...
How to represent geographical locations
I make the user interface appear adding integration with facebook and enabling combining a search with a category and a location: This poses some problems to me not only with the facebook integration but also with locations. I don't fetch the locations from the datastore, I just put them in plain html: <select name="w...
[ "Why not just do:\n<option value=\"{lat:-22.45,long:-43.12,r:294200}\">Rio De Janeiro</option>\n\nThen you can jsondecode the value to get the components of it.\n", "Most likely you look for a quadkey. A quadkey is a spatial index or a space-filling-curce. It looks like a quadtree or a fractal and reduce the 2d c...
[ 2, 1, 0 ]
[]
[]
[ "geocoding", "google_app_engine", "google_maps", "html", "python" ]
stackoverflow_0007084356_geocoding_google_app_engine_google_maps_html_python.txt
Q: in place sort returns None for empty list Why is it that [].sort() != [] but instead [].sort() = None? Logically, it seems that the first case should be true. A: It's because sort always returns None, it's an in-place sort. Use sorted instead. >>> sorted([]) == [] True A: It's because lists are mutable. [].sor...
in place sort returns None for empty list
Why is it that [].sort() != [] but instead [].sort() = None? Logically, it seems that the first case should be true.
[ "It's because sort always returns None, it's an in-place sort. Use sorted instead.\n>>> sorted([]) == []\nTrue\n\n", "It's because lists are mutable. [].sort() doesn't return a new list, it just changes the existing one, so the return value is nothing, or None. It's the same reason when you go to sort, you don't ...
[ 17, 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007085967_python.txt
Q: In python how can i print only the first line of stdout which results from a shell command in the following for loop, i print the version number of program installed for program in sub3_required_programs: try: version = subprocess.call([program, '-i']) ...
In python how can i print only the first line of stdout which results from a shell command
in the following for loop, i print the version number of program installed for program in sub3_required_programs: try: version = subprocess.call([program, '-i']) print version + '\n' except: exit ...
[ "You can do: \nprint version.split(\"\\n\")[0]\n\nwhich gets first line (splitting on newline character) from the output.\n", "The problem with the str.split('\\n') approach is that the newline character can differ across platforms. You might have better luck doing:\nprint version.splitlines()[0]\n\n", "Split t...
[ 4, 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007084044_python.txt
Q: Twisted threading howto avoid deepcopy I have a twisted server which does some "long" task for each request so i defer to thread each call. In each request i access a common resource, which gets altered during the process. Each request should start with the original data so i use deepcopy on the common resource (w...
Twisted threading howto avoid deepcopy
I have a twisted server which does some "long" task for each request so i defer to thread each call. In each request i access a common resource, which gets altered during the process. Each request should start with the original data so i use deepcopy on the common resource (while invoking a lock acquire). It works, BUT...
[ "Try operating with the minimum data possible in your worker threads. Pass all data that they need in as arguments and take all of their output as the return value (the value the Deferred fires with) rather than as mutations to the inputs.\nThen integrate the results into the common data structure in the reactor t...
[ 3, 2 ]
[]
[]
[ "deep_copy", "multithreading", "python", "twisted" ]
stackoverflow_0007083427_deep_copy_multithreading_python_twisted.txt
Q: adding to a list defined in a function How can I create a list in a function, append to it, and then pass another value into the function to append to the list. For example: def another_function(): y = 1 list_initial(y) def list_initial(x): list_new = [ ] list_new.append(x) print list_initial ...
adding to a list defined in a function
How can I create a list in a function, append to it, and then pass another value into the function to append to the list. For example: def another_function(): y = 1 list_initial(y) def list_initial(x): list_new = [ ] list_new.append(x) print list_initial another_function() list_initial(2) Thanks!...
[ "I'm guessing you're after something like this:\n#!/usr/bin/env python\n\ndef make_list(first_item):\n list_new = []\n list_new.append(first_item)\n return list_new\n\ndef add_item(list, item):\n list.append(item)\n return list\n\nmylist = make_list(1)\nmylist = add_item(mylist, 2)\n\nprint mylist ...
[ 7, 5 ]
[]
[]
[ "append", "function", "list", "python" ]
stackoverflow_0007087287_append_function_list_python.txt
Q: averages of a two dimensional list Basically, the function should deliver the average of the lists within the list. Example: lst = [[46, 27, 68], [26, 65, 80], [98, 56, 35], [98, 65, 0]] average(lst) >>> [47.0, 57.0, 63.0, 54.33333333333333] My code: def average(l): for i in range(len(l)): for j in r...
averages of a two dimensional list
Basically, the function should deliver the average of the lists within the list. Example: lst = [[46, 27, 68], [26, 65, 80], [98, 56, 35], [98, 65, 0]] average(lst) >>> [47.0, 57.0, 63.0, 54.33333333333333] My code: def average(l): for i in range(len(l)): for j in range(len(l[0])): l[i] / l[j]...
[ "First - indentation is important:\nThen thou must space to four. Four shall be the number of the\nspacing and the number of the spacing shall be four. Five shalt\nthou not space, neither shalt thou space three, excepting that\nthou then proceedeth to four. Tab characters are right out.\n\nSecond - use helpful vari...
[ 5, 3, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005073190_python.txt
Q: Improve my Shared Secret Algorithm/Methodology & suggest a Encryption Protocol I am looking for protocol/algorithm that will allow me to use a shared secret between my App & a HTML page. The shared secret is designed to ensure only people who have the app can access the webpage. My Problem: I do not know what alg...
Improve my Shared Secret Algorithm/Methodology & suggest a Encryption Protocol
I am looking for protocol/algorithm that will allow me to use a shared secret between my App & a HTML page. The shared secret is designed to ensure only people who have the app can access the webpage. My Problem: I do not know what algorithm(my methodology to validate a valid access to the HTML page) & what encryption...
[ "\nespecially if the hash algorithm doesn't produce the same result for the same in put all the time.\n\nThen the hash is broken. Why wouldn't it?\nYou want HMAC in the simple case. You are \"signing\" your request using the shared secret, and the signature is verified by the server. Note that the HMAC should inclu...
[ 3, 0, 0 ]
[]
[]
[ "c++", "encryption", "hash", "python" ]
stackoverflow_0007087395_c++_encryption_hash_python.txt
Q: Hyperlinks in QTreeView I'm trying to display clickable links within a QTreeView. I've created my own QStyledItemDelegate, and I can draw text that looks like a link, but isn't clickable like a link would be. One option I'm thinking of is creating a QLabel with a link, and drawing the QLabel inside the QTreeVi...
Hyperlinks in QTreeView
I'm trying to display clickable links within a QTreeView. I've created my own QStyledItemDelegate, and I can draw text that looks like a link, but isn't clickable like a link would be. One option I'm thinking of is creating a QLabel with a link, and drawing the QLabel inside the QTreeView cells. The only problem i...
[ "Have you checked out QAbstractItemView::setIndexWidget? You could create a QLabel like you said and pass it this function for the correct index. \n" ]
[ 1 ]
[]
[]
[ "hyperlink", "pyqt", "python", "qt", "qtreeview" ]
stackoverflow_0007087064_hyperlink_pyqt_python_qt_qtreeview.txt
Q: python executable file in windows Okay, I'm completely new to this. I created a python script that imports tkinter. On my Ubuntu, I can execute the program from the terminal program. Till now there is no problem. However, my friends asked if I could deliver the program to them so that they could use it on their P...
python executable file in windows
Okay, I'm completely new to this. I created a python script that imports tkinter. On my Ubuntu, I can execute the program from the terminal program. Till now there is no problem. However, my friends asked if I could deliver the program to them so that they could use it on their PC. They have 0 knowledge of programming...
[ "You can't use py2exe on plain Ubuntu. It needs to run from Windows. Right now, py2exe doesn't work well with Wine. Do you not have access to any Windows computers (maybe one of your friends')?\nYou can also get your friends to install Python on their Windows machines and teach them how to run your programs, if you...
[ 3 ]
[]
[]
[ "executable", "python" ]
stackoverflow_0007087529_executable_python.txt
Q: How do I obtain django default settings values NOT defined in my settings.py file? I must be missing something. I'm trying to import DEFAULT_CONTENT_TYPE from the settings file. I don't define it specifically in my settings.py file, but I was assuming that the default would be available. When I add this variable ...
How do I obtain django default settings values NOT defined in my settings.py file?
I must be missing something. I'm trying to import DEFAULT_CONTENT_TYPE from the settings file. I don't define it specifically in my settings.py file, but I was assuming that the default would be available. When I add this variable to my settings.py it works fine, but when it's not there and I try to import I get an Im...
[ "Never user from settings import ... or import settings. This will always only import your settings module, but not the whole Django settings.\nUse from django.conf import settings instead in all your Django projects. This is using the Django Settings class which is a wrapper around all Django defined settings and ...
[ 5, 0 ]
[]
[]
[ "django", "django_settings", "python" ]
stackoverflow_0007087405_django_django_settings_python.txt
Q: Multiple Sockets/Reuse/Close Sockets in Python? _socketobject error so I've been trying to make this bot in python that uses sockets to get some information to and from a chat on a website. This requires a login, which gets keys, then using the keys from the first connection, you can connect to the chat (different...
Multiple Sockets/Reuse/Close Sockets in Python? _socketobject error
so I've been trying to make this bot in python that uses sockets to get some information to and from a chat on a website. This requires a login, which gets keys, then using the keys from the first connection, you can connect to the chat (different socket/ip) I tried doing this with socket.close() and whatnot, but alas ...
[ "You had imported the socket module before. Then you create a global variable with the same name (\"socket\"), which now takes the place of the module. The module disappeared, and is now a socket object. Then when you try to call socket_make a second time, the global socket is no longer the module, but the socket i...
[ 1 ]
[]
[]
[ "bots", "packet", "python", "sockets" ]
stackoverflow_0007086943_bots_packet_python_sockets.txt
Q: getting a boundary of an item from another list I have a list which is like, tlist = [0.0, 0.07, 0.13, 0.15, 0.2, 0.22] (which is sorted) I have another list which is, newlist = [0.0, 0.04, 0.08, 0.12, 0.16, 0.2] (numbers with a difference of 0.04) I have to go through each item of the second list and check in ...
getting a boundary of an item from another list
I have a list which is like, tlist = [0.0, 0.07, 0.13, 0.15, 0.2, 0.22] (which is sorted) I have another list which is, newlist = [0.0, 0.04, 0.08, 0.12, 0.16, 0.2] (numbers with a difference of 0.04) I have to go through each item of the second list and check in which boundary (between which two numbers from the tl...
[ "Simple approach using enumerate:\nfor n in newlist:\n for i, t in enumerate(tlist):\n if t > n:\n # found upper boundry, previous must be equal or lower\n upper, lower = t, tlist[i-1]\n break\n print lower, n, upper\n\n", "Somewhat plain and assuming tlist is sorted\...
[ 4, 2, 2, 2, 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007070526_python.txt
Q: Error using NumPy.fromiter() with MySQL query results I have a very simple query, and I'm trying to convert it into a NumPy array using the fromiter() function. However, I can't figure out why it's not working, or what the error below means. Any ideas? import numpy as np c.execute("SELECT video_id FROM video") r...
Error using NumPy.fromiter() with MySQL query results
I have a very simple query, and I'm trying to convert it into a NumPy array using the fromiter() function. However, I can't figure out why it's not working, or what the error below means. Any ideas? import numpy as np c.execute("SELECT video_id FROM video") results = c.fetchall() D = np.fromiter(results, dtype=float,...
[ "As before, results returns tuples, so you will have to pull the value out of the tuple using itertools.imap, or your own iterable adapter.\nresults = itertools.imap(lambda t: t[0], results)\n\nBut I'm just guessing the index since I don't know what you are querying.\n", "import numpy as np\nfrom itertools import...
[ 2, 2, 0 ]
[]
[]
[ "database", "mysql", "numpy", "python", "sql" ]
stackoverflow_0007087897_database_mysql_numpy_python_sql.txt
Q: Python 3.x: urllib.request error My code: import urllib.request, urllib.parse, urllib.error def login(): url = 'http://rsbot.lt/news.php' values = {'user_name' : 'Name', 'user_pass' : 'Password' } data = urllib.parse.urlencode(values) req = urllib.request.Request(url, data) res...
Python 3.x: urllib.request error
My code: import urllib.request, urllib.parse, urllib.error def login(): url = 'http://rsbot.lt/news.php' values = {'user_name' : 'Name', 'user_pass' : 'Password' } data = urllib.parse.urlencode(values) req = urllib.request.Request(url, data) response = urllib.request.urlopen(req) ...
[ "The error tells you what you are doing wrong:\n\"TypeError: POST data should be bytes or an iterable of bytes. It cannot be str.\"\nYou should use a bytes type, not a str type for the POST data.\nIf you look at your data type, by doing type(data), you'll see that it is a str, but it should be a bytes.\nIf you then...
[ 6 ]
[]
[]
[ "python", "python_3.x", "urllib" ]
stackoverflow_0007081488_python_python_3.x_urllib.txt
Q: how to parse a dynamically updating .jsp form using python mechanize? I'm learning how to use Python Mechanize to scrape some data. For the most part, it's working, but one problem I've run into is that the .jsp page I'm looking at updates dynamically instead of using a 'submit' button. I'm running into two relate...
how to parse a dynamically updating .jsp form using python mechanize?
I'm learning how to use Python Mechanize to scrape some data. For the most part, it's working, but one problem I've run into is that the .jsp page I'm looking at updates dynamically instead of using a 'submit' button. I'm running into two related issues as a result: 1) There are multiple SelectControls I need to set on...
[ "Mechanize doesn't handle javascript, you could replicate what the javascript does (eg find out the possible values and build/select it manually). See this answer for more details and an alternative solution How to properly use mechanize to scrape AJAX sites\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "javascript", "mechanize", "python", "web_scraping" ]
stackoverflow_0007086895_beautifulsoup_javascript_mechanize_python_web_scraping.txt
Q: How to iterate a list over re.sub and replace variables in a string using python? I have a string say: s = 'deviceId={servicename.DeviceID}&deviceGroupID={servicename.GroupID}&abcd=dkef' I could get the data by parsing several XMLs for the items in Parentheses. After obtaining the data, I use dictset's combinator...
How to iterate a list over re.sub and replace variables in a string using python?
I have a string say: s = 'deviceId={servicename.DeviceID}&deviceGroupID={servicename.GroupID}&abcd=dkef' I could get the data by parsing several XMLs for the items in Parentheses. After obtaining the data, I use dictset's combinator to yield these results(roughly) for the items in parantheses {} : ['ApplC3LDJXGEDCP7',...
[ "Use single sub call and pass a function that returns what you need.\ns = 'deviceId={servicename.DeviceID}&deviceGroupID={servicename.GroupID}&abcd=dkef'\nr = ['ApplC3LDJXGEDCP7', '10']\nprint(re.sub(r'{.+?}', lambda match: r.pop(0), s, count=len(r)))\n# deviceId=ApplC3LDJXGEDCP7&deviceGroupID=10&abcd=dkef\n\nA bet...
[ 3 ]
[]
[]
[ "list", "loops", "python", "regex" ]
stackoverflow_0007087841_list_loops_python_regex.txt
Q: Programmatically tell if a Unicode character takes up more than one character space in a terminal I discovered that in the Mac OS X Terminal, some Unicode characters take up more than one character space. For example 27FC (long rightwards arrow from bar). It prints two characters wide, but the second character p...
Programmatically tell if a Unicode character takes up more than one character space in a terminal
I discovered that in the Mac OS X Terminal, some Unicode characters take up more than one character space. For example 27FC (long rightwards arrow from bar). It prints two characters wide, but the second character prints on top of whatever the next character is, so you have to do ⟼<space> for it to print correctly. ...
[ "While it's not relevant for the specific examples you give (all of which display at the size of a single character for me on Ubuntu), CJK characters have a unicode property which indicates that they are wider than normal, and display at double width in some terminals.\nFor example, in python:\n# 'a' is a normal (n...
[ 7, 4, 1 ]
[]
[]
[ "python", "terminal", "unicode" ]
stackoverflow_0007086856_python_terminal_unicode.txt
Q: Python with regex to replace strings recursively I've tried different ideas for this but haven't been successful yet. Hence this post. Some background: I am trying to decipher a Makefile that might include variables from a separate file. I've managed to read all the variables in Makefile and also its includes succ...
Python with regex to replace strings recursively
I've tried different ideas for this but haven't been successful yet. Hence this post. Some background: I am trying to decipher a Makefile that might include variables from a separate file. I've managed to read all the variables in Makefile and also its includes successfully into a python dictionary. But now I find that...
[ "Take advantage of re.subn, which returns number of replacements (so you know when to stop) and accepts function for repl argument (to select value from vars dictionary):\nimport re\n\nvs = { \n 'A' : '-L${F} ${B} ${D}',\n 'B' : '-L/myhome',\n 'F' : '/usr/lib',\n}\n\nwhile 1:\n treps = 0\n for k in v...
[ 4, 2, 0 ]
[]
[]
[ "python", "recursion", "regex" ]
stackoverflow_0007087905_python_recursion_regex.txt
Q: Getting output of system commands that use pipes (Python) I'm trying to generate a random string using this command: strings /dev/urandom | grep -o '[[:alnum:]]' | head -n 30 | tr -d '\n'; Works fine, but when I try to do subprocess.call(cmd,shell=True) it just gets stuck on the strings /dev/urandom command and s...
Getting output of system commands that use pipes (Python)
I'm trying to generate a random string using this command: strings /dev/urandom | grep -o '[[:alnum:]]' | head -n 30 | tr -d '\n'; Works fine, but when I try to do subprocess.call(cmd,shell=True) it just gets stuck on the strings /dev/urandom command and spams my screen with grep: writing output: Broken pipe What's ca...
[ "No need for subprocess, observe:\n>>> import base64\n>>> r = open(\"/dev/urandom\",\"r\")\n>>> base64.encodestring(r.read(22))[:30]\n'3Ttlx6TT3siM8h+zKm+Q6lH1k+dTcg'\n>>> r.close()\n\nAlso, stringsing and then greping alphanumeric characters from /dev/urandom is hugely inefficient and wastes a whole lot of randomn...
[ 5, 0 ]
[]
[]
[ "linux", "pipe", "python" ]
stackoverflow_0007088175_linux_pipe_python.txt
Q: column user_id is not unique, with Django UserProfiles I'm trying to add some extra attributes to a user by way of a User Profile in Django (1.2.5, the version supplied in Ubuntu natty), but whenever I create a new user through the admin console, with one of the new attributes included (eg, 'phone'), I get a "colu...
column user_id is not unique, with Django UserProfiles
I'm trying to add some extra attributes to a user by way of a User Profile in Django (1.2.5, the version supplied in Ubuntu natty), but whenever I create a new user through the admin console, with one of the new attributes included (eg, 'phone'), I get a "column user_id is not unique" IntegrityError. I see that other p...
[ "There are two attempts to create the same profile. One from the signal and one directly from the inlined admin form.\nThis question/answer covers it and a potential solution in more detail.\n", "Perhaps check to see if this is a signal for creating a user. You may be seeing a race condition with a number of call...
[ 5, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007086578_django_python.txt
Q: Plotting changing arrays I am trying to plot a real-time signal. I have an array of size 4 that is refreshed every 1/32nd of a second with new data and I need to plot these values for at least 1 sec. That means, there would be 32 of these arrays of size 4 each. This implies, I will have 32*4 = 128 data points to ...
Plotting changing arrays
I am trying to plot a real-time signal. I have an array of size 4 that is refreshed every 1/32nd of a second with new data and I need to plot these values for at least 1 sec. That means, there would be 32 of these arrays of size 4 each. This implies, I will have 32*4 = 128 data points to plot vs the no.of samples(1,2,...
[ "I like to use wxPython for real time things. Here is an example application that does what you ask. It retrieves generated readings and plots in a window. \n(Since I can't see your data, I generate a sine wave in a separate thread and plot it)\nimport wx\nfrom Queue import Queue, Empty, Full\nimport threading\nfro...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007087971_python.txt
Q: Slow Big Int Output in python Is there anyway to improve performance of "str(bigint)" and "print bigint" in python ? Printing big integer values takes a lot of time. I tried to use the following recursive technique : def p(x,n): if n < 10: sys.stdout.write(str(x)) return n >>= 1 ...
Slow Big Int Output in python
Is there anyway to improve performance of "str(bigint)" and "print bigint" in python ? Printing big integer values takes a lot of time. I tried to use the following recursive technique : def p(x,n): if n < 10: sys.stdout.write(str(x)) return n >>= 1 l = 10**n k = x/l p(k,n) ...
[ "Conversion from a Python integer to a string has a running of O(n^2) where n is the length of the number. For sufficiently large numbers, it will be slow. For a 1,000,001 digit number, str() takes approximately 24 seconds on my computer.\nIf you are really needing to convert very large numbers to a string, your re...
[ 1, 0 ]
[]
[]
[ "biginteger", "python" ]
stackoverflow_0007088297_biginteger_python.txt
Q: Python error when using os.popen() Well, I have a python script running on Mac OS X. Now I need to modify it to support updating my SVN working copy into a specified time. However, after learning I've found that SVN commands only support updating the working copy into a specified version. So I write a function to ...
Python error when using os.popen()
Well, I have a python script running on Mac OS X. Now I need to modify it to support updating my SVN working copy into a specified time. However, after learning I've found that SVN commands only support updating the working copy into a specified version. So I write a function to grub the information from the command: s...
[ "I get that error whenever I use svn log | head, too, it's not Python specific. Try something like:\nfrom subprocess import PIPE, Popen\n\nprocess = Popen('svn log XXX', stdout=PIPE, stderr=PIPE)\nprint process.stdout.readline()\nprint process.stdout.readline()\n\nto suppress the stderr. You could also just use \ns...
[ 1, 1 ]
[]
[]
[ "macos", "popen", "python", "svn" ]
stackoverflow_0007088924_macos_popen_python_svn.txt
Q: python: can i import the module namespace within the module itself? Since variables names are declared local if there is an assignment to them within a function, and I want to access the module variables from within a function, can I import the module name within the module and then use that to access the module v...
python: can i import the module namespace within the module itself?
Since variables names are declared local if there is an assignment to them within a function, and I want to access the module variables from within a function, can I import the module name within the module and then use that to access the module variables ? Example (file name : server.py): import server bar = 5 def f...
[ "Instead of using the global statement, as suggested in all of the other answers, don't use module level variables, but a class as a container or else another module just for the globals:\n# mg.py\n\nbar = 5\n\n# server.py\nimport mg\n\ndef foo():\n mg.bar = 10\n\nor\nclass mg:\n bar = 5\n\ndef foo():\n mg...
[ 6, 1, 1, 0 ]
[]
[]
[ "python", "python_module", "scope" ]
stackoverflow_0007089099_python_python_module_scope.txt
Q: how can I manage session with mod_wsgi with apache webserver? I've created a python script running under mod_wsgi with apache, I want to manage sessions, authentication and timeout. what would be the best way to achieve it? I'm using apache 2.x and mod_wsgi 2.x I've seen few mod_wsgi Directives but any help or art...
how can I manage session with mod_wsgi with apache webserver?
I've created a python script running under mod_wsgi with apache, I want to manage sessions, authentication and timeout. what would be the best way to achieve it? I'm using apache 2.x and mod_wsgi 2.x I've seen few mod_wsgi Directives but any help or article_URL may help me more. References: mod_wsgi Directive Reference...
[ "\"Middleware and libraries for WSGI\"\n", "See the WSGI middleware package called AuthKit.\nhttp://authkit.org/\n" ]
[ 3, 1 ]
[ "Don't try and re-invent the wheel. Use a framework.\n" ]
[ -2 ]
[ "apache", "authentication", "mod_wsgi", "python", "session" ]
stackoverflow_0007088888_apache_authentication_mod_wsgi_python_session.txt
Q: python - how can I display a image from web? I'm using Python to make a "web album viewer", but I meet some problem. I use Tkinter to write GUI, urllib2 to fetch the image from web, PIL to handle the image So the code is like this: root = Tk() frame = Frame(root) frame.pack() response = urllib2.urlopen(a_pic_url) ...
python - how can I display a image from web?
I'm using Python to make a "web album viewer", but I meet some problem. I use Tkinter to write GUI, urllib2 to fetch the image from web, PIL to handle the image So the code is like this: root = Tk() frame = Frame(root) frame.pack() response = urllib2.urlopen(a_pic_url) photo = ImageTk.PhotoImage(Image.open(response.rea...
[ "Image.open takes a filename or a file object, not a str which is what is returned by read. \nEither save the image to a file then open that, or use Image.open(response), to use it directly on the file-like objected returned by urlopen.\nEdit: This should work if you're having trouble with the urlopen object:\ntry:...
[ 4, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007089981_python.txt
Q: solve rectangular matrix in python to get solution with arbitrary parameters I want to solve a rectangular system (with arbitrary parameters in the solution). Failing that I would like to add rows to my matrix until it is square. print matrix_a print vector_b print len(matrix_a),len(matrix_a[0]) gives: [[0, 0,...
solve rectangular matrix in python to get solution with arbitrary parameters
I want to solve a rectangular system (with arbitrary parameters in the solution). Failing that I would like to add rows to my matrix until it is square. print matrix_a print vector_b print len(matrix_a),len(matrix_a[0]) gives: [[0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, ...
[ "Here is a simple implementation (with hard coded thresholds), but it gives the solution you are looking for with the test data. \nIt's based on Iteratively Reweighted Least Squares.\nfrom numpy import abs, diag, dot, zeros\nfrom numpy.linalg import lstsq, inv, norm\n\ndef irls(A, b, p= 1):\n \"\"\"Solve least...
[ 3, 2, 1 ]
[]
[]
[ "linear_algebra", "matrix", "numpy", "python", "scipy" ]
stackoverflow_0007076691_linear_algebra_matrix_numpy_python_scipy.txt
Q: Install a different version of Python this might be a very simple question but I need your help. I work in a network and I cannot install the programs I want. Anyway, I need to use another version of python, which is installed in the directory /new_version/. Now, when I type "python" in a shell (I use bash) the co...
Install a different version of Python
this might be a very simple question but I need your help. I work in a network and I cannot install the programs I want. Anyway, I need to use another version of python, which is installed in the directory /new_version/. Now, when I type "python" in a shell (I use bash) the command point to the version of python instal...
[ "Add the line\nexport PATH=/new_version/:$PATH\n\nto your ~/.bashrc (or ~/.bash_profile) file. Then, whenever you run python, it will find the new version first in your PATH. Note this is PATH, not PYTHONPATH. See the comment by @Aaron.\nEdit: Only do it this way if you want python to point to the new version. Use ...
[ 2, 2, 1 ]
[]
[]
[ "python", "shell" ]
stackoverflow_0007090065_python_shell.txt
Q: Pythonpath on Mac OSX I read through Add to python path mac os x and I figured doing that is a good idea, but still IDLE gives me a syntax error for a simple call of open(filename, mode), so I looked a little bit further and I found that I am able to do as stated in http://developer.apple.com/library/mac/#qa/qa106...
Pythonpath on Mac OSX
I read through Add to python path mac os x and I figured doing that is a good idea, but still IDLE gives me a syntax error for a simple call of open(filename, mode), so I looked a little bit further and I found that I am able to do as stated in http://developer.apple.com/library/mac/#qa/qa1067/_index.html and set up an...
[ "PYTHONPATH doesn't effect whether or not you get a SyntaxError -- only an ImportError. So, if you're getting a SyntaxError, you've got another problem with your code. Please post the code and we'll point it out.\nEdit: Your error is on this line:\n@app.route('/proPass', method ='POST')\n\nThe @ designates a decora...
[ 3 ]
[]
[]
[ "macos", "python", "pythonpath", "syntax_error" ]
stackoverflow_0007090527_macos_python_pythonpath_syntax_error.txt