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 chain a ssh, cd, then execution in subprocess.Popen I'm trying to execute the following code but it is not working p = subprocess.Popen("ssh root@IP cd /opt/msys/pe2/bin;./perlscript.pl; -a file.csv", shell=True,stdout=subprocess.PIPE, stderr=subprocess.STDOUT) OR: p = subprocess...
How to chain a ssh, cd, then execution in subprocess.Popen
I'm trying to execute the following code but it is not working p = subprocess.Popen("ssh root@IP cd /opt/msys/pe2/bin;./perlscript.pl; -a file.csv", shell=True,stdout=subprocess.PIPE, stderr=subprocess.STDOUT) OR: p = subprocess.Popen("ssh root@IP /opt/msys/pe2/bin/perlscript.pl; -a file.csv...
[ "Try quoting the command being sent to ssh:\nsubprocess.Popen('ssh root@IP \"cd /opt/msys/pe2/bin;./perlscript.pl;\" -a file.csv'\n\nOtherwise you're telling the local shell to do it.\n", "Subprocess isn't the best tool for this use case. All the process monitoring options (wait() and terminate() for example) ap...
[ 4, 2 ]
[]
[]
[ "python", "ssh" ]
stackoverflow_0007853974_python_ssh.txt
Q: Python shutil.move: odd softlinking A script I wrote was meant to move individual day directories from an old location to a new location with a structure like this: /old/YYYY/MM/DD /new/YYYY/MM/DD and for another task (unrelated to the moving of data) I created a softlink in the new location like this (this was t...
Python shutil.move: odd softlinking
A script I wrote was meant to move individual day directories from an old location to a new location with a structure like this: /old/YYYY/MM/DD /new/YYYY/MM/DD and for another task (unrelated to the moving of data) I created a softlink in the new location like this (this was the first mistake I made): /new/2011/09 ->...
[ "It comes down to these two lines in shutil.move:\n copytree(src, real_dst, symlinks=True)\n rmtree(src)\n\nwhere src='old' and real_dst='new/old'. The copytree command copies old to the subdirectory new/old. That goes fine, although it may not be what you intended. \nrmtree removes the old directory....
[ 1 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0007854608_linux_python.txt
Q: How to find min/max values from rows and columns in Python? I was wondering how can I find minimum and maximum values from a dataset, which is basically a text file. It has 50 rows, 50 columns. I know I can set up a control loop (for loop to be specific) to have it read each row and column, and determine the min/m...
How to find min/max values from rows and columns in Python?
I was wondering how can I find minimum and maximum values from a dataset, which is basically a text file. It has 50 rows, 50 columns. I know I can set up a control loop (for loop to be specific) to have it read each row and column, and determine the min/max values. But, I'm not sure how to do that. I think the rows an...
[ "If the file contains a regular (rectangular) matrix, and you know how many lines of header info it contains, then you can skip over the header info and use NumPy to do this particularly easily:\nimport numpy as np\n\nf = open(\"file.txt\")\n# skip over header info\nX = np.loadtxt(f)\nmax_per_col = X.max(axis=0)\nm...
[ 3, 3, 2, 1 ]
[]
[]
[ "max", "min", "python" ]
stackoverflow_0007854859_max_min_python.txt
Q: Failing to iterate over my list correctly The strange thing is that I'm using Python built in iteration O.o I have a class called Card. Card has, among other things, a name and a list of symbols (string). Here is a piece of my code (all the prints are for debugging purposes) # This prints all the names of the ...
Failing to iterate over my list correctly
The strange thing is that I'm using Python built in iteration O.o I have a class called Card. Card has, among other things, a name and a list of symbols (string). Here is a piece of my code (all the prints are for debugging purposes) # This prints all the names of the cards in the deck before the iteration. pri...
[ "You shouldn't remove items from a list while you iterate over it.\nEither iterate over a copy of the list:\nfor card in self.thegame.game_deck.deck[0][:]:\n ^^^ copies the list\n\nOr create a new list with the items you want to keep and then re-assign it:\ngame_deck = self....
[ 7, 0, 0, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007853898_list_python.txt
Q: How to use datastore id instead of key_name? How to define that? What should be used instead of get_by_key_name SELECT __key__ key().name() A: get_by__id() no change; it's still a key whether it has an ID or a name key().id()
How to use datastore id instead of key_name?
How to define that? What should be used instead of get_by_key_name SELECT __key__ key().name()
[ "\nget_by__id()\nno change; it's still a key whether it has an ID or a name\nkey().id() \n\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0007855099_google_app_engine_google_cloud_datastore_python.txt
Q: How can I set or modify the commit message from a mercurial extension? I'm trying to modify this Mercurial extension to prompt the user to add a FogBugz case number to their commit message. Ideally, I'd like the user to just type in a number after being prompted and have it automatically appended to the commit mes...
How can I set or modify the commit message from a mercurial extension?
I'm trying to modify this Mercurial extension to prompt the user to add a FogBugz case number to their commit message. Ideally, I'd like the user to just type in a number after being prompted and have it automatically appended to the commit message. Here's what I've got so far: def pretxncommit(ui, repo, **kwargs): ...
[ "I didn't end up finding a way using a hook, but I was able to do it using extensions.wrapcommand and modifying the options.\nI've included the source of the resulting extension here.\nUpon detecting the lack of a case in the commit message, my version prompts the user to either enter one, ignore the warning, or ab...
[ 6, 0 ]
[]
[]
[ "fogbugz", "mercurial", "mercurial_extension", "python" ]
stackoverflow_0007854041_fogbugz_mercurial_mercurial_extension_python.txt
Q: PyQt setup for Qt 4.7.4 I try to install PyQt to develop Python apps using Qt. I downloaded SIP and PyQt4 from http://www.riverbankcomputing.co.uk and compiled the packages. But I encountered a problem while compiling PyQt4: I ran python configure.py in the Terminal and I got: Error: Make sure you have a working Q...
PyQt setup for Qt 4.7.4
I try to install PyQt to develop Python apps using Qt. I downloaded SIP and PyQt4 from http://www.riverbankcomputing.co.uk and compiled the packages. But I encountered a problem while compiling PyQt4: I ran python configure.py in the Terminal and I got: Error: Make sure you have a working Qt v4 qmake on your PATH or us...
[ "The error message says that the PyQt installer cannot find the qmake executable.\nRunning these two commands should solve it:\nPATH=$PATH:~/.QtSDK/Simulator/Qt/gcc/bin/\nexport PATH\n\nAfterwards, resume your installation.\n", "make -q /home/user/.QtSDK/Simulator/Qt/gcc/bin/qmake\n\nDoes that work? I'm not sure ...
[ 2, 1 ]
[]
[]
[ "compilation", "configure", "pyqt", "python", "qt" ]
stackoverflow_0007854599_compilation_configure_pyqt_python_qt.txt
Q: Best practice: should I use exception handlers a lot in Python code, or should I avoid if it's possible? I have got a project, where I have to do this very frequently: if "something" in dict: some_var = dict["something"] del dict["something"] else: error_handler_or_other_stuff() However I have the ide...
Best practice: should I use exception handlers a lot in Python code, or should I avoid if it's possible?
I have got a project, where I have to do this very frequently: if "something" in dict: some_var = dict["something"] del dict["something"] else: error_handler_or_other_stuff() However I have the idea to use this: try: some_var = dict.pop("something") except KeyError: error_handler_or_other_stuff() ...
[ "Which construct makes your code easier to understand and maintain? Pick that one.\nIf the resulting code is too slow, then go back and consider whether a different error handling strategy is more efficient.\n", "Why not use dict.get or dict.pop with the default parameter?\n", "Exceptions are not particularly s...
[ 5, 4, 3, 3 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0007850317_exception_python.txt
Q: How do I add a command option to an existing command in a Mercurial extension? I'm working on an extension which includes a pre-commit hook. I'd like to be able to receive a new option within my hook. However, if I add it using the cmdtable example from the documentation, substituting a reference to the existing c...
How do I add a command option to an existing command in a Mercurial extension?
I'm working on an extension which includes a pre-commit hook. I'd like to be able to receive a new option within my hook. However, if I add it using the cmdtable example from the documentation, substituting a reference to the existing commit command, it just overwrites the built-in options. What is the right way to do ...
[ "This is possible by using extensions.wrapcommand:\ndef commit(originalcommit, ui, repo, **opts):\n return originalcommit(ui, repo, **opts)\n\ndef uisetup(ui): \n entry = extensions.wrapcommand(commands.table, \"commit\", commit)\n entry[1].append(('', 'newcommitoption', None, ('Description for the new ...
[ 1 ]
[]
[]
[ "mercurial", "mercurial_extension", "python" ]
stackoverflow_0007854475_mercurial_mercurial_extension_python.txt
Q: py2exe strangley hanging with wxPython program using IEHtmlWindow I have a Python 2.7.2 program with wxPython 2.8.12 and comtypes 0.6.2 dependencies on a win XP SP3 machine. I am using py2exe to produce windows distributables with the following setup: setup( options = { "py2exe": { "...
py2exe strangley hanging with wxPython program using IEHtmlWindow
I have a Python 2.7.2 program with wxPython 2.8.12 and comtypes 0.6.2 dependencies on a win XP SP3 machine. I am using py2exe to produce windows distributables with the following setup: setup( options = { "py2exe": { "packages": ['wx.lib.pubsub'] } }, windows = [ ...
[ "Solved, the problem was that comtypes generated a very large module file which was taking too much time to parse by py2exe:\ncomtypes.gen._3050F1C5_98B5_11CF_BB82_00AA00BDCE0B_0_4_0\nThe workaround is to patch py2exe source code (ver 0.6.9) as pointed out by Erez Bibi in his post:\nhttp://groups.google.com/group/w...
[ 2, 0 ]
[]
[]
[ "comtypes", "py2exe", "python", "wxpython" ]
stackoverflow_0007848616_comtypes_py2exe_python_wxpython.txt
Q: How do I convert the .place() method in python to java? I am trying to convert my Python Code to Java. I need a GUI that is similar to python where I can use widgetname.place(x,y) to place objects anywhere I want in the window. I want to be able to specify where the object is placed in the window. I have tried Gri...
How do I convert the .place() method in python to java?
I am trying to convert my Python Code to Java. I need a GUI that is similar to python where I can use widgetname.place(x,y) to place objects anywhere I want in the window. I want to be able to specify where the object is placed in the window. I have tried GridLayout, GridBagLayout, BoxLayout and FlowLayout. None of tho...
[ "This can be done setting your LayoutManager to null, but it's highly discouraged precisely because it annihilates the goal of layouts, which is to be able to have good-looking frames, regardless of the look and feel, screen resolution, etc.\nYou'd better learn how to use layout managers, because that's the good wa...
[ 4, 3, 1 ]
[]
[]
[ "frame", "java", "python", "windows" ]
stackoverflow_0007852853_frame_java_python_windows.txt
Q: error message concerning deprecation I ran some python code and got this error message: C:\Python26\lib\sets.py:85: DeprecationWarning: functions overriding warnings.showwarning() must support the 'line' argument stacklevel=2) I am not sure if this is some warning that I can just ignore or if this is serious? An...
error message concerning deprecation
I ran some python code and got this error message: C:\Python26\lib\sets.py:85: DeprecationWarning: functions overriding warnings.showwarning() must support the 'line' argument stacklevel=2) I am not sure if this is some warning that I can just ignore or if this is serious? Any input will be appreciated. Thanks
[ "No worries. The warning is about something in the standard library that was already fixed in Python 2.7. You can safely ignore it :-)\nThe sets.py is part of the standard library. Line 85 is just a warning that the sets module is deprecated in favor of the set() builtin method but that won't disappear until Pyt...
[ 2, 0 ]
[]
[]
[ "deprecated", "error_handling", "python" ]
stackoverflow_0007855293_deprecated_error_handling_python.txt
Q: Parallelize calling of object methods I have a list of objects and for each of them I want to call their foo function, passing it the argument bar. I want to parallelize this operation, so right now I'm looking at using Pool.map from the multiprocessing package. I'm not sure how to use map to run an object method,...
Parallelize calling of object methods
I have a list of objects and for each of them I want to call their foo function, passing it the argument bar. I want to parallelize this operation, so right now I'm looking at using Pool.map from the multiprocessing package. I'm not sure how to use map to run an object method, though. How can I do that? Or is there a b...
[ "Define a helper function and pass the object method and its arguments to that function via Pool.map. The helper function would look something like this:\ndef helper(*args):\n return args[0](*args[1:])\n\nAnd you would use it like this:\npool = Pool()\nresults = pool.map(helper, [obj.method, arg1, arg2])\n\nNote...
[ 2 ]
[]
[]
[ "parallel_processing", "python" ]
stackoverflow_0007855534_parallel_processing_python.txt
Q: Checking information in a dataset in Python I currently have a requirement to make a comparison of strings containing MAC addresses (eg. "11:22:33:AA:BB:CC" using Python 2.7. At present, I have a preconfigured set containing the MAC address and my script iterates through the set comparing each new MAC address to ...
Checking information in a dataset in Python
I currently have a requirement to make a comparison of strings containing MAC addresses (eg. "11:22:33:AA:BB:CC" using Python 2.7. At present, I have a preconfigured set containing the MAC address and my script iterates through the set comparing each new MAC address to those in the list. This works great but as the se...
[ "First, you need to profile your code to understand where exactly the bottleneck is...\nAlso, as a generic recommendation, consider psyco, although there are a few times when psyco doesn't help\nOnce you find a bottleneck, cython may be useful, but you need to be sure that you declare all your variables in the cyth...
[ 1, 0, 0 ]
[]
[]
[ "iteration", "list", "performance", "python", "scapy" ]
stackoverflow_0007848391_iteration_list_performance_python_scapy.txt
Q: Python - Should I put my helper functions inside or outside the class? In Python, if some methods of a class need a helper function, but the helper function itself doesn't use anything in the class, should I put the helper function inside or outside the class? I tried putting it inside but PyLint was complaining t...
Python - Should I put my helper functions inside or outside the class?
In Python, if some methods of a class need a helper function, but the helper function itself doesn't use anything in the class, should I put the helper function inside or outside the class? I tried putting it inside but PyLint was complaining that this function could have been put outside. @Karl: The class is a softwar...
[ "When deciding where to put helper functions the question I ask is, \"Is it only for this class?\" If it can help in other places, then it goes at the module level; if it is indeed only for this class, then it goes in the class with either staticmethod (needs no class data to do its job) or classmethod (uses some ...
[ 65, 11 ]
[]
[]
[ "class", "pylint", "python" ]
stackoverflow_0007855237_class_pylint_python.txt
Q: How to write to file in different places? I want to open file add 4 underline character to beginning of line find blank lines replace the newline character in the blank lines with 50 underline characters add new lines before and after 50 underline characters I found many similar questions in stackoverflow but I...
How to write to file in different places?
I want to open file add 4 underline character to beginning of line find blank lines replace the newline character in the blank lines with 50 underline characters add new lines before and after 50 underline characters I found many similar questions in stackoverflow but I could not combine all these operations without...
[ "You're going to have to pick:\n\nUse two files, but never have to store more than 1 line in memory at a time\nor\nBuild the new file in memory as you read the original, then overwrite the original with the new\n\nA file isn't a flexible memory structure. You can't replace the 1 or 2 characters from a newline with ...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007855968_python.txt
Q: How can I use valgrind with Python C++ extensions? I have Python extensions implemented on C++ classes. I don't have a C++ target to run valgrind with. I want to use valgrind for memory check. Can I use valgrind with Python? A: Yes, you can use valgrind with Python. You just need to use the valgrind suppression...
How can I use valgrind with Python C++ extensions?
I have Python extensions implemented on C++ classes. I don't have a C++ target to run valgrind with. I want to use valgrind for memory check. Can I use valgrind with Python?
[ "Yes, you can use valgrind with Python. You just need to use the valgrind suppression file provided by the Python developers, so you don't get a bunch of false positives due to Python's custom memory allocation/reallocation functions.\nThe valgrind suppression file can be found here: http://svn.python.org/projects/...
[ 50, 9, 0 ]
[]
[]
[ "c++", "python", "valgrind" ]
stackoverflow_0003982036_c++_python_valgrind.txt
Q: PyQt Designer where to write code? I have PyQT v.4.8.8 installed.When I draw layouts and I want to view the code , it comes with error that is unable to launch uic as in snapshot: I can compile the .ui files manually in cmdLine. But I dont know where to put the code for slot,methods ,signals. 1- Where should I se...
PyQt Designer where to write code?
I have PyQT v.4.8.8 installed.When I draw layouts and I want to view the code , it comes with error that is unable to launch uic as in snapshot: I can compile the .ui files manually in cmdLine. But I dont know where to put the code for slot,methods ,signals. 1- Where should I set the settings for finding uic to compil...
[ "As the name says, the Qt designer is for interface design only. You cannot use it to write the code for the actual application logic. For this, you'll need a normal Python editor. The exact details on how to use designer files in Python are explained in PyQt reference guide, Using Qt Designer.\nBtw, uic is not ...
[ 11, 4 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0007825851_pyqt_python.txt
Q: Can't run Python .py files from terminal on Mac I just downloaded Python 3.2 to Mac OS 10.6 environment. I'm new to programming and am trying to run my first stand-alone .py file, but I keep getting an error message saying "no such directory or file." The name of the file is "script1.py" and I saved it to /Users/b...
Can't run Python .py files from terminal on Mac
I just downloaded Python 3.2 to Mac OS 10.6 environment. I'm new to programming and am trying to run my first stand-alone .py file, but I keep getting an error message saying "no such directory or file." The name of the file is "script1.py" and I saved it to /Users/billp/Documents. When I open the Terminal to run the f...
[ "Make sure you are in the right working directory after opening terminal. Type\ncd /Users/billp/Documents/\n\n(use tab to autocomplete)\nthen\npython ./script1.py\n\nThis way you are launching python executable and passing it path to your file as the first argument. The shebang #! line you mentioned allows you to l...
[ 14, 4, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007855996_python.txt
Q: Python, command line argument parsing How do you accept/parse command line arguments for a py file that has no class? Here is what I have inside my file test.py: import sys if __name__ == '__main__': How do I get the arguments when the file is executed via command line? I call it via: python test.py <arg1> and ...
Python, command line argument parsing
How do you accept/parse command line arguments for a py file that has no class? Here is what I have inside my file test.py: import sys if __name__ == '__main__': How do I get the arguments when the file is executed via command line? I call it via: python test.py <arg1> and obviously want the value of "arg1".
[ "Look no further than sys.argv, which is a list containing all arguments passed to the program.\n", "try:\n arg = sys.argv[1]\nexcept IndexError:\n print \"No argument specified.\"\n sys.exit(1)\n\n" ]
[ 9, 5 ]
[]
[]
[ "command_line_arguments", "python" ]
stackoverflow_0007856168_command_line_arguments_python.txt
Q: How to translate from a hexdigest to a digest and vice-versa? I want to store hashes as binary (64 bytes). But for any type of API (web service) I would want to pass them around as strings. hashlib.hexdigest() will give me a string, and hashlib.digest() will give me the binary. But if, for example, I read in the b...
How to translate from a hexdigest to a digest and vice-versa?
I want to store hashes as binary (64 bytes). But for any type of API (web service) I would want to pass them around as strings. hashlib.hexdigest() will give me a string, and hashlib.digest() will give me the binary. But if, for example, I read in the binary version from disk, how would I convert it to a string? And if...
[ "You might want to look into binascii module, specifically hexlify and unhexlify functions.\n", "In 2.x you can use str.decode('hex') and str.encode('hex') to convert between raw bytes and a hex string. In 3.x you need to use the binascii module.\n", "You could start with the string version to pass around and d...
[ 10, 7, 6 ]
[]
[]
[ "binary_data", "hash", "python" ]
stackoverflow_0007856196_binary_data_hash_python.txt
Q: Python 3.2.1: Incorrectly reading from text file I have a text file that contains the x- and y-coordinates for the center of a circle, followed by the radius, and the fill color for the circle. THE TEXT FILE (for reference): 30,50 12 goldenrod 78,75 10 coral 14,79 11 tomato 32,77 12 maroon 21,25 15 burlywood 24,67...
Python 3.2.1: Incorrectly reading from text file
I have a text file that contains the x- and y-coordinates for the center of a circle, followed by the radius, and the fill color for the circle. THE TEXT FILE (for reference): 30,50 12 goldenrod 78,75 10 coral 14,79 11 tomato 32,77 12 maroon 21,25 15 burlywood 24,67 14 sienna 62,93 13 chartreuse 24,42 16 olivedrab 79,1...
[ "I think you just need to cut out this line before your for loop:\nlines = inFile.readline()\n\nThat's reading the first line, which you do nothing with, before you go through the file line-by-line.\n" ]
[ 6 ]
[]
[]
[ "file_io", "python", "python_3.x" ]
stackoverflow_0007856384_file_io_python_python_3.x.txt
Q: Subclassed QWebView doesn't react to Hyperlink Clicks This is in Python/PySide. I am trying to create my own Parental WebBrowser by overloading the PySide.QtWebKit.QWebView widget. Then whenever someone clicks a link on the widget I check to see if we are going to an invalid website, if not we proceed, if yes then...
Subclassed QWebView doesn't react to Hyperlink Clicks
This is in Python/PySide. I am trying to create my own Parental WebBrowser by overloading the PySide.QtWebKit.QWebView widget. Then whenever someone clicks a link on the widget I check to see if we are going to an invalid website, if not we proceed, if yes then I redirect to a generic page. So I have subclassed the PyS...
[ "There are several problems with the code you posted. Firstly, you are importing both PySide and PyQt4, which is not a good idea. Secondly, QWebView.linkClicked is a signal, not a protected method, so you can't override it. Thirdly, you are passing a string to QWebView.load, when you should be passing a QtCore.QUrl...
[ 4 ]
[]
[]
[ "pyqt", "pyqt4", "pyside", "python" ]
stackoverflow_0007856504_pyqt_pyqt4_pyside_python.txt
Q: How to define a Python class to inherit all other modules function? I wrote several modules to operate a system for different stuff. Only need the IP address of the system. Now, is it possile to define a class to inherit all functions already developed in other python modules? Thanks,
How to define a Python class to inherit all other modules function?
I wrote several modules to operate a system for different stuff. Only need the IP address of the system. Now, is it possile to define a class to inherit all functions already developed in other python modules? Thanks,
[]
[]
[ "I'm not sure if this is exactly what you're looking for, but you can extend classes from other modules:\nimport other_module\n\nclass MyClass(other_module.OtherClass):\n def my_function(self):\n #do something that calls a function that belonged to OtherClass\n self.other_function()\n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0007856637_python.txt
Q: The end= " " is a error Possible Duplicate: python print end=' ' Hello I've been teaching myself python, and I'm having trouble with the end= " " statement. could anybody help me with it?when i run it in my code it said that is is a invalid syntax. Thx in advance. Am i writing it wrong? Help for a newbie is grea...
The end= " " is a error
Possible Duplicate: python print end=' ' Hello I've been teaching myself python, and I'm having trouble with the end= " " statement. could anybody help me with it?when i run it in my code it said that is is a invalid syntax. Thx in advance. Am i writing it wrong? Help for a newbie is greatly appreciated.
[ "I assume that you are having trouble with print statement, So you are trying to use print(var,end=\"\"). This syntax is only valid with Python 3.0. if you are using Python 2.x then it will show you an error. In order to know which version of python you are using type python --version in your terminal. Python 2.x a...
[ 3, 1 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0007856623_eclipse_pydev_python.txt
Q: Working the function in the background - how? Python and PyQT I have a relatively large application written in Python and using PyQT as a GUI frontend. The entire application is in one class, in one file. Here's an example code: class Application(QMainWindow): def __init__(self): super(etc...) self.con...
Working the function in the background - how? Python and PyQT
I have a relatively large application written in Python and using PyQT as a GUI frontend. The entire application is in one class, in one file. Here's an example code: class Application(QMainWindow): def __init__(self): super(etc...) self.connect(self.mainBtn, SIGNAL("clicked()"), self.do_stuff) def do_st...
[ "Duplicate of Handling gui with different threads,\nHow to keep track of thread progress in Python without freezing the PyQt GUI?, etc.\nYour do_stuff() function needs to start up the computing thread and then return. Multi-threading is the name given to running multiple activities in a single process - by definit...
[ 2 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0007856713_pyqt_python.txt
Q: Can I run some mod_wsgi apps on Python 2.7, and keep the rest on Python 2.5? App A is written in Python 2.5 with Django and runs on an Apache server via mod_wsgi. App B is written in Python 2.7 and I want it to run side-by-side on the same server. I don't want to update App A to use 2.7, or change App B to use 2.5...
Can I run some mod_wsgi apps on Python 2.7, and keep the rest on Python 2.5?
App A is written in Python 2.5 with Django and runs on an Apache server via mod_wsgi. App B is written in Python 2.7 and I want it to run side-by-side on the same server. I don't want to update App A to use 2.7, or change App B to use 2.5. The question: Can I run two Django apps with two separate Python runtimes side-...
[ "Correct, you 'can't have 2.5 and 2.7 Django apps running side by side'. It is not possible. The best you can do is have applications running in different virtual environments but where all virtual environments are for the same Python version as mod_wsgi was compiled for.\n" ]
[ 3 ]
[]
[]
[ "apache", "django", "mod_wsgi", "python", "virtualenv" ]
stackoverflow_0007854203_apache_django_mod_wsgi_python_virtualenv.txt
Q: Change Cursor type in Pygtk Application In my application I want to change cursor type of all buttons, on mouse leave and enter events. for this, I want to write generalized code instead of connecting each button with appropriate signal. here's an example code for it. import gtk class Button(gtk.Button): __gs...
Change Cursor type in Pygtk Application
In my application I want to change cursor type of all buttons, on mouse leave and enter events. for this, I want to write generalized code instead of connecting each button with appropriate signal. here's an example code for it. import gtk class Button(gtk.Button): __gsignals__ = { "leave" : "override", "e...
[ "I know this has been sitting here for a while, so just a thought...perhaps rebuild your GUI (or some mockup) outside of Glade. It really isn't very hard to do, and the documentation is fantastic. \nThen, try and hook up your mouse cursor change codes, and see if it works.\n" ]
[ 0 ]
[]
[]
[ "mouse_cursor", "pygtk", "python" ]
stackoverflow_0006328990_mouse_cursor_pygtk_python.txt
Q: pygtk progressbar is not working when my program receiving new file file is copied fine but progress bar is not moving... if possible please suggest me a better algo.. Thanks def filetransfer(self): s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REU...
pygtk progressbar is not working
when my program receiving new file file is copied fine but progress bar is not moving... if possible please suggest me a better algo.. Thanks def filetransfer(self): s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('',30098)) ...
[ "I'm not sure why so many people answer in the comments...\nYou need to call \"Update()\" inside of a loop, as in the question posted in the comment above.\nProgress bar not updating during operation \nHowever, if this doesn't work, please update the question so I can help you further.\n" ]
[ 0 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0007418169_pygtk_python.txt
Q: Hashing non-ascii Python string I'm trying to extract some string from a file using python re, then MD5ing this string using something like: #MD5er.py salt = extract_salt(file_foo) print 'salt: %s' % salt from md5 import md5 print 'hash: %s' % md5(salt).hexdigest() $python MD5er salt: \000...
Hashing non-ascii Python string
I'm trying to extract some string from a file using python re, then MD5ing this string using something like: #MD5er.py salt = extract_salt(file_foo) print 'salt: %s' % salt from md5 import md5 print 'hash: %s' % md5(salt).hexdigest() $python MD5er salt: \0001\072\206\277\354\107\134\061\361\076...
[ "The string in the first case is exactly what you saw printed:\n>>> salt = '\\\\0001\\\\072\\\\206\\\\277\\\\354\\\\107\\\\134\\\\061\\\\361\\\\076\\\\150\\\\047\\\\010\\\\\n124\\\\200\\\\315\\\\100'\n>>> md5(salt).hexdigest()\n'ce24166858853dfb12a86d7d602b0638'\n\nNotice how I've escaped the backslashes to keep th...
[ 4 ]
[]
[]
[ "ascii", "hash", "md5", "python", "unicode" ]
stackoverflow_0007857099_ascii_hash_md5_python_unicode.txt
Q: run web app with gevent I want to try playing around with gevent as a web server and application framework. I don't see any way to "restart" the server or update the application code without killing and starting the whole python application again. Is this just how it's done? Maybe it's just a matter of me unders...
run web app with gevent
I want to try playing around with gevent as a web server and application framework. I don't see any way to "restart" the server or update the application code without killing and starting the whole python application again. Is this just how it's done? Maybe it's just a matter of me understanding a different paradigm ...
[ "Gunicorn has 3 gevent workers:\n\n-k gevent (using gunicorn's HTTP parser)\n-k gevent_pywsgi (using gevent.pywsgi module)\n-k gevent_wsgi (using gevent.wsgi module)\n\ngevent.wsgi is a fast HTTP server based on libevent.\ngevent.pywsgi is WSGI server implemented in Python.\nThe reason for existence of geve...
[ 27 ]
[]
[]
[ "gevent", "gunicorn", "python" ]
stackoverflow_0007855343_gevent_gunicorn_python.txt
Q: Recursive Function palindrome in Python I need help writing a recursive function which detects whether a string is a palindrome. But i can't use any loops it must be recursive. Can anyone help show me how this is done . Im using Python. A: def ispalindrome(word): if len(word) < 2: return True if word[0] ...
Recursive Function palindrome in Python
I need help writing a recursive function which detects whether a string is a palindrome. But i can't use any loops it must be recursive. Can anyone help show me how this is done . Im using Python.
[ "def ispalindrome(word):\n if len(word) < 2: return True\n if word[0] != word[-1]: return False\n return ispalindrome(word[1:-1])\n\nAnd here is the best one liner\ndef ispalindrome(word):\n return word == word[::-1]\n\n", "From a general algorithm perspective, the recursive function has 3 cases:\n1) ...
[ 68, 47, 3, 3, 2, 2, 1, 0, 0 ]
[ "n=raw_input(\"Enter a number===>\")\nn=str(n)\nl=len(n)\ns=\"\"\nfor i in range(1,l+1):\n s=s+n[l-i]\nif s==n:\n print \"Given number is polindrom\"\nelse:\n print \"Given number is not polindrom\"\n\n", "Here is C version, if anyone happens to land here searching for C code!\nint IsPalindrome_Recursive...
[ -1, -1 ]
[ "palindrome", "python", "recursion" ]
stackoverflow_0000952110_palindrome_python_recursion.txt
Q: As an alternative to Objective-C, which language works better? I would like to know which one of these languages brings better functionalities on a mac for programming mac os x? A: You want this. http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/RubyPythonCocoa/Introduction/Introduction.html...
As an alternative to Objective-C, which language works better?
I would like to know which one of these languages brings better functionalities on a mac for programming mac os x?
[ "You want this.\nhttp://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/RubyPythonCocoa/Introduction/Introduction.html#//apple_ref/doc/uid/TP40004936\nThey both have the same level of integration. You simply get your language of choice's benefits.\n" ]
[ 0 ]
[]
[]
[ "cocoa", "objective_c", "python" ]
stackoverflow_0007857375_cocoa_objective_c_python.txt
Q: python zipfile module with TextIOWrapper I wrote the following piece of code to read a text file inside of a zipped directory. Since I don't want the output in bytes I added the TextIOWrapper to display the output as a string. Assuming that this is the right way to read a zip file line by line (if it isn't let m...
python zipfile module with TextIOWrapper
I wrote the following piece of code to read a text file inside of a zipped directory. Since I don't want the output in bytes I added the TextIOWrapper to display the output as a string. Assuming that this is the right way to read a zip file line by line (if it isn't let me know), then why does the output print a blan...
[ "zipfile.open opens the zipped file in binary mode, which doesn't strip out carriage returns (i.e. '\\r'), and neither did the defaults for TextIOWrapper in my test. Try configuring TextIOWrapper to use universal newlines (i.e. newline=None):\nimport zipfile\nimport io\n\nzf = zipfile.ZipFile('data/test_zip.zip')\n...
[ 5 ]
[]
[]
[ "python", "readline", "string", "types", "zip" ]
stackoverflow_0007857225_python_readline_string_types_zip.txt
Q: How to Store Rows from CSV File into Python and Print Data with HTML Basically my problem is this: I have a CSV excel file with info on Southpark characters and I and I have an HTML template and what I have to do is take the data by rows (stored in lists) for each character and using the HTML template given implem...
How to Store Rows from CSV File into Python and Print Data with HTML
Basically my problem is this: I have a CSV excel file with info on Southpark characters and I and I have an HTML template and what I have to do is take the data by rows (stored in lists) for each character and using the HTML template given implement that data to create 5 seperate HTML pages with the characters last nam...
[ "First and foremost, have a look at the CSV docs.\nOnce you understand the basics take a look at this code. This should get you started on the right path:\nimport csv\n\noriginal = file('southpark.csv', 'rU')\nreader = csv.reader(original)\n\nfor row in reader:\n #will print each row by itself (all columns from ...
[ 6 ]
[]
[]
[ "csv", "excel", "html", "python" ]
stackoverflow_0007857337_csv_excel_html_python.txt
Q: More pythonic regex parse Is there a more pythonic way than doing: parsedStr=origStr[compiledRegex.match(origStr).start():compiledRegex.match(origStr).end()) For exampile assume my original string is "The cat said hi" and my compiled regex is "The.*said" I would pull the text "The cat said" The above code looks ...
More pythonic regex parse
Is there a more pythonic way than doing: parsedStr=origStr[compiledRegex.match(origStr).start():compiledRegex.match(origStr).end()) For exampile assume my original string is "The cat said hi" and my compiled regex is "The.*said" I would pull the text "The cat said" The above code looks ugly but that's how i've been d...
[ "Use the group method on the match object:\n>>> import re\n>>> origStr = \"The cat said hi\"\n>>> compiledRegex = re.compile('The.*said')\n>>> compiledRegex.match(origStr).group()\n'The cat said'\n\n", "Does this work for you?\ninstancesFound = compiledRegex.findall(origStr)\nif instancesFound:\n parsedStr = p...
[ 1, 0, 0 ]
[]
[]
[ "match", "parsing", "python", "regex", "string" ]
stackoverflow_0007856853_match_parsing_python_regex_string.txt
Q: Is this a "pythonic" method of executing functions as a python switch statement for tuple values? I have a situation where I have six possible situations which can relate to four different results. Instead of using an extended if/else statement, I was wondering if it would be more pythonic to use a dictionary to c...
Is this a "pythonic" method of executing functions as a python switch statement for tuple values?
I have a situation where I have six possible situations which can relate to four different results. Instead of using an extended if/else statement, I was wondering if it would be more pythonic to use a dictionary to call the functions that I would call inside the if/else as a replacement for a "switch" statement, like ...
[ "Consider this idiom instead:\n>>> def run():\n... print 'run'\n... \n>>> def walk():\n... print 'walk'\n... \n>>> def talk():\n... print 'talk'\n>>> switch={'run':run,'walk':walk,'talk':talk}\n>>> switch['run']()\nrun\n\nI think it is a little more readable than the direction you are heading. \nedit\nAnd th...
[ 17, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007857837_python.txt
Q: RFID + Android --> where do I start? I've heard that the Google Nexus S has RFID capabilities. I'd like to start learning about RFID and programmatically doing things. Where should I start? Good tutorials or code examples are what I'm after. (or hardware if it's not Android I suppose). Doesn't have to be Android, ...
RFID + Android --> where do I start?
I've heard that the Google Nexus S has RFID capabilities. I'd like to start learning about RFID and programmatically doing things. Where should I start? Good tutorials or code examples are what I'm after. (or hardware if it's not Android I suppose). Doesn't have to be Android, could be python or java libraries as well....
[ "Buy a Nexus-S, buy some tags.\nThen take a look at the code of the 'Tags' application that comes with android. Play with it, modify it. Write some tags with your own application. \nLearn what Ndef is and how you craft your own messages/records. Learn how to use the transceive function to do direct communication to...
[ 1 ]
[]
[]
[ "android", "java", "python", "rfid" ]
stackoverflow_0007857940_android_java_python_rfid.txt
Q: Connecting to Google app engine using Python on the client side The server as well as the client side program are to be written in Python. Can someone tell me how to use Python on the client side to communicate with the Google App Server written in Python? Google app engine already provides a Channel API but that ...
Connecting to Google app engine using Python on the client side
The server as well as the client side program are to be written in Python. Can someone tell me how to use Python on the client side to communicate with the Google App Server written in Python? Google app engine already provides a Channel API but that is on the server side and it requires JavaScript on the client side. ...
[ "Have you considered a building a restful api on the backend? Maybe django-piston could help there (not sure if it runs on GAE out of the box).\nThere is also Python library of the Google Channel API Client side, apparently somebody reverse-engineered the protocol: https://bitbucket.org/lohre/gae_channel/overview/\...
[ 4 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007858008_google_app_engine_python.txt
Q: Dispatching URLs through Flask without a TCP port I want to build a hybrid application (Web technologies embedded in a desktop app). I will start with a Web version and the embed it using WebKit, but I don't want the embedded version to service requests through a TCP port. With WebKit (Qt,Gtk) I can intercept al...
Dispatching URLs through Flask without a TCP port
I want to build a hybrid application (Web technologies embedded in a desktop app). I will start with a Web version and the embed it using WebKit, but I don't want the embedded version to service requests through a TCP port. With WebKit (Qt,Gtk) I can intercept all URL requests and act on them. What I'm missing is a ...
[ "Simon Sapin answered on the (quite active) Flask mailing list:\n\nWhy not WSGI ?\nYou have to get a Python interpreter somewhere. Then you need to call\n your application somehow with data from WebKit like the URL being\n requested, and get the response. WSGI is just that: a calling\n convention for Python func...
[ 2 ]
[]
[]
[ "flask", "hybrid", "python", "webkit" ]
stackoverflow_0007758988_flask_hybrid_python_webkit.txt
Q: Saving data to a column without deleting others in a Django script I have a model in the form of: class Data(models.Model): some_id = models.IntegerField(primary_key=True) data1 = models.IntegerField() data2 = models.IntegerField() data3 = models.CharField(max_length=150) I'm reading in data from ...
Saving data to a column without deleting others in a Django script
I have a model in the form of: class Data(models.Model): some_id = models.IntegerField(primary_key=True) data1 = models.IntegerField() data2 = models.IntegerField() data3 = models.CharField(max_length=150) I'm reading in data from various files, and using header information to identify where the column...
[ "You are confusing an attribute lookup with getattr. You can't resolve strings to attributes by typing data.single_arg - how would python know whether to use the variable value or the attribute name?\nsingle_arg = 'data2'\ndata.single_arg = 100\n\n# you can NOT set an attribute by a string this way. \n# You're just...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007853070_django_python.txt
Q: Ruby vs Python: Which is better suited for scripting utilities on Windows? And why? I need to write a bunch of scripts to grab diagnostic data from customer environments where our product is installed. Troubleshooting data I need comes various sources including Oracle database, PowerShell commands, WMI, Registry,...
Ruby vs Python: Which is better suited for scripting utilities on Windows? And why?
I need to write a bunch of scripts to grab diagnostic data from customer environments where our product is installed. Troubleshooting data I need comes various sources including Oracle database, PowerShell commands, WMI, Registry, Windows commands such as netstat, our own property files, log files etc. The results wi...
[ "I started with python and ruby both few months ago. Ruby has loads and loads of issues and I find python really cool. Dint try with scripting. I am working on web apps.\nUsed python script to to interact with database and inserting raw fields. Works really fine.\n", "Ruby's type system is much simpler and cleane...
[ 1, 0 ]
[]
[]
[ "python", "ruby", "scripting" ]
stackoverflow_0007858436_python_ruby_scripting.txt
Q: Is there a way to define the [ ] operator for an instance of class? I want to define class to represent a matrix class matrix: def __init__(self, mat): self.mat = mat self.dim = len(mat) @classmethod def withDim(matrix, dimension): mat = [ [0]*dimension for i in range(dimensio...
Is there a way to define the [ ] operator for an instance of class?
I want to define class to represent a matrix class matrix: def __init__(self, mat): self.mat = mat self.dim = len(mat) @classmethod def withDim(matrix, dimension): mat = [ [0]*dimension for i in range(dimension)] return matrix(mat) where mat is a list of lists, so to repre...
[ "operator[] calls __getitem__:\nclass A:\n def __getitem__(self, index):\n return index+1\n\na = A()\nprint(a[1]) # prints 2\n\nYou can implement [][] by returning a proxy object which represents the row and also responds to __getitem__. Or, you can accept tuple as index and use A[i,j] syntax.\n" ]
[ 7 ]
[]
[]
[ "object", "operators", "python" ]
stackoverflow_0007858516_object_operators_python.txt
Q: buildout seems don't correctly execute setup.py buildout.cfg [buildout] parts = icom develop = . unzip = true include-site-packages = false eggs = sqlalchemy flask scss [icom] recipe = zc.recipe.egg eggs = ${buildout:eggs} interpreter = python scripts = create_db scss t...
buildout seems don't correctly execute setup.py
buildout.cfg [buildout] parts = icom develop = . unzip = true include-site-packages = false eggs = sqlalchemy flask scss [icom] recipe = zc.recipe.egg eggs = ${buildout:eggs} interpreter = python scripts = create_db scss there is a create_db in scripts. setup.py from setupto...
[ "Make sure you include icom in your eggs list. Either add it to the [buildout] section:\n[buildout]\n...\neggs =\n icom\n sqlalchemy\n flask\n scss\n\nor to the [icom] section:\n[icom]\nrecipe = zc.recipe.egg\neggs =\n icom\n ${buildout:eggs}\n...\n\n" ]
[ 3 ]
[]
[]
[ "buildout", "python" ]
stackoverflow_0007857904_buildout_python.txt
Q: In Python, how do I automate the control of a UI in a program that uses WPF? I've been working on this Python program to try to do some automated testing. The problem is that up until recently, I've been able to use pywinauto just fine. Now, I have to control some programs that have their UI made with Windows Pres...
In Python, how do I automate the control of a UI in a program that uses WPF?
I've been working on this Python program to try to do some automated testing. The problem is that up until recently, I've been able to use pywinauto just fine. Now, I have to control some programs that have their UI made with Windows Presentation Foundation (WPF). So far, I have been using the standard Python interpret...
[ "I assume you are trying to send Window Messages to the controls, or simulate key strokes.\nHave a look at this question: \nExperiences with UI Automation and WPF\n" ]
[ 0 ]
[]
[]
[ "ironpython", "python", "ui_automation", "windows", "wpf" ]
stackoverflow_0007853842_ironpython_python_ui_automation_windows_wpf.txt
Q: Setup Qt4 and PyQt for Python 2.6 under MacOS I downloaded Qt4 from http://qt.nokia.com/downloads/ and installed it. Using MacPorts I tried to install PyQt as a binding for Python 2.6.1 (which is installed by default in MacOS X Snow Leopard) using both these two lines: sudo port install py-pyqt4 sudo port install ...
Setup Qt4 and PyQt for Python 2.6 under MacOS
I downloaded Qt4 from http://qt.nokia.com/downloads/ and installed it. Using MacPorts I tried to install PyQt as a binding for Python 2.6.1 (which is installed by default in MacOS X Snow Leopard) using both these two lines: sudo port install py-pyqt4 sudo port install py26-pyqt4 Obviously that didnt work. If I try imp...
[ "I found the solution myself: PyQt4 was installed correctly and so was Qt4. However, PyQt was installed in the MacPort's installation of python, not in the system's python-installation. To change the installation that will start when executing \"python\" I selected python26 using macports:\nsudo port select python ...
[ 2 ]
[]
[]
[ "osx_snow_leopard", "pyqt4", "python" ]
stackoverflow_0007851049_osx_snow_leopard_pyqt4_python.txt
Q: save an image field from django template to a table I have a form in my template like this : <form action="." method="GET" style="font-family: Tahoma; font-size: 12px"> <table style="width: 100%;"> <tr> <td> name: </td> ...
save an image field from django template to a table
I have a form in my template like this : <form action="." method="GET" style="font-family: Tahoma; font-size: 12px"> <table style="width: 100%;"> <tr> <td> name: </td> <td> <input id="name" name="name"...
[ "Are you having a specific problem with the way django explains how to do this? https://docs.djangoproject.com/en/dev/topics/http/file-uploads/ \nFirst of all, you need to assign enctype=\"multipart/form-data\" inside the <form> tag.\nIf you must do this manually instead of leveraging the power of Django's forms fr...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007858856_django_python.txt
Q: python pty module - buffer hangs? I am trying to make a small module which opens an ssh connection and allows to send commands over ssh and return the output of the command. Hereby, there should only be one ssh connection (so that multiple commands do not cause auto-blocks). I am aware of paramiko, but I cannot us...
python pty module - buffer hangs?
I am trying to make a small module which opens an ssh connection and allows to send commands over ssh and return the output of the command. Hereby, there should only be one ssh connection (so that multiple commands do not cause auto-blocks). I am aware of paramiko, but I cannot use it as I have to use python3.2 because...
[ "Solved, or at least worked around it:\nBy using a thread with the ssh -M option, I could have one Master ssh connection open and have commands open their own ssh subprocess, which connects through the master connection, thereby alleviating the need to open more than one connection.\n", "Try pexpect. I ran into a...
[ 1, 0 ]
[]
[]
[ "buffer", "pty", "python", "ssh", "subprocess" ]
stackoverflow_0007752054_buffer_pty_python_ssh_subprocess.txt
Q: Set label in popup menu - no hovering Can I set a label (text) in popup menu (gtk.Menu) but without hovering effect, for example: LABEL MenuItem1 (hover effect) MenuItem2 (hover effect) MenuItem3 (hover effect) EDIT: This is not popup menu example but it show hover effect. For hovering effect I mean when I click...
Set label in popup menu - no hovering
Can I set a label (text) in popup menu (gtk.Menu) but without hovering effect, for example: LABEL MenuItem1 (hover effect) MenuItem2 (hover effect) MenuItem3 (hover effect) EDIT: This is not popup menu example but it show hover effect. For hovering effect I mean when I click left button mouse it will open the popup m...
[ "You can use Widget.set_sensitive(False) to disable the menu item. This way, no hover effect is generated, but the menu item won't be clickable also.\n" ]
[ 0 ]
[]
[]
[ "menu", "pygtk", "python" ]
stackoverflow_0007799765_menu_pygtk_python.txt
Q: different field then expected being put out in html When I try to put out comment in my html, author's email instead of comment is being put out somehow: asdas(Oct. 22, 2011, 2:38 p.m.) marijus.merkevicius@gmail.com Here's my models : class Comment(models.Model): name = models.CharField(max_length=10...
different field then expected being put out in html
When I try to put out comment in my html, author's email instead of comment is being put out somehow: asdas(Oct. 22, 2011, 2:38 p.m.) marijus.merkevicius@gmail.com Here's my models : class Comment(models.Model): name = models.CharField(max_length=100) email = models.EmailField() pub_date = models....
[ "That's because you store the email address in the comment field:\ncomment = cd[\"email\"],\n\n" ]
[ 1 ]
[]
[]
[ "django", "html", "python" ]
stackoverflow_0007859299_django_html_python.txt
Q: Extending the Charme Interpreter by Defining Null and Null? I need to help extending the Charme interpreter and defining the null and null? primitives that behave similarly to the primitive Scheme procedures. I know I can use Python's None value to represent null. A: This seems to be a homework question: http://...
Extending the Charme Interpreter by Defining Null and Null?
I need to help extending the Charme interpreter and defining the null and null? primitives that behave similarly to the primitive Scheme procedures. I know I can use Python's None value to represent null.
[ "This seems to be a homework question:\nhttp://www.cs.virginia.edu/~evans/cs1120-f09/ps/ps7/\nA few pointers:\n\nHow is the empty list (aka null) represented as a Python value?\nWhich function is used to extend the environment?\n\n" ]
[ 0 ]
[]
[]
[ "interpreter", "python", "scheme" ]
stackoverflow_0005505519_interpreter_python_scheme.txt
Q: installing pythonsetup tools to a specific python directory I have to work on grid for which I need to install some python packages. I was trying to install pythonsetup tools, though the grid has python installed when i run python setup.py install it gives my Permission denied: '/usr/local/lib/python2.7/site-packa...
installing pythonsetup tools to a specific python directory
I have to work on grid for which I need to install some python packages. I was trying to install pythonsetup tools, though the grid has python installed when i run python setup.py install it gives my Permission denied: '/usr/local/lib/python2.7/site-packages/test-easy-install-22642.write-test'. Hence I went and instal...
[ "To have local Python deployments (with site-packages) you can create isolated Python environments with a tool called virtualenv:\nhttp://pypi.python.org/pypi/virtualenv\nIt answers your both questions\n\nOverrides default Python interpreter (after activation)\nCan have site-packages in any folder (no root access n...
[ 1 ]
[]
[]
[ "environment_variables", "installation", "python", "setuptools" ]
stackoverflow_0007856641_environment_variables_installation_python_setuptools.txt
Q: qt pyside - qsql*model, qabstractitemmodel and qtreeview interaction I want to produce a simple enough application which uses a QTreeView widget to show hierarchical data from a SQLite3 (flat) table, use QDataWidgetMapper to populate some lineedit fields, allow user to edit, which in turn updates the table. Simpl...
qt pyside - qsql*model, qabstractitemmodel and qtreeview interaction
I want to produce a simple enough application which uses a QTreeView widget to show hierarchical data from a SQLite3 (flat) table, use QDataWidgetMapper to populate some lineedit fields, allow user to edit, which in turn updates the table. Simple & basic (for most!). I have been working on the basis that the following...
[ "What you want is a proxy model that acts as a bridge between QSql*Model and the view. For that, you need to subclass QAbstractProxyModel. You have to have a consistent way of finding parent-child relationships in proxy model and mapping them to the source model, so that might require keeping some tally in the prox...
[ 2 ]
[]
[]
[ "model_view_controller", "pyside", "python", "qt", "sqlite" ]
stackoverflow_0007858653_model_view_controller_pyside_python_qt_sqlite.txt
Q: Does not raise the exception My code is like below: def getAllVehicles(self): try: vehobj = Vehicles.objects.all() except VehicleDoesNotExists, e: logger.debug("Exception in getAllVehicles() is :::: %s ", e) return vehobj And here is my test case: def test_getAllVehicles(se...
Does not raise the exception
My code is like below: def getAllVehicles(self): try: vehobj = Vehicles.objects.all() except VehicleDoesNotExists, e: logger.debug("Exception in getAllVehicles() is :::: %s ", e) return vehobj And here is my test case: def test_getAllVehicles(self): Vehicles.objects.all().de...
[ "Vehicles.objects.all() will give you an empty list... which is the correct behavior. If you want to raise an exception, you can test for an empty list and raise VehicleDoesNotExists(...) yourself... but I don't understand why you'd want to.\n" ]
[ 6 ]
[]
[]
[ "django", "exception", "python" ]
stackoverflow_0007860171_django_exception_python.txt
Q: Python26, re.match returns only the last match The following is the content of my source file: Number= 010010 Name= Jan Mayen Country= NORWAY Lat= 70.9 Long= 8.7 ... It seems like there is a major mistake in my expression or a misunderstanding of re.match() because I need to get all properties (and not just ...
Python26, re.match returns only the last match
The following is the content of my source file: Number= 010010 Name= Jan Mayen Country= NORWAY Lat= 70.9 Long= 8.7 ... It seems like there is a major mistake in my expression or a misunderstanding of re.match() because I need to get all properties (and not just the last one). >>> pattern = re.compile(r'^(([^\n]+)...
[ "The problem is that you're repeating your capturing group:\npattern = re.compile(r'^(...)+')\n\nThis means that with every match, the previous match is overwritten. This is expected behaviour in all regex engines; only few (like .NET) allow later access to the individual captures of a repeated group.\nSo you do in...
[ 6, 3, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007860209_python_regex.txt
Q: MySQL Python Insert strange? I dont see why it's not working. I have created several databases and tables and obviously no problem. But I am stuck with this table which is created from django data model. To clarify what I have done, created new database and table from mysql console and try to insert from python an...
MySQL Python Insert strange?
I dont see why it's not working. I have created several databases and tables and obviously no problem. But I am stuck with this table which is created from django data model. To clarify what I have done, created new database and table from mysql console and try to insert from python and working. But, this one is strang...
[ "sql = \"\"\"INSERT INTO pmass_experiment (user,filetype,createddate,uploaddate,time,size,located)\n VALUES (user, ftype, date, date, time, size, located)\"\"\"\n\nParametrize your sql and pass in the values as the second argument to cursor.execute:\nsql = \"\"\"INSERT INTO pmass_experiment (user,filetype,create...
[ 1 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0007860326_django_mysql_python.txt
Q: FTP corrupted ZIP When I use this code to download a zip file from and FTP server it comes back corrupted. Anyone know why? from ftplib import FTP import getpass user = raw_input('Username: ') password = getpass.getpass() host = raw_input('Host:') ftp = FTP(host,user,password) ftp.retrlines('LIST') f_file = raw_i...
FTP corrupted ZIP
When I use this code to download a zip file from and FTP server it comes back corrupted. Anyone know why? from ftplib import FTP import getpass user = raw_input('Username: ') password = getpass.getpass() host = raw_input('Host:') ftp = FTP(host,user,password) ftp.retrlines('LIST') f_file = raw_input('What is the name ...
[ "This is probably because you're writing the local copy in ASCII mode, not binary mode, thereby changing all 0A bytes into 0D0A (LF to CRLF), corrupting the binary file.\nTry again using l_file = open(f_file, 'wb').\n" ]
[ 3 ]
[]
[]
[ "ftplib", "python", "zip" ]
stackoverflow_0007860364_ftplib_python_zip.txt
Q: python printing a blank line on the first line when writing to a file I'm stuck on why my code is printing a blank line before writing text to a file. What I am doing is reading two files from a zipped folder and writing the text to a new text file. I am getting the expected results in the file, except for the f...
python printing a blank line on the first line when writing to a file
I'm stuck on why my code is printing a blank line before writing text to a file. What I am doing is reading two files from a zipped folder and writing the text to a new text file. I am getting the expected results in the file, except for the fact that there is a blank line on the first line of the file. def test(): ...
[ "My guess is that the first file in zf.namelist() doesn't contain anything, so you skip the for line in words loop for that file and just do new_file.write('\\n'). It's difficult to tell without seeing the files that you're looping over; perhaps add some debug statements that print out the files' names and some inf...
[ 4 ]
[]
[]
[ "file", "newline", "python" ]
stackoverflow_0007860534_file_newline_python.txt
Q: Extract first paragraph using regex I'm trying to extract first paragraph. But I have found any luck. Can any one help me? here is text. http://dpaste.com/638776/. My text is dynamic. thanks UPDATE: I'm reading XML file using eTree module. In XML there is tag called <text></text>. The data between <text></text> is...
Extract first paragraph using regex
I'm trying to extract first paragraph. But I have found any luck. Can any one help me? here is text. http://dpaste.com/638776/. My text is dynamic. thanks UPDATE: I'm reading XML file using eTree module. In XML there is tag called <text></text>. The data between <text></text> is here. I just want print following data f...
[ "If you build a regex where the dot matches the newline, you have (tested in ruby but I guess that it will work in python as is). It is quite the same as the answer by Niall Byrne:\n}}\\n(.*?)\\n\\n\n\nPlease see the effect at rubular.\n", "Revised based on new info ...\nIf you able to produce the text between th...
[ 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007859816_python_regex.txt
Q: implement a unix pipe with python cmd module? I'm implement a simple shell using python's cmd module. Now, I'd like to implement a unix pipe in this shell, that is when I type: ls | grep "a" it will pass the result of do_ls to the input of do_grep, what's the simplest way to do this? Sorry CryptoJones, I forgo...
implement a unix pipe with python cmd module?
I'm implement a simple shell using python's cmd module. Now, I'd like to implement a unix pipe in this shell, that is when I type: ls | grep "a" it will pass the result of do_ls to the input of do_grep, what's the simplest way to do this? Sorry CryptoJones, I forgot to say that my platform is Windows.
[ "The simplest way is probably to store the output of your do_ls in a buffer and feed it to do_grep. You probably want to do it line by line or by groups of lines, rather than in a single go, especially if you want to implement a more command.\nA more complete approach would be to run all of your commands in sub-pro...
[ 2, 2, 2, 1 ]
[]
[]
[ "cmd", "pipe", "python", "shell", "windows" ]
stackoverflow_0007859696_cmd_pipe_python_shell_windows.txt
Q: IOError: [Errno 2] No such file or directory: import os try: os.path.exists("E:/Contact") #Check if dir exist except: os.mkdir("E:/Contact") #if not, create def add(name,cell,email): #add contact conPath0 = 'E:/Contact' conPath1 = '/ ' conPath1b = conPath1.strip() conPath2 = name+...
IOError: [Errno 2] No such file or directory:
import os try: os.path.exists("E:/Contact") #Check if dir exist except: os.mkdir("E:/Contact") #if not, create def add(name,cell,email): #add contact conPath0 = 'E:/Contact' conPath1 = '/ ' conPath1b = conPath1.strip() conPath2 = name+'.txt' conPath = conPath0+conPath1b+conPath2 ...
[ "If the path does not exist, the os.path.exists call returns False rather than throwing an exception. So the first part of the code do not work as intended. Use this instead\nif not os.path.exists(\"E:/Contact\"):\n os.mkdir(\"E:/Contact\") \n\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0007860866_python.txt
Q: Parse and interact with obfuscated javascript I'm trying to interact with a HTML 4.0 website which uses heavily obfuscated javascript to hide the regular HTML elements. What I want to do is to fill out a form and read the returned results, and this is proving harder to do than expected. When I read the page using ...
Parse and interact with obfuscated javascript
I'm trying to interact with a HTML 4.0 website which uses heavily obfuscated javascript to hide the regular HTML elements. What I want to do is to fill out a form and read the returned results, and this is proving harder to do than expected. When I read the page using Firebug, it gave me the source code deobfuscated, a...
[ "Rather than trying to process the page, how about just use Firebug to figure out the names of the form fields, and then use httplib or whatever to send a request with the necessary fields and settings?\nIf it's sent using ajax, you should be able to determine the values being sent to the server in Firebug as well....
[ 1 ]
[]
[]
[ "deobfuscation", "mechanize", "python", "screen_scraping", "web_scraping" ]
stackoverflow_0007858552_deobfuscation_mechanize_python_screen_scraping_web_scraping.txt
Q: Python and Android This link says that it is indeed possible to write code in Python and use it for app development in android platform. I would like to know what the catch is when using Python and not Java. Is there any compromise being made in speed of execution or size? A: From the link you posted: Scripts ...
Python and Android
This link says that it is indeed possible to write code in Python and use it for app development in android platform. I would like to know what the catch is when using Python and not Java. Is there any compromise being made in speed of execution or size?
[ "From the link you posted:\n\nScripts can be run interactively in a terminal, in the background, or via Locale.\n\nThis already is a disadvantage, as you can't release your Apps to Android Market easily. This can however ostensibly be avoided by the build script of Pygame Subset for Android, but I am not sure about...
[ 2 ]
[]
[]
[ "android", "python" ]
stackoverflow_0007860772_android_python.txt
Q: PyGtk thread not running until main quits I've been trying to sort this problem for hours now, scouring the web and reading the documentation hasn't helped. I'm trying to perform a long running task in a separate thread and display the progress in a progress bar in the UI. The new thread is started but is not give...
PyGtk thread not running until main quits
I've been trying to sort this problem for hours now, scouring the web and reading the documentation hasn't helped. I'm trying to perform a long running task in a separate thread and display the progress in a progress bar in the UI. The new thread is started but is not given any time until the main loop quits, I have ca...
[ "And having spent hours trying to find an answer before posting a question I find the solution minutes after posting. Turns out (from here) that for GTK3 you need to call GLib.threads_init(), the code works with an initial from gi.repository import GLib and a GLib.threads_init() before the call to Gtk.main(), so a ...
[ 4 ]
[]
[]
[ "gtk", "python" ]
stackoverflow_0007850134_gtk_python.txt
Q: JPype doesn't work inside thread? I tested out a simple hello world line to test out JPype: jpype.java.lang.System.out.println("hello world") It works great inside the context of a "main" python program. However, inside the context of a running thread, I get the following response: # # A fatal error has been dete...
JPype doesn't work inside thread?
I tested out a simple hello world line to test out JPype: jpype.java.lang.System.out.println("hello world") It works great inside the context of a "main" python program. However, inside the context of a running thread, I get the following response: # # A fatal error has been detected by the Java Runtime Environment: #...
[ "citing from the JPype documentation:\n\nPython Threads\nFor the most part, python threads based on OS level threads (i.e posix threads), will work without problem. The only thing to remember is to call jpype.attachThreadToJVM() in the thread body to make the JVM usable from that thread. For threads that you do not...
[ 9 ]
[]
[]
[ "java", "porting", "python" ]
stackoverflow_0007861299_java_porting_python.txt
Q: Celery-Django: Unable to execute tasks asynchronously I'm trying to run some tasks in the background while users browse my site, but whenever I call a function using Celery it seems to be executed synchronously instead of asynchronously. e.g., when I call function.delay() the entire site hangs until function.dela...
Celery-Django: Unable to execute tasks asynchronously
I'm trying to run some tasks in the background while users browse my site, but whenever I call a function using Celery it seems to be executed synchronously instead of asynchronously. e.g., when I call function.delay() the entire site hangs until function.delay() returns. Other methods of calling functions in a simila...
[ "Try removing\nCELERY_ALWAYS_EAGER = True\n\nYou are explicitly asking celery to execute tasks synchronously. It'll always wait for the result.\nThis setting is useful for writing unit tests etc.\nRead http://ask.github.com/celery/configuration.html\n" ]
[ 8 ]
[]
[]
[ "celery", "django", "python" ]
stackoverflow_0007505846_celery_django_python.txt
Q: What is the most efficient way in Python to convert a string to all lowercase stripping out all non-ascii alpha characters? I have a simple task I need to perform in Python, which is to convert a string to all lowercase and strip out all non-ascii non-alpha characters. For example: "This is a Test" -> "thisisates...
What is the most efficient way in Python to convert a string to all lowercase stripping out all non-ascii alpha characters?
I have a simple task I need to perform in Python, which is to convert a string to all lowercase and strip out all non-ascii non-alpha characters. For example: "This is a Test" -> "thisisatest" "A235th@#$&( er Ra{}|?>ndom" -> "atherrandom" I have a simple function to do this: import string import sys def strip_string...
[ "Another solution (not that pythonic, but very fast) is to use string.translate - though note that this will not work for unicode. It's also worth noting that you can speed up Dana's code by moving the characters into a set (which looks up by hash, rather than performing a linear search each time). Here are the t...
[ 27, 17, 11, 8, 7, 4, 3, 2, 2, 1, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0000638893_python_string.txt
Q: Python regular expression to match either a quoted or unquoted string I am trying to write a regular expression in Python that will match either a quoted string with spaces or an unquoted string without spaces. For example given the string term:foo the result would be foo and given the string term:"foo bar" the re...
Python regular expression to match either a quoted or unquoted string
I am trying to write a regular expression in Python that will match either a quoted string with spaces or an unquoted string without spaces. For example given the string term:foo the result would be foo and given the string term:"foo bar" the result would be foo bar. So far I've come up with the following regular expre...
[ "Avoid grouping, and instead use lookahead/lookbehind assertions to eliminate the parts that are not needed:\ns = 'term:foo term:\"foo bar\" term:bar foo term:\"foo term:'\nre.findall(r'(?<=term:)[^\" ]+|(?<=term:\")[^\"]+(?=\")', s)\n\nGives:\n['foo', 'foo bar', 'bar']\n\n", "It doesn't seem that you really want...
[ 4, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007860644_python_regex.txt
Q: Is there a switch to ignore undefined namespace prefixes in LXML? I'm parsing a non-compliant XML file (Sphinx's xmlpipe2 format) and would like LXML parser to ignore the fact that there are unresolved namespace prefixes. An example of the Sphinx XML: <sphinx:schema> <sphinx:field name="subject"/> ...
Is there a switch to ignore undefined namespace prefixes in LXML?
I'm parsing a non-compliant XML file (Sphinx's xmlpipe2 format) and would like LXML parser to ignore the fact that there are unresolved namespace prefixes. An example of the Sphinx XML: <sphinx:schema> <sphinx:field name="subject"/> <sphinx:field name="content"/> <sphinx:attr name="published" typ...
[ "Add xmlns:sphinx=\"bogus\" to the root element.\n" ]
[ 3 ]
[]
[]
[ "lxml", "python", "xml" ]
stackoverflow_0003521140_lxml_python_xml.txt
Q: iPod/iPhone (jailbroken) GUI applications Python I am looking for a GUI example for iPod/iPhone (jailbroken) or some help to know where I can easily learn to make GUI applications for iPhones with Python. Thanks guys! A: Writing an iPhone application in any language besides Objective C, or to some extent, Lua (o...
iPod/iPhone (jailbroken) GUI applications Python
I am looking for a GUI example for iPod/iPhone (jailbroken) or some help to know where I can easily learn to make GUI applications for iPhones with Python. Thanks guys!
[ "Writing an iPhone application in any language besides Objective C, or to some extent, Lua (or HTML5) is not easy or recommended.\nSee also:\n\n\"currently the only languages available to access the iPhone SDK are C/C++ and Objective C\" (2008-09)\n\"It's now legal to include a Python interpreter in an iPhone app.\...
[ 0 ]
[]
[]
[ "ipod", "python", "user_interface" ]
stackoverflow_0007860440_ipod_python_user_interface.txt
Q: Regarding summation with a for loop I'm trying to get the user to input a birth date and then add the individual ints in those numbers. Also, if a sum of any of these digits is greater than or equal to 10, the loop repeats and the process runs again for the value. Here's my code so far if (sumYear >= 10): sumY...
Regarding summation with a for loop
I'm trying to get the user to input a birth date and then add the individual ints in those numbers. Also, if a sum of any of these digits is greater than or equal to 10, the loop repeats and the process runs again for the value. Here's my code so far if (sumYear >= 10): sumYear2=0 for num in str(sumYear): ...
[ "Too much work.\nsingledigitsum = (int(inputvalue) - 1) % 9 + 1\n\nNote that this will fail for numbers less than 1.\n", "@Ignacio Vazquez-Abrams's answer provides the formula. But if there were none then your code as a loop without using sumYear2 could look like:\nwhile sumYear >= 10:\n sumYear = sum(map(in...
[ 2, 1, 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0007861671_loops_python.txt
Q: Writing 4 arguments with the write function to a file I would like to write this to a file f.write("add unit at-wc 0 0 0 %s" % x ,y, z, "0.000 0.000 0.000 ") but when I do that I get an error saying function takes exactly 1 argument (4 given). A: You're using the % operator incorrectly. You might be looking for ...
Writing 4 arguments with the write function to a file
I would like to write this to a file f.write("add unit at-wc 0 0 0 %s" % x ,y, z, "0.000 0.000 0.000 ") but when I do that I get an error saying function takes exactly 1 argument (4 given).
[ "You're using the % operator incorrectly. You might be looking for something like this:\nf.write(\"add unit at-wc 0 0 0 %s %s %s 0.000 0.000 0.000 \" % (x, y, z))\n\nNotice that the substitution variables x, y, z are all in parentheses, which means they are a single tuple passed to the % operator.\nIn your code, no...
[ 6, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007861920_python.txt
Q: Keys or IDs on Google App Engine with Python Hiya, I asked a question earlier regarding using keys which was answered perfectly. However, now I'm wondering if creating and using keys for my Models is the way to go, I've been told by my iPhone App guy that we need INTs to store in the database. I got my Python code...
Keys or IDs on Google App Engine with Python
Hiya, I asked a question earlier regarding using keys which was answered perfectly. However, now I'm wondering if creating and using keys for my Models is the way to go, I've been told by my iPhone App guy that we need INTs to store in the database. I got my Python code working with Keys and now may have to back track....
[ "You probably want to avoid using just \"id\" for field names. It could be confused with the data key's id() when coding. http://code.google.com/appengine/docs/python/datastore/keyclass.html\nuser_id is good choice.\nYour \"iPhone guy\" wanting to use ints is very concerning. You really don't want to depend or use ...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004823256_google_app_engine_python.txt
Q: How to convert upper case letters to lower case I have a script which reads the input and than lists it, however i want it to convert upper case letters to lower case, how can i do that? this is what i got for words in text.readlines(): sentence = [w.strip(',.') for w in line.split() if w.strip(',.')] lis...
How to convert upper case letters to lower case
I have a script which reads the input and than lists it, however i want it to convert upper case letters to lower case, how can i do that? this is what i got for words in text.readlines(): sentence = [w.strip(',.') for w in line.split() if w.strip(',.')] list.append(sentence)
[ "You can find more methods and functions related to Python strings in section 5.6.1. String Methods of the documentation.\nw.strip(',.').lower()\n\n", "str.lower() converts all cased characters to lowercase.\n", "To convert a string to lower case in Python, use something like this.\nlist.append(sentence.lower()...
[ 133, 29, 5 ]
[]
[]
[ "python" ]
stackoverflow_0007862018_python.txt
Q: Include External Libraries in Packaged Python Application I have just picked up Python to develop a tool and I am so far really enjoying the language, however have one issue I am not entirely sure how to solve. I am looking to use a few external libraries in my project, at the moment cherryPy and Cheetah however I...
Include External Libraries in Packaged Python Application
I have just picked up Python to develop a tool and I am so far really enjoying the language, however have one issue I am not entirely sure how to solve. I am looking to use a few external libraries in my project, at the moment cherryPy and Cheetah however I am not sure how to package up my application so that these lib...
[ "I think what you're asking is how to create what Python calls a Built Distribution. This can be done with distutils and it is tedious. And again I'm guessing at the question, but I think you'd benefit from the docs about describing extension modules.\nBesides that, I don't think a broad answer would be complete ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0007856918_python.txt
Q: Python - Conditionally split line Python 2.4.x I have a series of lines that I'm reading in - rearranging and then making each line into a list which is nested inside another list. I've got the following. testposition = (22, 3, 1, 2, 18, 19, 5, 6, 8, 9, 12, 23, 24, 25, 26, 27, 28) def giveme(s, words=()): lis...
Python - Conditionally split line
Python 2.4.x I have a series of lines that I'm reading in - rearranging and then making each line into a list which is nested inside another list. I've got the following. testposition = (22, 3, 1, 2, 18, 19, 5, 6, 8, 9, 12, 23, 24, 25, 26, 27, 28) def giveme(s, words=()): lista = s.split() return [lista[item-1...
[ "If you supply the optional second argument to str.split, you can control how many splits are performed:\ntestposition = (22, 3, 1, 2, 18, 19, 5, 6, 8, 9, 12, 23)\n\ndef giveme(s, words=()):\n lista = s.split(' ',22)\n result=[lista[item-1] for item in words]\n return result\n\nrec='Lorem ipsum dolor sit a...
[ 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007862119_python.txt
Q: Easygui input error The following code gives me an error. import easygui result = easygui.enterbox(message="Enter your name", title="Name query", argDefaultText="Ian Ozsvald") This is the error. Traceback (most recent call last): File "/Volumes/CHROME USB/STORAGE/TKinker GUI/easygui inputbox.py", line 2, in...
Easygui input error
The following code gives me an error. import easygui result = easygui.enterbox(message="Enter your name", title="Name query", argDefaultText="Ian Ozsvald") This is the error. Traceback (most recent call last): File "/Volumes/CHROME USB/STORAGE/TKinker GUI/easygui inputbox.py", line 2, in result = easygui....
[ "easygui.enterbox has no argument message, nor argDefaultText.\nWhat you want is:\nimport easygui\nresult = easygui.enterbox(msg='Enter your name', title='Name query', default='Ian Ozsvald')\n\nThe signature of the enterbox function can be found here:\nhttp://easygui.sourceforge.net/download/version0.95/pydoc/easyg...
[ 2 ]
[]
[]
[ "easygui", "input", "python" ]
stackoverflow_0007862113_easygui_input_python.txt
Q: python: how to determine default program associated with a given type, under windows How do I find the program associated with a given file type using Python under Windows? For example, given http I'd like python to determine the default browser. I can do this from a cmd prompt by running 'ftype http'. Windows gi...
python: how to determine default program associated with a given type, under windows
How do I find the program associated with a given file type using Python under Windows? For example, given http I'd like python to determine the default browser. I can do this from a cmd prompt by running 'ftype http'. Windows gives me the full path to the browser. I've tried: subprocess.call(['http://www.google.com']...
[ "You're missing the '/c' option that configures cmd to run a command and then exit:\nsubprocess.check_output(['cmd', '/c', 'ftype http'])\n\n", "Try this:\nprint subprocess.check_output(['ftype', 'http'])\n\n" ]
[ 2, 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0007861774_python_windows.txt
Q: Commands in Python IRC bot built with oyoyo I have recently found the oyoyo Python IRC framework and as it looks decent from my newbie perspective, I have chosen to build an IRC bot with it (Twisted seems a bit daunting). I have looked at the example, but I am not sure how I would implement more commands. Would I ...
Commands in Python IRC bot built with oyoyo
I have recently found the oyoyo Python IRC framework and as it looks decent from my newbie perspective, I have chosen to build an IRC bot with it (Twisted seems a bit daunting). I have looked at the example, but I am not sure how I would implement more commands. Would I just have a lot of if statements in the privmsg f...
[ "IRC bot in twisted demonstrates how your bot can respond to several commands. \nYou define several command_*() methods and call them from privmsg() method. \ngetattr(self, 'command_'+command_name, None) retrieves appropriate method to call.\n" ]
[ 1 ]
[]
[]
[ "command", "frameworks", "irc", "python" ]
stackoverflow_0007861445_command_frameworks_irc_python.txt
Q: How can I force a window full screen in python (using easyGUI) I am just starting out using easyGUI with Python, and am running in to a bit of trouble. I want my application to run in full screen. However, I can not figure out how to get this to work. This could apply to any python/easyGUI code, such as something ...
How can I force a window full screen in python (using easyGUI)
I am just starting out using easyGUI with Python, and am running in to a bit of trouble. I want my application to run in full screen. However, I can not figure out how to get this to work. This could apply to any python/easyGUI code, such as something as simple as hello world: from easygui import * msgbox("Hello, world...
[ "I don't think this is possible using EasyGUI, as none of the methods even allow for width and height arguments; you're sacrificing extensibility for ease of use.\nThis can be done with Tkinter directly. Here's a nice example for Making a Toplevel cover the Full Screen.\n" ]
[ 2 ]
[]
[]
[ "easygui", "fullscreen", "python" ]
stackoverflow_0007858038_easygui_fullscreen_python.txt
Q: Converting string to digits in Python I have a string: x = "12.000" And I want it to convert it to digits. However, I have used int, float, and others but I only get 12.0 and i want to keep all the zeroes. Please help! I want x = 12.000 as a result. A: decimal.Decimal allows you to use a specific precision. >>>...
Converting string to digits in Python
I have a string: x = "12.000" And I want it to convert it to digits. However, I have used int, float, and others but I only get 12.0 and i want to keep all the zeroes. Please help! I want x = 12.000 as a result.
[ "decimal.Decimal allows you to use a specific precision.\n>>> decimal.Decimal('12.000')\nDecimal('12.000')\n\n", "If you really want to perform calculations that take precision into account, the easiest way is to probably to use the uncertainties module. Here is an example\n>>> import uncertainties\n>>> x = unce...
[ 6, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007861208_python.txt
Q: gtk.ListStore / gtk.TreeModel and dict type I've a dictionary (dict type) which I would store in a gtk.ListStore. Is there a way to do this ? (Which column type is good for that ?) or do I have to add as many columns in the gtk.ListStore as there are elements in the dictionary? Thanks A: You might want to look a...
gtk.ListStore / gtk.TreeModel and dict type
I've a dictionary (dict type) which I would store in a gtk.ListStore. Is there a way to do this ? (Which column type is good for that ?) or do I have to add as many columns in the gtk.ListStore as there are elements in the dictionary? Thanks
[ "You might want to look at the DictionaryGrid quickly widget. See here for it's usage.\nThe DictionaryGrid might exactly do what you need or you can copy parts of it.\n" ]
[ 2 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0007862275_gtk_pygtk_python.txt
Q: Unittesting web applications I am developing a very simple web application in python using the bottle microframework and I was wondering if there are frameworks that can rigorously aid in testing the application. A: This StackOverflow link might be of use: Practicing BDD with python Here's a link to the mentione...
Unittesting web applications
I am developing a very simple web application in python using the bottle microframework and I was wondering if there are frameworks that can rigorously aid in testing the application.
[ "This StackOverflow link might be of use:\nPracticing BDD with python\nHere's a link to the mentioned doctest.\n" ]
[ 1 ]
[]
[]
[ "python", "web" ]
stackoverflow_0007862549_python_web.txt
Q: Reading variables from text files I have a text file, xyz.txt that has variables, and I want to use those variables, I know how to read them but do not know how to use it and call them when I need it. For example, If in the text file there is x = 123 I would like to be able to call on that variable for use, so if ...
Reading variables from text files
I have a text file, xyz.txt that has variables, and I want to use those variables, I know how to read them but do not know how to use it and call them when I need it. For example, If in the text file there is x = 123 I would like to be able to call on that variable for use, so if i said print x it would give me 123. te...
[ "One solution might be using a dictionary:\nvars = dict()\n\nwith open(\"file.txt\") as f:\n for line in f:\n eq_index = line.find('=')\n var_name = line[:eq_index].strip()\n number = float(line[eq_index + 1:].strip())\n vars[var_name] = number\n\nprint(vars)\n\nAnd the file.txt:\na =...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007862587_python.txt
Q: Apple store receipt validation through Twisted server I'm trying to validate a transaction receipt from an inApp purchase with the Apple store server from my Twisted server. I have sent the (SKPaymentTransaction *)transaction.transactionReceipt from my app to my server. But now, sending the JSON object to the Appl...
Apple store receipt validation through Twisted server
I'm trying to validate a transaction receipt from an inApp purchase with the Apple store server from my Twisted server. I have sent the (SKPaymentTransaction *)transaction.transactionReceipt from my app to my server. But now, sending the JSON object to the Apple server, I keep getting an unhandled error in Deferred fro...
[ "The comment style in your code sample is incorrect. Python uses # for comments, not //.\nAfter fixing that and running the snippet through pyflakes, I see these errors:\nprogram.py:1: 'service' imported but unused\nprogram.py:6: 'defer' imported but unused\nprogram.py:21: undefined name 'succeed'\nprogram.py:48: ...
[ 1 ]
[]
[]
[ "https", "in_app_purchase", "iphone", "python", "twisted" ]
stackoverflow_0007857868_https_in_app_purchase_iphone_python_twisted.txt
Q: Tkinter (python 2.7.2) Help needed I'm trying to make my first GUI program. The problem is, that I can't figure out how to make a main menu, which would switch to one of the programs after clicking a button. #Dev by Mkee from Tkinter import * import tkMessageBox #Main Stuff app = Tk() app.title("Mkee's Tools") app...
Tkinter (python 2.7.2) Help needed
I'm trying to make my first GUI program. The problem is, that I can't figure out how to make a main menu, which would switch to one of the programs after clicking a button. #Dev by Mkee from Tkinter import * import tkMessageBox #Main Stuff app = Tk() app.title("Mkee's Tools") app.geometry('300x200') #modules class Pro...
[ "\nYou could call pack_forget() to hide widgets, and (later)\npack to show them again:\nTkinter is singled-threaded, and mainloop runs the main event loop. Therefore you shouldn't call mainloop twice.\n\n\n#Dev by Mkee\nimport Tkinter as tk\nimport sys\n\nclass Shuffle(object):\n def __init__(self,master=None):\...
[ 1 ]
[]
[]
[ "python", "python_2.7", "tkinter" ]
stackoverflow_0007862621_python_python_2.7_tkinter.txt
Q: Where in Python can I find real_fft() these days? It's not in numpy.fft I have some ancient code (5 years old) and how I used to access real_fft() method was this: from FFT import * real_fft(data, fft_length) I guess the FFT module came with NumPy. Now, years later I installed the NumPy 1.6.1 with pip install num...
Where in Python can I find real_fft() these days? It's not in numpy.fft
I have some ancient code (5 years old) and how I used to access real_fft() method was this: from FFT import * real_fft(data, fft_length) I guess the FFT module came with NumPy. Now, years later I installed the NumPy 1.6.1 with pip install numpy And all I see in the docs http://www.scipy.org/Numpy_Functions_by_Categor...
[ "It looks like NumPy underwent some reorganisation in recent years.\nhttp://www.scipy.org/Numpy_Example_List_With_Doc#fft\nFFT is now numpy.fft, and real_fft() seems to be renamed into rfft()\n>>> from numpy import *\n>>> \n>>> signal = array([-2., 8., -6., 4., 1., 0., 3., 5.]) \n>\n>>> from numpy.fft import *...
[ 4 ]
[]
[]
[ "fft", "numpy", "python" ]
stackoverflow_0007862899_fft_numpy_python.txt
Q: Clean up text after html2txt I am using lxml to convert html into txt. I almost get to where I wanted with parsing, converting and some parts of the cleanup (tabs, spaces, empty lines) functions ready and a program up and running. However, after I tried my code with about a hundred htmls (all from different sites)...
Clean up text after html2txt
I am using lxml to convert html into txt. I almost get to where I wanted with parsing, converting and some parts of the cleanup (tabs, spaces, empty lines) functions ready and a program up and running. However, after I tried my code with about a hundred htmls (all from different sites), I noticed some exceptions, i.e. ...
[ "That is indeed CSS. You're getting a document like this:\n<style>\n#wrapper #PrimaryNav {margin:0;*overflow:hidden;}\na.scbbtnred{background-position:right -44px;}\na.scbbtnblack{background-position:right -176px;}\n.ghsearch{width:58px;height:21px;line-height:21px;background-position:0 -80px;}\na.scbbtnred span sp...
[ 2 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0007863054_lxml_python.txt
Q: Get non-local host name from Google App Engine dev_appserver I'd like to get the hostname in Google App Engine when running dev_appserver.py, because GAE is making a request of an external server and that server needs to know where to send its response. Unfortunately, the canonical Python way doesn't seem to work,...
Get non-local host name from Google App Engine dev_appserver
I'd like to get the hostname in Google App Engine when running dev_appserver.py, because GAE is making a request of an external server and that server needs to know where to send its response. Unfortunately, the canonical Python way doesn't seem to work, being: import socket socket.gethostbyname(socket.gethostname()) ...
[ "the socket package might be disabled in the GAE sandbox. \nHave you tried using the request object to determine this?\nhttp://docs.webob.org/en/latest/reference.html#id1\nmight be the most reliable way.\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "python", "sockets" ]
stackoverflow_0007863128_google_app_engine_python_sockets.txt
Q: Python: simple iteration of lists in a dict I have this simple structure: o = { 2: [0, 148, 149, 150, 151], 3: [0, 152, 153, 154, 155, 156], 4: [0, 157, 158, 159, 160], 5: [0, 161, 162, 163, 164, 165, 166] } ...and I am going nuts trying to isolate each number in the lists (eg. 0, 148, 149) if I d...
Python: simple iteration of lists in a dict
I have this simple structure: o = { 2: [0, 148, 149, 150, 151], 3: [0, 152, 153, 154, 155, 156], 4: [0, 157, 158, 159, 160], 5: [0, 161, 162, 163, 164, 165, 166] } ...and I am going nuts trying to isolate each number in the lists (eg. 0, 148, 149) if I do any kind of loop I get: TypeError: 'int' object...
[ "Next time, please show the code that fails.\nI'm going to guess you do something like:\nfor x in o:\n for y in x:\n print y\n\nThe problem is that if you iterate over o, you get the keys not the values. What you want is:\n for key, value in o.items():\n for v in value:\n print v\n\nItems ...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007862656_python.txt
Q: Using Python in Windows, how do I send and retrieve an arbitrary amount of data over a socket connection? I am trying to follow an example from an online tutorial regarding basic client-server socket programming using standard Python libraries (version 2.7), but I cannot get the example to work under Windows (Vist...
Using Python in Windows, how do I send and retrieve an arbitrary amount of data over a socket connection?
I am trying to follow an example from an online tutorial regarding basic client-server socket programming using standard Python libraries (version 2.7), but I cannot get the example to work under Windows (Vista). It works fine in Ubuntu 11.10, so I know that the following code at least works in a UNIX-based environment...
[ "It looks like you may need to have it running in 2 different processes or split the client and server into 2 different threads. I got this to work on my Win7 box just now:\nclient.py\nimport socket\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((\"localhost\", 4242))\nwhile True:\n line = ...
[ 3 ]
[]
[]
[ "client_server", "networking", "python", "sockets", "winsock" ]
stackoverflow_0007863118_client_server_networking_python_sockets_winsock.txt
Q: Evaluating function objects from within a function in Python Lets say we have two defined function objects add1 = lambda x: x+1 and square = lambda x: x*x now I want to have a function that calls and adds the result of these two functions. What I thought would work is: def addFuncs(f,g): f+g addFunc...
Evaluating function objects from within a function in Python
Lets say we have two defined function objects add1 = lambda x: x+1 and square = lambda x: x*x now I want to have a function that calls and adds the result of these two functions. What I thought would work is: def addFuncs(f,g): f+g addFuncs(add1,square)(10) Which I thought would give me an answer of 111...
[ "def addFuncs(f,g):\n return lambda x: f(x) + g(x)\n\naddFuncs(add1,square)(10)\n\nPython doesn't support adding functions together which both of your attempts tried to do. Instead, you need to create a new function, such as with lambda which calls the original functions.\n", "Your original idea will work if y...
[ 3, 1, 0 ]
[]
[]
[ "functional_programming", "python" ]
stackoverflow_0007863584_functional_programming_python.txt
Q: batch search and replace strings in filenames with python I am trying to write a small python script to rename a bunch of filenames by searching and replacing. For example: Original filename: MyMusic.Songname.Artist-mp3.iTunes.mp3 Intendet Result: Songname.Artist.mp3 what i've got so far is: #!/usr/bin/env python...
batch search and replace strings in filenames with python
I am trying to write a small python script to rename a bunch of filenames by searching and replacing. For example: Original filename: MyMusic.Songname.Artist-mp3.iTunes.mp3 Intendet Result: Songname.Artist.mp3 what i've got so far is: #!/usr/bin/env python from os import rename, listdir mustgo = "MyMusic." filenames ...
[ "import fnmatch\nimport re \nimport os\n\nwith open('badwords.txt','r') as f:\n pat='|'.join(fnmatch.translate(badword)[:-1] for badword in \n f.read().splitlines()) \n\nfor fname in os.listdir('.'):\n new_fname=re.sub(pat,'',fname)\n if fname != new_fname:\n print('{o} --> {n}'...
[ 3 ]
[]
[]
[ "filenames", "linux", "python", "rename" ]
stackoverflow_0007863464_filenames_linux_python_rename.txt
Q: Best practice for hacking on a 3rd-party python module I often find myself wanting to use a 3rd party python module in my own project, but I know that I will also need to make changes to the 3rd party module that I want to push upstream. What is the best practice of file layout/installation to achieve this? Most p...
Best practice for hacking on a 3rd-party python module
I often find myself wanting to use a 3rd party python module in my own project, but I know that I will also need to make changes to the 3rd party module that I want to push upstream. What is the best practice of file layout/installation to achieve this? Most python modules are laid out with root dir containing a "setup...
[ "If the 3rd party project is using setuptools or distribute, you can do python setup.py develop instead of install. This will create the appropriate sym-links in the site-packages dir for you.\n" ]
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0007864103_python.txt
Q: A regular expression for finding a word within a string exactly "n" times Im trying to make a regular expression in python that allows me to find a word within a string "n" times For example, if i wanted to find a expression that could match if the word "cat" is exactly two times. How i would do that? It should ac...
A regular expression for finding a word within a string exactly "n" times
Im trying to make a regular expression in python that allows me to find a word within a string "n" times For example, if i wanted to find a expression that could match if the word "cat" is exactly two times. How i would do that? It should accept "The blue cat talks to the red cat in the tree". Because it has "cat" exac...
[ "Don't use regular expressions just because they are there.\nwords = text.split()\nprint words.count('cat')\n\nAs Vincent points out, that assumes all words are seperated by whitespace.\nwords = re.findall(\"\\b\\w*\") \n\nIs probably a better options. Although whether that is neccesary depends on details not provi...
[ 3, 2, 2, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007863077_python_regex.txt
Q: gnu-binutils-strings utf-8 instead of utf-16 or ascii I've noticed gnu-binutils-strings can printout utf-16 content in a file - is it possible for the program to print out utf-8 strings? if so, which arguments are appropriate? i'm working in a python environment using subprocess and would like to work with the out...
gnu-binutils-strings utf-8 instead of utf-16 or ascii
I've noticed gnu-binutils-strings can printout utf-16 content in a file - is it possible for the program to print out utf-8 strings? if so, which arguments are appropriate? i'm working in a python environment using subprocess and would like to work with the output from gnu-binutils-strings that a subprocess.Popen call ...
[ "I'm not experienced with strings, but the version I have (2.21.51.20110605) has an 8-bit encoding option (-eS) that would work with utf-8 text. It must have to cast a wide net looking for 'text' delimited by non-printable characters (value < 32). I'd expect a lot of noise. A test on a random executable showed the ...
[ 4 ]
[]
[]
[ "binutils", "python", "unix", "utf_16", "utf_8" ]
stackoverflow_0007863986_binutils_python_unix_utf_16_utf_8.txt
Q: Horizontal flip of Image on Python with pypng I am trying to horizontally flip an image (from left to right) on Python using PyPNG, I have written the following codes but it does not seem to work, anybody have any idea what I'm doing wrong here? def horizontal_flip(image): rows = len(image) cols = len(imag...
Horizontal flip of Image on Python with pypng
I am trying to horizontally flip an image (from left to right) on Python using PyPNG, I have written the following codes but it does not seem to work, anybody have any idea what I'm doing wrong here? def horizontal_flip(image): rows = len(image) cols = len(image[0]) new_image = [] for r in range(rows): ...
[ "new_row.append(image[r][c]) should be outside of the if.\nAlso, you're flipping the image horizontally... twice. Make your for loop use range(0,cols/2,3). (That may also eliminate the need for that if.)\nYou're also modifying the original image in-place; are you sure you want to do that?\nSeems a simpler solutio...
[ 0, 0 ]
[]
[]
[ "image", "pypng", "python" ]
stackoverflow_0007863932_image_pypng_python.txt
Q: Change Program Flow based on Available Libraries I am developing a Python model that will support graphing if the correct modules are installed. I would like the source code to be the same if possible, IE, if the graphing model can't load, graphing would be ignored from the menu logic. How can I accomplish this?...
Change Program Flow based on Available Libraries
I am developing a Python model that will support graphing if the correct modules are installed. I would like the source code to be the same if possible, IE, if the graphing model can't load, graphing would be ignored from the menu logic. How can I accomplish this?
[ "Attempt an import and set a flag if fails. Then use the flag to determine whether to offer graphic output:\ntry:\n import Tkinter\n gui_installed = True\nexcept ImportError:\n gui_installed = False\n\n\n...\n\nresult = somecalc()\nif gui_installed:\n display_with_gui(result)\nelse:\n display_as_tex...
[ 7, 1, 0 ]
[]
[]
[ "graph", "matplotlib", "python" ]
stackoverflow_0007863224_graph_matplotlib_python.txt
Q: Instantiating a unique object every time when using object composition? As an example, just a couple of dummy objects that will be used together. FWIW this is using Python 2.7.2. class Student(object): def __init__(self, tool): self.tool = tool def draw(self): if self.tool.broken != True:...
Instantiating a unique object every time when using object composition?
As an example, just a couple of dummy objects that will be used together. FWIW this is using Python 2.7.2. class Student(object): def __init__(self, tool): self.tool = tool def draw(self): if self.tool.broken != True: print "I used my tool. Sweet." else: print "...
[ "You have to create new instances of the Tool for each Student.\nclass Student(object):\n def __init__(self, tool):\n self.tool = tool\n\n def draw(self):\n if self.tool.broken != True:\n print \"I used my tool. Sweet.\"\n else:\n print \"My tool is broken. Wah.\"\n\...
[ 3, 2, 1, 1, 0, 0 ]
[]
[]
[ "composition", "object", "python", "singleton" ]
stackoverflow_0007844187_composition_object_python_singleton.txt
Q: How can I sort an item alphabetically before I add it to the list? I have an assignment that I am supposed to find each word in a line, and add that word to a list. Then there is also another list corresponding to the list of word, but that list will tell the amount of times the word appear in the text. I have fin...
How can I sort an item alphabetically before I add it to the list?
I have an assignment that I am supposed to find each word in a line, and add that word to a list. Then there is also another list corresponding to the list of word, but that list will tell the amount of times the word appear in the text. I have finished that part. However, I cannot find a way to compare the new found w...
[ "Homework hint: look at Python's source code for the bisect module. That shows how to find indexes and make insertions in a sorted list.\n" ]
[ 1 ]
[]
[]
[ "alphabetical_sort", "python", "sorting" ]
stackoverflow_0007864362_alphabetical_sort_python_sorting.txt