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 do I use udev to find info about inserted video media (e.g. DVDs) I'm trying to port an application from using HAL to using pure udev. It is written in python and will use the gudev library, though I would love to see examples in any language. I'm able to get all attached video devices (such as cameras) via: import gudev client = gudev.Client(["video4linux"]) for device in client.get_devices(): print device.get_sysfs_attr("name"), device.get_device_name() This prints out something like: USB2.0 UVC WebCam /dev/video0 I am also able to get a list of block devices, but how can I: Tell if it is a CD/DVD drive? Tell if media is currently inserted if the drive supports removable media? Tell what the name/label of the media is (e.g. FUTURAMAS1 for a DVD)? The original code I am trying to port over is located at http://github.com/danielgtaylor/arista/blob/045a4d48ebfda44bc5d0609618ff795604ee134f/arista/inputs.py Any and all help would be greatly appreciated! Update: adding answer below. import gudev client = gudev.Client(['block']) for device in client.query_by_subsystem("block"): if device.has_property("ID_CDROM"): print "Found CD/DVD drive at %s" % device.get_device_file() if device.has_property("ID_FS_LABEL"): print "Found disc: %s" % device.get_property("ID_FS_LABEL") elif device.has_property("ID_FS_TYPE"): print "Found disc" else: print "No disc" The code above will output data like: Found CD/DVD drive at /dev/sr0 Found disc: Ubuntu_10.04_i386 Thanks for the help! A: Have a look at the device properties: import gudev client = gudev.Client(['block']) for device in client.query_by_subsystem("block"): print device for device_key in device.get_property_keys(): print " property %s: %s" % (device_key, device.get_property(device_key)) print
How do I use udev to find info about inserted video media (e.g. DVDs)
I'm trying to port an application from using HAL to using pure udev. It is written in python and will use the gudev library, though I would love to see examples in any language. I'm able to get all attached video devices (such as cameras) via: import gudev client = gudev.Client(["video4linux"]) for device in client.get_devices(): print device.get_sysfs_attr("name"), device.get_device_name() This prints out something like: USB2.0 UVC WebCam /dev/video0 I am also able to get a list of block devices, but how can I: Tell if it is a CD/DVD drive? Tell if media is currently inserted if the drive supports removable media? Tell what the name/label of the media is (e.g. FUTURAMAS1 for a DVD)? The original code I am trying to port over is located at http://github.com/danielgtaylor/arista/blob/045a4d48ebfda44bc5d0609618ff795604ee134f/arista/inputs.py Any and all help would be greatly appreciated! Update: adding answer below. import gudev client = gudev.Client(['block']) for device in client.query_by_subsystem("block"): if device.has_property("ID_CDROM"): print "Found CD/DVD drive at %s" % device.get_device_file() if device.has_property("ID_FS_LABEL"): print "Found disc: %s" % device.get_property("ID_FS_LABEL") elif device.has_property("ID_FS_TYPE"): print "Found disc" else: print "No disc" The code above will output data like: Found CD/DVD drive at /dev/sr0 Found disc: Ubuntu_10.04_i386 Thanks for the help!
[ "Have a look at the device properties:\nimport gudev\n\nclient = gudev.Client(['block'])\nfor device in client.query_by_subsystem(\"block\"):\n print device\n for device_key in device.get_property_keys():\n print \" property %s: %s\" % (device_key, device.get_property(device_key))\n print\n\n" ]
[ 4 ]
[]
[]
[ "python", "udev" ]
stackoverflow_0002861098_python_udev.txt
Q: Integrating Jython Cpython I am about to begin a project where I will likely use PyQt or Pyside. I will need to interface with a buggy 3rd party piece of server software that provides C++ and Java APIs. The Java APIs are a lot easier to use because you get Exceptions where with the C++ libraries you get segfaults. Also, the Python bindings to the Java APIs are automatic with Jython whereas the Python bindings for the C++ APIs don't exist. So, how would a CPython PyQt client application be able to communicate with these Java APIs? How would you go about it? Would you have another separate Java process on the client that serializes / pickles objects and communicates with the PyQt process over a socket? I don't want to re-invent the wheel... is there some sort of standard interface for these types of things? Some technology I should look into? RPC, Corba, etc? Thanks, ~Eric A: If you want to maintain complete isolation and increase your robustness (the 3rd party library going down and not taking your client, and if it's buggy I would recommend that) then perhaps something like CORBA is the way forwards. Don't forget that Java comes with a CORBA implementation as standard, so you just need to generate your C proxy from the IDL. Swig may be of interest if you want to run stuff in-process. It simplifies the binding of components in different languages. Note in particular that it generates bindings for Python and Java. A: If the criteria is not reinventing the wheel, there is the SimpleXMLRPCServer and xmlrpclib modules available in the standard library. They should work in Jython too.
Integrating Jython Cpython
I am about to begin a project where I will likely use PyQt or Pyside. I will need to interface with a buggy 3rd party piece of server software that provides C++ and Java APIs. The Java APIs are a lot easier to use because you get Exceptions where with the C++ libraries you get segfaults. Also, the Python bindings to the Java APIs are automatic with Jython whereas the Python bindings for the C++ APIs don't exist. So, how would a CPython PyQt client application be able to communicate with these Java APIs? How would you go about it? Would you have another separate Java process on the client that serializes / pickles objects and communicates with the PyQt process over a socket? I don't want to re-invent the wheel... is there some sort of standard interface for these types of things? Some technology I should look into? RPC, Corba, etc? Thanks, ~Eric
[ "If you want to maintain complete isolation and increase your robustness (the 3rd party library going down and not taking your client, and if it's buggy I would recommend that) then perhaps something like CORBA is the way forwards. Don't forget that Java comes with a CORBA implementation as standard, so you just need to generate your C proxy from the IDL.\nSwig may be of interest if you want to run stuff in-process. It simplifies the binding of components in different languages. Note in particular that it generates bindings for Python and Java.\n", "If the criteria is not reinventing the wheel, there is the SimpleXMLRPCServer and xmlrpclib modules available in the standard library. They should work in Jython too.\n" ]
[ 0, 0 ]
[]
[]
[ "jython", "process", "pyqt", "python", "qt" ]
stackoverflow_0002860650_jython_process_pyqt_python_qt.txt
Q: Distributing an executable zip file with __main__.py, how to access extra data? I'm doing a little program and I want to distribute it using this recipe: single directory with __main__.py in it zip this directory and adding a shebang on it #!/usr/bin/env python making it executable The problem is that in this package I have also extra files (I'm using pygtk toolkit and I need images and ui xml files). When I try to access these files I have the error that the resource is unavailable (the path that I'm trying to open is something like file.zip/gui/gui.ui ). How can I handle this situation? A: I figured out by myself, It's sufficient to use pkgutil.get_data to access the data inside a package.
Distributing an executable zip file with __main__.py, how to access extra data?
I'm doing a little program and I want to distribute it using this recipe: single directory with __main__.py in it zip this directory and adding a shebang on it #!/usr/bin/env python making it executable The problem is that in this package I have also extra files (I'm using pygtk toolkit and I need images and ui xml files). When I try to access these files I have the error that the resource is unavailable (the path that I'm trying to open is something like file.zip/gui/gui.ui ). How can I handle this situation?
[ "I figured out by myself, It's sufficient to use pkgutil.get_data to access the data inside a package.\n" ]
[ 8 ]
[]
[]
[ "packaging", "python", "zipapp" ]
stackoverflow_0002859413_packaging_python_zipapp.txt
Q: How do I convert this Python punctuation-stripping function to JavaScript? Please can anyone translate this python code into javascript. # def strip_punctuation(s): # for c in ',.":;!%$': # while s.find(c) is not -1: # s.replace(c, '') A: function strip_punctuation(s) { return s.replace(/[,.":;!%$]/g, ""); }
How do I convert this Python punctuation-stripping function to JavaScript?
Please can anyone translate this python code into javascript. # def strip_punctuation(s): # for c in ',.":;!%$': # while s.find(c) is not -1: # s.replace(c, '')
[ "function strip_punctuation(s) {\n return s.replace(/[,.\":;!%$]/g, \"\");\n}\n\n" ]
[ 12 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0002861528_javascript_python.txt
Q: How to determine subprocess.Popen() failed when shell=True Windows version of Python 2.6.4: Is there any way to determine if subprocess.Popen() fails when using shell=True? Popen() successfully fails when shell=False >>> import subprocess >>> p = subprocess.Popen( 'Nonsense.application', shell=False ) Traceback (most recent call last): File ">>> pyshell#258", line 1, in <module> p = subprocess.Popen( 'Nonsense.application' ) File "C:\Python26\lib\subprocess.py", line 621, in __init__ errread, errwrite) File "C:\Python26\lib\subprocess.py", line 830, in _execute_child startupinfo) WindowsError: [Error 2] The system cannot find the file specified But when shell=True, there appears to be no way to determine if a Popen() call was successful or not. >>> p = subprocess.Popen( 'Nonsense.application', shell=True ) >>> p >>> subprocess.Popen object at 0x0275FF90>>> >>> p.pid 6620 >>> p.returncode >>> Ideas appreciated. Regards, Malcolm A: returncode will work, although it will be None until you've called p.poll(). poll() itself will return the error code, so you can just do if a.poll() != 0: print ":(" A: In the first case it fails to start, in the second - it successfully starts shell which, in turn, fails to execute the application. So your process has been properly spawned, exited and waits for you to inquire about its exit code. So, the thing is, unless your shell or environment (e.g. no memory) is utterly broken there's no way Popen itself may fail. So, you can safely .poll() and .wait() on it to get all the sad news.
How to determine subprocess.Popen() failed when shell=True
Windows version of Python 2.6.4: Is there any way to determine if subprocess.Popen() fails when using shell=True? Popen() successfully fails when shell=False >>> import subprocess >>> p = subprocess.Popen( 'Nonsense.application', shell=False ) Traceback (most recent call last): File ">>> pyshell#258", line 1, in <module> p = subprocess.Popen( 'Nonsense.application' ) File "C:\Python26\lib\subprocess.py", line 621, in __init__ errread, errwrite) File "C:\Python26\lib\subprocess.py", line 830, in _execute_child startupinfo) WindowsError: [Error 2] The system cannot find the file specified But when shell=True, there appears to be no way to determine if a Popen() call was successful or not. >>> p = subprocess.Popen( 'Nonsense.application', shell=True ) >>> p >>> subprocess.Popen object at 0x0275FF90>>> >>> p.pid 6620 >>> p.returncode >>> Ideas appreciated. Regards, Malcolm
[ "returncode will work, although it will be None until you've called p.poll(). poll() itself will return the error code, so you can just do\nif a.poll() != 0:\n print \":(\"\n\n", "In the first case it fails to start, in the second - it successfully starts shell which, in turn, fails to execute the application. So your process has been properly spawned, exited and waits for you to inquire about its exit code. So, the thing is, unless your shell or environment (e.g. no memory) is utterly broken there's no way Popen itself may fail.\nSo, you can safely .poll() and .wait() on it to get all the sad news.\n" ]
[ 16, 5 ]
[]
[]
[ "popen", "python", "subprocess" ]
stackoverflow_0002861548_popen_python_subprocess.txt
Q: template files evaluation in python I am trying to use python for translating a set of templates to a set of configuration files based on values taken from a main configuration file. However, I am having certain issues. Consider the following example of a template file. file1.cfg.template %(CLIENT1)s %(HOST1)s %(PORT1)d C %(COMPID1)s %(CLIENT2)s %(HOST2)s %(PORT2)d C %(COMPID2)s This file contains an entry for each client. There are hundreds of config files like this and I don't want to have logic for each type of config file. Python should do the replacements and generate config files automatically given a set of global values read from a main xml config file. However, in the above example, if CLIENT2 does not exist, how do I delete that line? I expect Python would generate the config file using something like this: os.open("file1.cfg.template").read() % myhash where myhash is hash of configuration parameters from the main config file which may not contain CLIENT2 at all. In the case it does not contain CLIENT2, I want that line to disappear from the file. Is it possible to insert some 'IF' block in the file and have python evaluate it? Thanks for your help. Any suggestions most welcome. A: Sounds like you may have outgrown your originally simple home-grown templating solution. Maybe you should move to something like Jinja? It might be less of a headache to simply implement a third-party solution than it would be to create/continue to maintain your own solution. Other options: cheetah mako A: Maybe you can use a standalone Django template. How do I use Django templates without the rest of Django? - Stack Overflow A: Given that the files already exist, I would set default values for things like CLIENT2 (assuming you know ahead of time all possible keys). You can probably set the default value to something unusual so you can do config = os.open("file1.cfg.template").read() % myhash config = [l for l in config.split('\n') if <l does not have unusual text>].join('\n') I agree with others that in the long term a more robust template would be better.
template files evaluation in python
I am trying to use python for translating a set of templates to a set of configuration files based on values taken from a main configuration file. However, I am having certain issues. Consider the following example of a template file. file1.cfg.template %(CLIENT1)s %(HOST1)s %(PORT1)d C %(COMPID1)s %(CLIENT2)s %(HOST2)s %(PORT2)d C %(COMPID2)s This file contains an entry for each client. There are hundreds of config files like this and I don't want to have logic for each type of config file. Python should do the replacements and generate config files automatically given a set of global values read from a main xml config file. However, in the above example, if CLIENT2 does not exist, how do I delete that line? I expect Python would generate the config file using something like this: os.open("file1.cfg.template").read() % myhash where myhash is hash of configuration parameters from the main config file which may not contain CLIENT2 at all. In the case it does not contain CLIENT2, I want that line to disappear from the file. Is it possible to insert some 'IF' block in the file and have python evaluate it? Thanks for your help. Any suggestions most welcome.
[ "Sounds like you may have outgrown your originally simple home-grown templating solution. Maybe you should move to something like Jinja? It might be less of a headache to simply implement a third-party solution than it would be to create/continue to maintain your own solution.\nOther options:\n\ncheetah\nmako\n\n", "Maybe you can use a standalone Django template.\nHow do I use Django templates without the rest of Django? - Stack Overflow\n", "Given that the files already exist, I would set default values for things like CLIENT2 (assuming you know ahead of time all possible keys). You can probably set the default value to something unusual so you can do\nconfig = os.open(\"file1.cfg.template\").read() % myhash\nconfig = [l for l in config.split('\\n') if <l does not have unusual text>].join('\\n')\n\nI agree with others that in the long term a more robust template would be better.\n" ]
[ 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002861543_python.txt
Q: Converting datetime.ctime() values to Unicode I would like to convert datetime.ctime() values to Unicode. Using Python 2.6.4 running under Windows I can set my locale to Spanish like below: >>> import locale >>> locale.setlocale(locale.LC_ALL, 'esp' ) Then I can pass %a, %A, %b, and %B to ctime() to get day and month names and abbreviations. >>> import datetime >>> dateValue = datetime.date( 2010, 5, 15 ) >>> dayName = dateValue.strftime( '%A' ) >>> dayName 's\xe1bado' How do I convert the 's\xe1bado' value to Unicode? Specifically what encoding do I use? I'm thinking I might do something like the following, but I'm not sure this is the right approach. >>> codePage = locale.getdefaultlocale()[ 1 ] >>> dayNameUnicode = unicode( dayName, codePage ) >>> dayNameUnicode u's\xe1bado' Malcolm A: Converting with unicode() or string.decode() like in your example should work. The only problem should be that in your example you use the default locale's encoding even though you set the locale to something different before. If you use locale.getlocale()[1] instead of locale.getdefaultlocale()[1] you should get the correct results. A: It is Unicode - when you called unicode() on it it became Unicode. You can tell because there's a u in front of the string when it's displayed with repr(). Try printing it instead: >>> d = u's\xe1bado' >>> d u's\xe1bado' >>> print d sábado >>> A: This probably depends on your OS. But the data looks like latin1. >>> s.decode('latin1') u's\xe1bado'
Converting datetime.ctime() values to Unicode
I would like to convert datetime.ctime() values to Unicode. Using Python 2.6.4 running under Windows I can set my locale to Spanish like below: >>> import locale >>> locale.setlocale(locale.LC_ALL, 'esp' ) Then I can pass %a, %A, %b, and %B to ctime() to get day and month names and abbreviations. >>> import datetime >>> dateValue = datetime.date( 2010, 5, 15 ) >>> dayName = dateValue.strftime( '%A' ) >>> dayName 's\xe1bado' How do I convert the 's\xe1bado' value to Unicode? Specifically what encoding do I use? I'm thinking I might do something like the following, but I'm not sure this is the right approach. >>> codePage = locale.getdefaultlocale()[ 1 ] >>> dayNameUnicode = unicode( dayName, codePage ) >>> dayNameUnicode u's\xe1bado' Malcolm
[ "Converting with unicode() or string.decode() like in your example should work. The only problem should be that in your example you use the default locale's encoding even though you set the locale to something different before. If you use locale.getlocale()[1] instead of locale.getdefaultlocale()[1] you should get the correct results.\n", "It is Unicode - when you called unicode() on it it became Unicode. You can tell because there's a u in front of the string when it's displayed with repr(). Try printing it instead:\n>>> d = u's\\xe1bado'\n>>> d\nu's\\xe1bado'\n>>> print d\nsábado\n>>>\n\n", "This probably depends on your OS. But the data looks like latin1.\n>>> s.decode('latin1')\nu's\\xe1bado'\n\n" ]
[ 3, 2, 0 ]
[]
[]
[ "datetime", "python", "unicode" ]
stackoverflow_0002861583_datetime_python_unicode.txt
Q: parse this directory path without losing slash I have a wxPython application. I am taking in a directory path from a textbox using GetValue(). I notice that while trying to write this string to a variable: "C:\Documents and Settings\tchan\Desktop\InputFile.xls", python sees the string as 'C:\\Documents and Settings\tchan\\Desktop\\InputFile.xls' (missing a slash between "Settings" and "UserName). More info: The directory path string is created by the "open file" dialog, which creates a standard 'choose file' dialog you see in any 'open' function in a text processor. The string is written to a textbox and read later when the main thread begins (in case the user wants to change it). EDIT: I realise that the problem comes from the '\t' being seen as a "tab" instead of normal forward slash. However I don't know how to work past this, since A: I suspect there's a different way to get that path from wx that would avoid this issue, since it seems like this would be a fairly common problem. That said, there are a few ways to fix a mangled path like you describe, by converting the string you have to a raw string. rawpath = "%r" % path The resulting rawpath will likely be somewhat messy since it will probably add extra escapes to the backslashes and give you something like: "'C:\\\\Documents and Settings\\tchan\\\\Desktop\\\\InputFile.xls'" It seems like os.path.normpath will clean that up though. import os.path os.path.normpath(rawpath) A: not saying this is the correct solution, but you can x = "C:\tmp".encode('string-escape') x 'C:\\tmp' better, if you are using the file dialog os.path.join(dlg.GetDirectory(),dlg.GetFilename()) where dlg is your dialog A: You have to escape the slashes. \\ will store a literal \ in the string: path = "C:\\Documents and Settings\\tchan\\Desktop\\InputFile.xls"
parse this directory path without losing slash
I have a wxPython application. I am taking in a directory path from a textbox using GetValue(). I notice that while trying to write this string to a variable: "C:\Documents and Settings\tchan\Desktop\InputFile.xls", python sees the string as 'C:\\Documents and Settings\tchan\\Desktop\\InputFile.xls' (missing a slash between "Settings" and "UserName). More info: The directory path string is created by the "open file" dialog, which creates a standard 'choose file' dialog you see in any 'open' function in a text processor. The string is written to a textbox and read later when the main thread begins (in case the user wants to change it). EDIT: I realise that the problem comes from the '\t' being seen as a "tab" instead of normal forward slash. However I don't know how to work past this, since
[ "I suspect there's a different way to get that path from wx that would avoid this issue, since it seems like this would be a fairly common problem. That said, there are a few ways to fix a mangled path like you describe, by converting the string you have to a raw string.\nrawpath = \"%r\" % path\n\nThe resulting rawpath will likely be somewhat messy since it will probably add extra escapes to the backslashes and give you something like:\n\"'C:\\\\\\\\Documents and Settings\\\\tchan\\\\\\\\Desktop\\\\\\\\InputFile.xls'\"\n\nIt seems like os.path.normpath will clean that up though.\nimport os.path\nos.path.normpath(rawpath)\n\n", "not saying this is the correct solution, but you can \nx = \"C:\\tmp\".encode('string-escape')\nx\n'C:\\\\tmp'\n\nbetter, if you are using the file dialog \nos.path.join(dlg.GetDirectory(),dlg.GetFilename())\n\nwhere dlg is your dialog\n", "You have to escape the slashes. \\\\ will store a literal \\ in the string:\npath = \"C:\\\\Documents and Settings\\\\tchan\\\\Desktop\\\\InputFile.xls\"\n\n" ]
[ 4, 2, 0 ]
[]
[]
[ "escaping", "python", "string", "wxpython" ]
stackoverflow_0002860233_escaping_python_string_wxpython.txt
Q: Viewing Python's shelve objects in PHP I am using Python for indexing utilizing the shelve functionality and I was wondering whether it was possible to open and read the files in PHP. I checked out the PHP Shelve option and it doesn't seem to be working on PHP 5.X I am getting (when running the example they gave me) PHP Fatal error: Cannot pass parameter 2 by reference in test.php on line 205 Even still, I don't think I'd get the same performance writing to the shelve in PHP as I would in Python. A: I'm not sure how mature or well developed that project is, but, if I had that need, I would try the Python In PHP project.
Viewing Python's shelve objects in PHP
I am using Python for indexing utilizing the shelve functionality and I was wondering whether it was possible to open and read the files in PHP. I checked out the PHP Shelve option and it doesn't seem to be working on PHP 5.X I am getting (when running the example they gave me) PHP Fatal error: Cannot pass parameter 2 by reference in test.php on line 205 Even still, I don't think I'd get the same performance writing to the shelve in PHP as I would in Python.
[ "I'm not sure how mature or well developed that project is, but, if I had that need, I would try the Python In PHP project.\n" ]
[ 1 ]
[]
[]
[ "php", "python", "shelve" ]
stackoverflow_0002862016_php_python_shelve.txt
Q: building a pairwise matrix in scipy/numpy in Python from dictionaries I have a dictionary whose keys are strings and values are numpy arrays, e.g.: data = {'a': array([1,2,3]), 'b': array([4,5,6]), 'c': array([7,8,9])} I want to compute a statistic between all pairs of values in 'data' and build an n by x matrix that stores the result. Assume that I know the order of the keys, i.e. I have a list of "labels": labels = ['a', 'b', 'c'] What's the most efficient way to compute this matrix? I can compute the statistic for all pairs like this: result = [] for elt1, elt2 in itertools.product(labels, labels): result.append(compute_statistic(data[elt1], data[elt2])) But I want result to be a n by n matrix, corresponding to "labels" by "labels". How can I record the results as this matrix? thanks. A: You could use a nested loop, or a list comprehension like: result = [[compute_stat(data[row], data[col]) for col in labels] for row in labels] A: Convert the result list into a matrix and then adjust the shape. myMatrix = array(result) # or use matrix(result) myMatrix.shape = (len(labels), len(labels)) If you want to index the matrix with the labels you could do myMatrix[labels.index('a'), labels.index('b')] This gets the a*b value. If this is your intention it would be better to store the indexes in a dictionary. labelsIndex = {'a' : 0, 'b' : 1, 'c' : 2 } myMatrix[labelsIndex['a'], labelsIndex['b']] Hope this helps.
building a pairwise matrix in scipy/numpy in Python from dictionaries
I have a dictionary whose keys are strings and values are numpy arrays, e.g.: data = {'a': array([1,2,3]), 'b': array([4,5,6]), 'c': array([7,8,9])} I want to compute a statistic between all pairs of values in 'data' and build an n by x matrix that stores the result. Assume that I know the order of the keys, i.e. I have a list of "labels": labels = ['a', 'b', 'c'] What's the most efficient way to compute this matrix? I can compute the statistic for all pairs like this: result = [] for elt1, elt2 in itertools.product(labels, labels): result.append(compute_statistic(data[elt1], data[elt2])) But I want result to be a n by n matrix, corresponding to "labels" by "labels". How can I record the results as this matrix? thanks.
[ "You could use a nested loop, or a list comprehension like:\nresult = [[compute_stat(data[row], data[col]) for col in labels]\n for row in labels]\n\n", "Convert the result list into a matrix and then adjust the shape.\nmyMatrix = array(result) # or use matrix(result)\nmyMatrix.shape = (len(labels), len(labels))\n\nIf you want to index the matrix with the labels you could do\nmyMatrix[labels.index('a'), labels.index('b')]\n\nThis gets the a*b value. If this is your intention it would be better to store the indexes in a dictionary.\nlabelsIndex = {'a' : 0, 'b' : 1, 'c' : 2 }\nmyMatrix[labelsIndex['a'], labelsIndex['b']]\n\nHope this helps.\n" ]
[ 2, 2 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0002861862_numpy_python_scipy.txt
Q: Searching for a track on iTunes I'd like to search for tracks on iTunes using a Python script on Mac OS/X. I found a way to access the iTunes application through: iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes") but I haven't figured out (yet) the way to perform searches. A little help appreciated. Disclaimer: OS/X newbie here. Note: I am not looking for ways to access the XML/plist database directly. A: You might want to check out appscript (note, you'll need ASDictionary for online help): >>> import appscript >>> iTunes = appscript.app("iTunes") >>> lib = iTunes.playlists['Library'] >>> for trk in lib.tracks(): ... if re.search("test", trk.name()): ... print trk.name() This might give you the most control by iterating over each item, but there's a much faster way too, by using applescript hooks to do the searching: >>> trks = lib.tracks[appscript.its.name.contains('test')] >>> print trks.name() Check out these appscript usage examples as well. A: It might be useless answer, but i'd advise you to use AppleScript instead of Python. Take a look at this piece of code: tell application "iTunes" repeat with bTrack in (every track of playlist 7 whose artist contains "Golden") ... Perfect tutorials might be found here: http://macscripter.net/viewtopic.php?id=25631 A: What do you think of: script = '''tell application "iTunes" repeat with bTrack in (every track of playlist 7 whose artist contains "Golden") print bTrack end repeat end tell''' tracks,_ = subprocess.Popen("osascript -e %s" % script, stdout=subprocess.PIPE).communicate() trackList = tracks.split('\n') I never tested this, though....
Searching for a track on iTunes
I'd like to search for tracks on iTunes using a Python script on Mac OS/X. I found a way to access the iTunes application through: iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes") but I haven't figured out (yet) the way to perform searches. A little help appreciated. Disclaimer: OS/X newbie here. Note: I am not looking for ways to access the XML/plist database directly.
[ "You might want to check out appscript (note, you'll need ASDictionary for online help):\n>>> import appscript\n>>> iTunes = appscript.app(\"iTunes\")\n>>> lib = iTunes.playlists['Library']\n>>> for trk in lib.tracks():\n... if re.search(\"test\", trk.name()):\n... print trk.name()\n\nThis might give you the most control by iterating over each item, but there's a much faster way too, by using applescript hooks to do the searching:\n>>> trks = lib.tracks[appscript.its.name.contains('test')]\n>>> print trks.name()\n\nCheck out these appscript usage examples as well.\n", "It might be useless answer, but i'd advise you to use AppleScript instead of Python.\nTake a look at this piece of code:\ntell application \"iTunes\"\n repeat with bTrack in (every track of playlist 7 whose artist contains \"Golden\")\n...\n\nPerfect tutorials might be found here: http://macscripter.net/viewtopic.php?id=25631\n", "What do you think of:\n\nscript = '''tell application \"iTunes\"\n repeat with bTrack in (every track of playlist 7 whose artist contains \"Golden\")\n print bTrack\n end repeat\nend tell'''\ntracks,_ = subprocess.Popen(\"osascript -e %s\" % script, stdout=subprocess.PIPE).communicate()\ntrackList = tracks.split('\\n')\n\nI never tested this, though....\n" ]
[ 4, 0, 0 ]
[]
[]
[ "itunes", "macos", "python", "scripting" ]
stackoverflow_0002752225_itunes_macos_python_scripting.txt
Q: How do I get an overview and a methodology for programming in Python I've started to learn Python and programming from scratch. I have not programmed before so it's a new experience. I do seem to grasp most of the concepts, from variables to definitions and modules. I still need to learn a lot more about what the different libraries and modules do and also I lack knowledge on OOP and classes in Python. I see people who just program in Python like that's all they have ever done and I am still just coming to grips with it. Is there a way, some tools, a logical methodology that would give me an overview or a good hold of how to handle programming problems ? For instance, I'm trying to create a parser which we need at the office . I also need to create a spider that would collect links from various websites. Is there a formidable way of studying the various modules to see what is needed ? Or is it just nose to the grind stone and understand what the documentation says ? Sorry for the lengthy question.. A: The MIT Intro to Computer Science course on the MIT OpenCourseWare website was taught using Python. There are 24 lectures available as videos that you can watch for free. It's kind of academic to be sure, but it would give you a very solid foundation to start from. A: Start working your way through the Essential Python Reading List, which has articles on how to code in Python and how to do it well. A: If you like a more academical approach try Learning Python from Mark Lutz. For the use of standard libraries, the official docs are very good. More hands on descriptions can also be found in PYMOTW from Doug Hellmann A: Just do your project, learning what you need to along the way. By the time you do that a couple times, you'll "get" it. And you'll only improve from there. You can also read other peoples' code: download X that looks interesting and read through the code to understand how it works. Those two tips will help you learn any language. Aside from that, Dive Into Python is a great resource for learning a lot about Python. A: It might be useful to get some information on Object Oriented programming (just what is the whole class thing about, and how do you tell if your classes are good/poor/indifferent). Mark Lutz' book Learning Python has an entire Part (several chapters) on OO. If this stuff is new to you, it might be helpful to take a look. Two other books I have found quite useful: The Python Cookbook (Alex Martelli, a prolific contributor here), and the Python Essential Reference (David Beazley).
How do I get an overview and a methodology for programming in Python
I've started to learn Python and programming from scratch. I have not programmed before so it's a new experience. I do seem to grasp most of the concepts, from variables to definitions and modules. I still need to learn a lot more about what the different libraries and modules do and also I lack knowledge on OOP and classes in Python. I see people who just program in Python like that's all they have ever done and I am still just coming to grips with it. Is there a way, some tools, a logical methodology that would give me an overview or a good hold of how to handle programming problems ? For instance, I'm trying to create a parser which we need at the office . I also need to create a spider that would collect links from various websites. Is there a formidable way of studying the various modules to see what is needed ? Or is it just nose to the grind stone and understand what the documentation says ? Sorry for the lengthy question..
[ "The MIT Intro to Computer Science course on the MIT OpenCourseWare website was taught using Python. There are 24 lectures available as videos that you can watch for free.\nIt's kind of academic to be sure, but it would give you a very solid foundation to start from.\n", "Start working your way through the Essential Python Reading List, which has articles on how to code in Python and how to do it well.\n", "If you like a more academical approach try Learning Python from Mark Lutz.\nFor the use of standard libraries, the official docs are very good. More hands on descriptions can also be found in PYMOTW from Doug Hellmann\n", "Just do your project, learning what you need to along the way. By the time you do that a couple times, you'll \"get\" it. And you'll only improve from there. \nYou can also read other peoples' code: download X that looks interesting and read through the code to understand how it works. \nThose two tips will help you learn any language. Aside from that, Dive Into Python is a great resource for learning a lot about Python.\n", "It might be useful to get some information on Object Oriented programming (just what is the whole class thing about, and how do you tell if your classes are good/poor/indifferent). Mark Lutz' book Learning Python has an entire Part (several chapters) on OO. If this stuff is new to you, it might be helpful to take a look. Two other books I have found quite useful: The Python Cookbook (Alex Martelli, a prolific contributor here), and the Python Essential Reference (David Beazley).\n" ]
[ 4, 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002861575_python.txt
Q: Lighting Fast CMS, a Django based CMS. Any experiences? I've just came across Lighting Fast CMS, which seems to be very promising Django based content management system. Documentation seem to be very good, even though it is still in beta stage. It also has very nice buildout based installation. Also the core Components of it seem to be nicely decoupled. Does anyone have any experiences with it yet? How much one can customize it with extensions? How's extension development in general compared to Drupal or Plone? I'm hoping that I could do some projects with it instead of Plone or Drupal. Those both are great, but extending them ain't too nice. The project can be found here: http://www.lfcproject.com/
Lighting Fast CMS, a Django based CMS. Any experiences?
I've just came across Lighting Fast CMS, which seems to be very promising Django based content management system. Documentation seem to be very good, even though it is still in beta stage. It also has very nice buildout based installation. Also the core Components of it seem to be nicely decoupled. Does anyone have any experiences with it yet? How much one can customize it with extensions? How's extension development in general compared to Drupal or Plone? I'm hoping that I could do some projects with it instead of Plone or Drupal. Those both are great, but extending them ain't too nice. The project can be found here: http://www.lfcproject.com/
[]
[]
[ "I do not know anything about lfc, but you can also give django-cms a try!\nhttp://www.django-cms.org\n" ]
[ -1 ]
[ "content_management_system", "django", "python" ]
stackoverflow_0002862061_content_management_system_django_python.txt
Q: Difficulties with Django on Google App Engine I have a Django 1.1.1 project that works fine. I'm trying to import it to Google App Engine. I'm trying to follow these instructions. I run it on the dev server, and I get an import error: ImportError at / No module named mysite.urls This is the folder structure of mysite/: app.yaml <DIR> myapp index.yaml main.py manage.py <DIR> media settings.py urls.py __init__.py app.yaml: application: mysite version: 1 runtime: python api_version: 1 handlers: - url: .* script: main.py from settings.py: ROOT_URLCONF = 'mysite.urls' What am I doing wrong? UPDATE: now I get this error: Request Method: GET Request URL: http://localhost:8082/ Exception Type: AttributeError Exception Value: 'module' object has no attribute 'autodiscover' Exception Location: C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py in LoadModuleRestricted, line 1782 main.py: import logging, os # Google App Engine imports. from google.appengine.ext.webapp import util # Force Django to reload its settings. from django.conf import settings settings._target = None # Must set this env var before importing any part of Django # 'project' is the name of the project created with django-admin.py os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' import logging import django.core.handlers.wsgi import django.core.signals import django.db import django.dispatch.dispatcher def log_exception(*args, **kwds): logging.exception('Exception in request:') # Log errors. django.dispatch.dispatcher.connect( log_exception, django.core.signals.got_request_exception) # Unregister the rollback event handler. django.dispatch.dispatcher.disconnect( django.db._rollback_on_exception, django.core.signals.got_request_exception) def main(): # Create a Django application for WSGI. application = django.core.handlers.wsgi.WSGIHandler() # Run the WSGI CGI handler with that application. util.run_wsgi_app(application) if __name__ == '__main__': main() Directory structure of engineapp/: <DIR> mysite app.yaml index.yaml main.py Directory structure of engineapp/mysite: <DIR> myapp <DIR> media __init__.py initial_data.json manage.py settings.py urls.py I feel like I'm getting closer, but still not there. A: Try changing ROOT_URLCONF to just 'urls'. I don't think the parent directory of your app (in the App Engine sense, not the Django sense) directory is on sys.path when running on App Engine, which means that it doesn't see mysite as a Python package/module. EDIT to keep up with edited question: Now it sounds like you're inadvertently using Django 0.96 but expecting to use Django 1.1+. When you import django on App Engine, you will end up with 0.96 unless you explicitly tell App Engine you want to use a different version. Something like from google.appengine.dist import use_library use_library('django', '1.1') from jonmiddleton's answer should do the trick. Please note that in order to use this on the development server, you must have your own copy of Django 1.1 installed, because it's not bundled with the SDK. Please also note that, as far as I know, you're not going to have any luck using the Django admin site on App Engine. A: Here is my main.py: import os import sys import logging # Google App Hosting imports. from google.appengine.ext.webapp import util from google.appengine.dist import use_library os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings" sys.path.append("/home/brox/tmp/mysite") use_library('django', '1.1') # Enable info logging by the app (this is separate from appserver's # logging). logging.getLogger().setLevel(logging.DEBUG) def log_exception(*args, **kwds): logging.exception('Exception in request:') # Force sys.path to have our own directory first, so we can import from it. sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) # Force Django to reload its settings. from django.conf import settings settings._target = None import django.core.handlers.wsgi import django.core.signals import django.db # Log errors. django.dispatch.Signal.connect( django.core.signals.got_request_exception, log_exception) # Unregister the rollback event handler. django.dispatch.Signal.disconnect( django.core.signals.got_request_exception, django.db._rollback_on_exception) def main(): # Create a Django application for WSGI. application = django.core.handlers.wsgi.WSGIHandler() # Run the WSGI CGI handler with that application. util.run_wsgi_app(application) if __name__ == "__main__": main() As you can see there are additional paths and the django error logging is a bit different... Hope that it helps you. A: I haven't used pure django with appengine. But from what I've read you need the djangoappengine-patch to make it work. You can read about it and download it from http://www.allbuttonspressed.com/projects.
Difficulties with Django on Google App Engine
I have a Django 1.1.1 project that works fine. I'm trying to import it to Google App Engine. I'm trying to follow these instructions. I run it on the dev server, and I get an import error: ImportError at / No module named mysite.urls This is the folder structure of mysite/: app.yaml <DIR> myapp index.yaml main.py manage.py <DIR> media settings.py urls.py __init__.py app.yaml: application: mysite version: 1 runtime: python api_version: 1 handlers: - url: .* script: main.py from settings.py: ROOT_URLCONF = 'mysite.urls' What am I doing wrong? UPDATE: now I get this error: Request Method: GET Request URL: http://localhost:8082/ Exception Type: AttributeError Exception Value: 'module' object has no attribute 'autodiscover' Exception Location: C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py in LoadModuleRestricted, line 1782 main.py: import logging, os # Google App Engine imports. from google.appengine.ext.webapp import util # Force Django to reload its settings. from django.conf import settings settings._target = None # Must set this env var before importing any part of Django # 'project' is the name of the project created with django-admin.py os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' import logging import django.core.handlers.wsgi import django.core.signals import django.db import django.dispatch.dispatcher def log_exception(*args, **kwds): logging.exception('Exception in request:') # Log errors. django.dispatch.dispatcher.connect( log_exception, django.core.signals.got_request_exception) # Unregister the rollback event handler. django.dispatch.dispatcher.disconnect( django.db._rollback_on_exception, django.core.signals.got_request_exception) def main(): # Create a Django application for WSGI. application = django.core.handlers.wsgi.WSGIHandler() # Run the WSGI CGI handler with that application. util.run_wsgi_app(application) if __name__ == '__main__': main() Directory structure of engineapp/: <DIR> mysite app.yaml index.yaml main.py Directory structure of engineapp/mysite: <DIR> myapp <DIR> media __init__.py initial_data.json manage.py settings.py urls.py I feel like I'm getting closer, but still not there.
[ "Try changing ROOT_URLCONF to just 'urls'. I don't think the parent directory of your app (in the App Engine sense, not the Django sense) directory is on sys.path when running on App Engine, which means that it doesn't see mysite as a Python package/module.\nEDIT to keep up with edited question:\nNow it sounds like you're inadvertently using Django 0.96 but expecting to use Django 1.1+. When you import django on App Engine, you will end up with 0.96 unless you explicitly tell App Engine you want to use a different version.\nSomething like\nfrom google.appengine.dist import use_library\nuse_library('django', '1.1')\n\nfrom jonmiddleton's answer should do the trick. Please note that in order to use this on the development server, you must have your own copy of Django 1.1 installed, because it's not bundled with the SDK.\nPlease also note that, as far as I know, you're not going to have any luck using the Django admin site on App Engine.\n", "Here is my main.py:\nimport os\nimport sys\nimport logging\n\n# Google App Hosting imports.\nfrom google.appengine.ext.webapp import util\nfrom google.appengine.dist import use_library\n\nos.environ[\"DJANGO_SETTINGS_MODULE\"] = \"mysite.settings\"\nsys.path.append(\"/home/brox/tmp/mysite\")\n\nuse_library('django', '1.1')\n\n# Enable info logging by the app (this is separate from appserver's\n# logging).\nlogging.getLogger().setLevel(logging.DEBUG)\n\ndef log_exception(*args, **kwds):\n logging.exception('Exception in request:')\n\n# Force sys.path to have our own directory first, so we can import from it.\nsys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))\n\n# Force Django to reload its settings.\nfrom django.conf import settings\nsettings._target = None\n\nimport django.core.handlers.wsgi\nimport django.core.signals\nimport django.db\n\n# Log errors.\ndjango.dispatch.Signal.connect(\n django.core.signals.got_request_exception, log_exception)\n\n# Unregister the rollback event handler.\ndjango.dispatch.Signal.disconnect(\ndjango.core.signals.got_request_exception,\ndjango.db._rollback_on_exception)\n\ndef main(): \n # Create a Django application for WSGI.\n application = django.core.handlers.wsgi.WSGIHandler()\n\n # Run the WSGI CGI handler with that application.\n util.run_wsgi_app(application)\n\nif __name__ == \"__main__\":\n main()\n\nAs you can see there are additional paths and the django error logging is a bit different...\nHope that it helps you.\n", "I haven't used pure django with appengine. But from what I've read you need the djangoappengine-patch to make it work. You can read about it and download it from http://www.allbuttonspressed.com/projects.\n" ]
[ 2, 1, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0002861024_django_google_app_engine_python.txt
Q: How to format date when I load data from google-app-engine? I use remote_api to load data from Google App Engine. appcfg.py download_data --config_file=helloworld/GreetingLoad.py --filename=a.csv --kind=Greeting helloworld The setting is: class AlbumExporter(bulkloader.Exporter): def __init__(self): bulkloader.Exporter.__init__(self, 'Greeting', [('author', str, None), ('content', str, None), ('date', str, None), ]) exporters = [AlbumExporter] And I download a.csv. The date is not readable. How to get the full date? I changed this: class AlbumExporter(bulkloader.Exporter): def __init__(self): bulkloader.Exporter.__init__(self, 'Greeting', [('author', str, None), ('content', str, None), ('date', lambda x: datetime.datetime.strptime(x, '%m/%d/%Y').date(), None), ]) exporters = [AlbumExporter] However, I am still getting an error. A: Looks like you're getting a truncation at the space in the third column when you say ('date', str, None), (the other attempt is clearly wrong because you're getting a datetime and you can't strptime that!-). If you want the date as a string, try: ('date', lambda dt: str(dt.date()), None), or, change strptime to strftime in your second attempt. Mnemonic: the f in strftime stands for format: take a datetime and format it to a string; the p in strptime stands for parse: take a string and make a datetime out of it. They're old names, coming from the standard library for ANSI C (and even-earlier influences on it)...
How to format date when I load data from google-app-engine?
I use remote_api to load data from Google App Engine. appcfg.py download_data --config_file=helloworld/GreetingLoad.py --filename=a.csv --kind=Greeting helloworld The setting is: class AlbumExporter(bulkloader.Exporter): def __init__(self): bulkloader.Exporter.__init__(self, 'Greeting', [('author', str, None), ('content', str, None), ('date', str, None), ]) exporters = [AlbumExporter] And I download a.csv. The date is not readable. How to get the full date? I changed this: class AlbumExporter(bulkloader.Exporter): def __init__(self): bulkloader.Exporter.__init__(self, 'Greeting', [('author', str, None), ('content', str, None), ('date', lambda x: datetime.datetime.strptime(x, '%m/%d/%Y').date(), None), ]) exporters = [AlbumExporter] However, I am still getting an error.
[ "Looks like you're getting a truncation at the space in the third column when you say\n('date', str, None),\n\n(the other attempt is clearly wrong because you're getting a datetime and you can't strptime that!-). If you want the date as a string, try:\n('date', lambda dt: str(dt.date()), None),\n\nor, change strptime to strftime in your second attempt. Mnemonic: the f in strftime stands for format: take a datetime and format it to a string; the p in strptime stands for parse: take a string and make a datetime out of it. They're old names, coming from the standard library for ANSI C (and even-earlier influences on it)...\n" ]
[ 1 ]
[]
[]
[ "format", "google_app_engine", "load", "python" ]
stackoverflow_0002862460_format_google_app_engine_load_python.txt
Q: Estimating the boundary of arbitrarily distributed data I have two dimensional discrete spatial data. I would like to make an approximation of the spatial boundaries of this data so that I can produce a plot with another dataset on top of it. Ideally, this would be an ordered set of (x,y) points that matplotlib can plot with the plt.Polygon() patch. My initial attempt is very inelegant: I place a fine grid over the data, and where data is found in a cell, a square matplotlib patch is created of that cell. The resolution of the boundary thus depends on the sampling frequency of the grid. Here is an example, where the grey region are the cells containing data, black where no data exists. 1st attempt http://astro.dur.ac.uk/~dmurphy/data_limits.png OK, problem solved - why am I still here? Well.... I'd like a more "elegant" solution, or at least one that is faster (ie. I don't want to get on with "real" work, I'd like to have some fun with this!). The best way I can think of is a ray-tracing approach - eg: from xmin to xmax, at y=ymin, check if data boundary crossed in intervals dx y=ymin+dy, do 1 do 1-2, but now sample in y An alternative is defining a centre, and sampling in r-theta space - ie radial spokes in dtheta increments. Both would produce a set of (x,y) points, but then how do I order/link neighbouring points them to create the boundary? A nearest neighbour approach is not appropriate as, for example (to borrow from Geography), an isthmus (think of Panama connecting N&S America) could then close off and isolate regions. This also might not deal very well with the holes seen in the data, which I would like to represent as a different plt.Polygon. The solution perhaps comes from solving an area maximisation problem. For a set of points defining the data limits, what is the maximum contiguous area contained within those points To form the enclosed area, what are the neighbouring points for the nth point? How will the holes be treated in this scheme - is this erring into topology now? Apologies, much of this is me thinking out loud. I'd be grateful for some hints, suggestions or solutions. I suspect this is an oft-studied problem with many solution techniques, but I'm looking for something simple to code and quick to run... I guess everyone is, really! ~~~~~~~~~~~~~~~~~~~~~~~~~ OK, here's attempt #2 using Mark's idea of convex hulls: alt text http://astro.dur.ac.uk/~dmurphy/data_limitsv2.png For this I used qconvex from the qhull package, getting it to return the extreme vertices. For those interested: cat [data] | qconvex Fx > out The sampling of the perimeter seems quite low, and although I haven't played much with the settings, I'm not convinced I can improve the fidelity. A: I think what you are looking for is the Convex Hull of the data That will give a set of points that if connected will mean that all your points are on or inside the connected points A: I may have mixed something, but what's the motivation for simply not determining the maximum and minimum x and y level? Unless you have an enormous amount of data you could simply iterate through your points determining minimum and maximum levels fairly quickly. This isn't the most efficient example, but if your data set is small this won't be particularly slow: import random data = [(random.randint(-100, 100), random.randint(-100, 100)) for i in range(1000)] x_min = min([point[0] for point in data]) x_max = max([point[0] for point in data]) y_min = min([point[1] for point in data]) y_max = max([point[1] for point in data])
Estimating the boundary of arbitrarily distributed data
I have two dimensional discrete spatial data. I would like to make an approximation of the spatial boundaries of this data so that I can produce a plot with another dataset on top of it. Ideally, this would be an ordered set of (x,y) points that matplotlib can plot with the plt.Polygon() patch. My initial attempt is very inelegant: I place a fine grid over the data, and where data is found in a cell, a square matplotlib patch is created of that cell. The resolution of the boundary thus depends on the sampling frequency of the grid. Here is an example, where the grey region are the cells containing data, black where no data exists. 1st attempt http://astro.dur.ac.uk/~dmurphy/data_limits.png OK, problem solved - why am I still here? Well.... I'd like a more "elegant" solution, or at least one that is faster (ie. I don't want to get on with "real" work, I'd like to have some fun with this!). The best way I can think of is a ray-tracing approach - eg: from xmin to xmax, at y=ymin, check if data boundary crossed in intervals dx y=ymin+dy, do 1 do 1-2, but now sample in y An alternative is defining a centre, and sampling in r-theta space - ie radial spokes in dtheta increments. Both would produce a set of (x,y) points, but then how do I order/link neighbouring points them to create the boundary? A nearest neighbour approach is not appropriate as, for example (to borrow from Geography), an isthmus (think of Panama connecting N&S America) could then close off and isolate regions. This also might not deal very well with the holes seen in the data, which I would like to represent as a different plt.Polygon. The solution perhaps comes from solving an area maximisation problem. For a set of points defining the data limits, what is the maximum contiguous area contained within those points To form the enclosed area, what are the neighbouring points for the nth point? How will the holes be treated in this scheme - is this erring into topology now? Apologies, much of this is me thinking out loud. I'd be grateful for some hints, suggestions or solutions. I suspect this is an oft-studied problem with many solution techniques, but I'm looking for something simple to code and quick to run... I guess everyone is, really! ~~~~~~~~~~~~~~~~~~~~~~~~~ OK, here's attempt #2 using Mark's idea of convex hulls: alt text http://astro.dur.ac.uk/~dmurphy/data_limitsv2.png For this I used qconvex from the qhull package, getting it to return the extreme vertices. For those interested: cat [data] | qconvex Fx > out The sampling of the perimeter seems quite low, and although I haven't played much with the settings, I'm not convinced I can improve the fidelity.
[ "I think what you are looking for is the Convex Hull of the data That will give a set of points that if connected will mean that all your points are on or inside the connected points\n", "I may have mixed something, but what's the motivation for simply not determining the maximum and minimum x and y level? Unless you have an enormous amount of data you could simply iterate through your points determining minimum and maximum levels fairly quickly.\nThis isn't the most efficient example, but if your data set is small this won't be particularly slow: \nimport random\ndata = [(random.randint(-100, 100), random.randint(-100, 100)) for i in range(1000)]\n\nx_min = min([point[0] for point in data])\nx_max = max([point[0] for point in data])\n\ny_min = min([point[1] for point in data])\ny_max = max([point[1] for point in data])\n\n" ]
[ 2, 0 ]
[]
[]
[ "python", "sampling", "spatial" ]
stackoverflow_0002856222_python_sampling_spatial.txt
Q: Show escaped string as Unicode in Python i have just known Python for few days. Unicode seems to be a problem with Python. i have a text file stores a text string like this '\u0110\xe8n \u0111\u1ecf n\xfat giao th\xf4ng Ng\xe3 t\u01b0 L\xe1ng H\u1ea1' i can read the file and print the string out but it displays incorrectly. How can i print it out to screen correctly as follow: "Đèn đỏ nút giao thông Ngã tư Láng Hạ" Thanks in advance A: >>> x=r'\u0110\xe8n \u0111\u1ecf n\xfat giao th\xf4ng Ng\xe3 t\u01b0 L\xe1ng H\u1ea1' >>> u=unicode(x, 'unicode-escape') >>> print u Đèn đỏ nút giao thông Ngã tư Láng Hạ This works in a Mac, where Terminal.App correctly makes sys.stdout.encoding be set to utf-8. If your platform doesn't set that attribute correctly (or at all), you'll need to replace the last line with print u.decode('utf8') or whatever other encoding your terminal/console is using. Note that in the first line I assign a raw string literal so that the "escape sequences" would not be expanded -- that just mimics what would happen if bytestring x was being read from a (text or binary) file with that literal content. A: It helps to show a simple example with code and output what you have explicitly tried. At a guess your console doesn't support Vietnamese. Here are some options: # A byte string with Unicode escapes as text. >>> x='\u0110\xe8n \u0111\u1ecf n\xfat giao th\xf4ng Ng\xe3 t\u01b0 L\xe1ng H\u1ea1' # Convert to Unicode string. >>> x=x.decode('unicode-escape') >>> x u'\u0110\xe8n \u0111\u1ecf n\xfat giao th\xf4ng Ng\xe3 t\u01b0 L\xe1ng H\u1ea1' # Try to print to my console: >>> print x Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\dev\python\lib\encodings\cp437.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character u'\u0110' in position 0: character maps to <undefined> # My console's encoding is cp437. # Instead of the default strict error handling that throws exceptions, try: >>> print x.encode('cp437','replace') ?èn ?? nút giao thông Ng? t? Láng H? # Six characters weren't supported. # Here's a way to write the text to a temp file and display it with another # program that supports the UTF-8 encoding: >>> import tempfile >>> f,name=tempfile.mkstemp() >>> import os >>> os.write(f,x.encode('utf8')) 48 >>> os.close(f) >>> os.system('notepad.exe '+name) Hope that helps you. A: Try this >>> s=u"\u0110\xe8n \u0111\u1ecf n\xfat giao th\xf4ng Ng\xe3 t\u01b0 L\xe1ng H\u1ea1" >>> print s => Đèn đỏ nút giao thông Ngã tư Láng Hạ
Show escaped string as Unicode in Python
i have just known Python for few days. Unicode seems to be a problem with Python. i have a text file stores a text string like this '\u0110\xe8n \u0111\u1ecf n\xfat giao th\xf4ng Ng\xe3 t\u01b0 L\xe1ng H\u1ea1' i can read the file and print the string out but it displays incorrectly. How can i print it out to screen correctly as follow: "Đèn đỏ nút giao thông Ngã tư Láng Hạ" Thanks in advance
[ ">>> x=r'\\u0110\\xe8n \\u0111\\u1ecf n\\xfat giao th\\xf4ng Ng\\xe3 t\\u01b0 L\\xe1ng H\\u1ea1'\n>>> u=unicode(x, 'unicode-escape')\n>>> print u\nĐèn đỏ nút giao thông Ngã tư Láng Hạ\n\nThis works in a Mac, where Terminal.App correctly makes sys.stdout.encoding be set to utf-8. If your platform doesn't set that attribute correctly (or at all), you'll need to replace the last line with\nprint u.decode('utf8')\n\nor whatever other encoding your terminal/console is using.\nNote that in the first line I assign a raw string literal so that the \"escape sequences\" would not be expanded -- that just mimics what would happen if bytestring x was being read from a (text or binary) file with that literal content.\n", "It helps to show a simple example with code and output what you have explicitly tried. At a guess your console doesn't support Vietnamese. Here are some options:\n# A byte string with Unicode escapes as text.\n>>> x='\\u0110\\xe8n \\u0111\\u1ecf n\\xfat giao th\\xf4ng Ng\\xe3 t\\u01b0 L\\xe1ng H\\u1ea1'\n\n# Convert to Unicode string.\n>>> x=x.decode('unicode-escape')\n>>> x\nu'\\u0110\\xe8n \\u0111\\u1ecf n\\xfat giao th\\xf4ng Ng\\xe3 t\\u01b0 L\\xe1ng H\\u1ea1'\n\n# Try to print to my console:\n>>> print x\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"C:\\dev\\python\\lib\\encodings\\cp437.py\", line 12, in encode\n return codecs.charmap_encode(input,errors,encoding_map)\nUnicodeEncodeError: 'charmap' codec can't encode character u'\\u0110' in position 0:\n character maps to <undefined>\n\n# My console's encoding is cp437.\n# Instead of the default strict error handling that throws exceptions, try:\n>>> print x.encode('cp437','replace')\n?èn ?? nút giao thông Ng? t? Láng H? \n\n# Six characters weren't supported.\n# Here's a way to write the text to a temp file and display it with another\n# program that supports the UTF-8 encoding:\n>>> import tempfile\n>>> f,name=tempfile.mkstemp()\n>>> import os\n>>> os.write(f,x.encode('utf8'))\n48\n>>> os.close(f)\n>>> os.system('notepad.exe '+name)\n\nHope that helps you.\n", "Try this\n>>> s=u\"\\u0110\\xe8n \\u0111\\u1ecf n\\xfat giao th\\xf4ng Ng\\xe3 t\\u01b0 L\\xe1ng H\\u1ea1\"\n>>> print s\n=> Đèn đỏ nút giao thông Ngã tư Láng Hạ\n\n" ]
[ 8, 1, 0 ]
[]
[]
[ "escaping", "python", "unicode" ]
stackoverflow_0002855661_escaping_python_unicode.txt
Q: I'm searching for a messaging platform (like XMPP) that allows tight integration with a web application At the company I work for, we are building a cluster of web applications for collaboration. Things like accounting, billing, CRM etc. We are using a RESTfull technique: For database we use CouchDB Different applications communicate with one another and with the database via http. Besides, we have a single sign on solution, so that when you login in one application, you are automatically logged to the other. For all apps we use Python (Pylons). Now we need to add instant messaging to the stack. We need to support both web and desktop clients. But just being able to chat is not enough. We need to be able to achieve all of the following (and more similar things). When somebody gets assigned to a task, they must receive a message. I guess this is possible with some system daemon. There must be an option to automatically group people in groups by lots of different properties. For example, there must be groups divided both by geographical location, by company division, by job type (all the programers from different cities and different company divisions must form a group), so that one can send mass messages to a group of choice. Rooms should be automatically created and destroyed. For example when several people visit the same invoice, a room for them must be automatically created (and they must auto-join). And when all leave the invoice, the room must be destroyed. Authentication and authorization from our applications. I can implement this using custom solutions like hookbox http://hookbox.org/docs/intro.html but then I'll have lots of problems in supporting desktop clients. I have no former experience with instant messaging. I've been reading about this lately. I've been looking mostly at things like ejabberd. But it has been a hard time and I can't find whether what I want is possible at all. So I'd be happy if people with experience in this field could help me with some advice, articles, tales of what is possible etc. A: Like frx suggested above, the StropheJS folks have an excellent book about web+xmpp coding but since you mentioned you have no experience in this type of coding I would suggest talking to some folks who have :) It will save you time in the long run - not that I'm saying don't try to implement what frx outlines, it could be a fun project :) I know of one group who has implemented something similar and chatting with them would help solidify what you have in mind: http://andyet.net/ (I'm not affiliated with them at all except for the fact that the XMPP dev community is small and we tend to know each other :) A: All goals could be achieved with ejabberd, strophe and little server side scripting When someone gets assigned to task, server side script could easily authenticate to xmpp server and send message stanza to assigned JID. That its trivial task. To group different people in groups, it is easily can be done from web chat app if those user properties are stored somewhere. Just join them in particular multi user chat room after authentication. Ejabberd has option to automatically create and destroy rooms. Ejabberd has various authorization methods including database and script auth You could take look at StropheJS library, they have great book (paperback) released. Really recommend to read this book http://professionalxmpp.com/
I'm searching for a messaging platform (like XMPP) that allows tight integration with a web application
At the company I work for, we are building a cluster of web applications for collaboration. Things like accounting, billing, CRM etc. We are using a RESTfull technique: For database we use CouchDB Different applications communicate with one another and with the database via http. Besides, we have a single sign on solution, so that when you login in one application, you are automatically logged to the other. For all apps we use Python (Pylons). Now we need to add instant messaging to the stack. We need to support both web and desktop clients. But just being able to chat is not enough. We need to be able to achieve all of the following (and more similar things). When somebody gets assigned to a task, they must receive a message. I guess this is possible with some system daemon. There must be an option to automatically group people in groups by lots of different properties. For example, there must be groups divided both by geographical location, by company division, by job type (all the programers from different cities and different company divisions must form a group), so that one can send mass messages to a group of choice. Rooms should be automatically created and destroyed. For example when several people visit the same invoice, a room for them must be automatically created (and they must auto-join). And when all leave the invoice, the room must be destroyed. Authentication and authorization from our applications. I can implement this using custom solutions like hookbox http://hookbox.org/docs/intro.html but then I'll have lots of problems in supporting desktop clients. I have no former experience with instant messaging. I've been reading about this lately. I've been looking mostly at things like ejabberd. But it has been a hard time and I can't find whether what I want is possible at all. So I'd be happy if people with experience in this field could help me with some advice, articles, tales of what is possible etc.
[ "Like frx suggested above, the StropheJS folks have an excellent book about web+xmpp coding but since you mentioned you have no experience in this type of coding I would suggest talking to some folks who have :) It will save you time in the long run - not that I'm saying don't try to implement what frx outlines, it could be a fun project :)\nI know of one group who has implemented something similar and chatting with them would help solidify what you have in mind: http://andyet.net/ (I'm not affiliated with them at all except for the fact that the XMPP dev community is small and we tend to know each other :)\n", "All goals could be achieved with ejabberd, strophe and little server side scripting\n\nWhen someone gets assigned to task, server side script could easily authenticate to xmpp server and send message stanza to assigned JID. That its trivial task.\nTo group different people in groups, it is easily can be done from web chat app if those user properties are stored somewhere. Just join them in particular multi user chat room after authentication.\nEjabberd has option to automatically create and destroy rooms.\nEjabberd has various authorization methods including database and script auth\n\nYou could take look at StropheJS library, they have great book (paperback) released. Really recommend to read this book http://professionalxmpp.com/\n" ]
[ 1, 0 ]
[]
[]
[ "couchdb", "ejabberd", "pylons", "python", "xmpp" ]
stackoverflow_0002833957_couchdb_ejabberd_pylons_python_xmpp.txt
Q: How do I get the Math equation of Python Algorithm? ok so I am feeling a little stupid for not knowing this, but a coworker asked so I am asking here: I have written a python algorithm that solves his problem. given x > 0 add all numbers together from 1 to x. def intsum(x): if x > 0: return x + intsum(x - 1) else: return 0 intsum(10) 55 first what is this type of equation is this and what is the correct way to get this answer as it is clearly easier using some other method? A: This is recursion, though for some reason you're labeling it like it's factorial. In any case, the sum from 1 to n is also simply: n * ( n + 1 ) / 2 (You can special case it for negative values if you like.) A: Transforming recursively-defined sequences of integers into ones that can be expressed in a closed form is a fascinating part of discrete mathematics -- I heartily recommend Concrete Mathematics: A Foundation for Computer Science, by Ronald Graham, Donald Knuth, and Oren Patashnik (see. e.g. the wikipedia entry about it). However, the specific sequence you show, fac(x) = fac(x - 1) + x, according to a famous anecdote, was solved by Gauss when he was a child in first grade -- the teacher had given the pupils the taksk of summing numbers from 1 to 100 to keep them quet for a while, but two minutes later there was young Gauss with the answer, 5050, and the explanation: "I noticed that I can sum the first, 1, and the last, 100, that's 101; and the second, 2, and the next-to-last, 99, and that's again 101; and clearly that repeats 50 times, so, 50 times 101, 5050". Not rigorous as proofs go, but quite correct and appropriate for a 6-years-old;-). In the same way (plus really elementary algebra) you can see that the general case is, as many have already said, (N * (N+1)) / 2 (the product is always even, since one of the numbers must be odd and one even; so the division by two will always produce an integer, as desired, with no remainder). A: Here is how to prove the closed form for an arithmetic progression S = 1 + 2 + ... + (n-1) + n S = n + (n-1) + ... + 2 + 1 2S = (n+1) + (n+1) + ... + (n+1) + (n+1) ^ you'll note that there are n terms there. 2S = n(n+1) S = n(n+1)/2 A: Larry is very correct with his formula, and its the fastest way to calculate the sum of all integers up to n. But for completeness, there are built-in Python functions, that perform what you have done, on lists with arbitrary elements. E.g. sum() >>> sum(range(11)) 55 >>> sum([2,4,6]) 12 or more general, reduce() >>> import operator >>> reduce(operator.add, range(11)) 55 A: I'm not allowed to comment yet so I'll just add that you'll want to be careful in using range() as it's 0 base. You'll need to use range(n+1) to get the desired effect. Sorry for the duplication... sum(range(10)) != 55 sum(range(11)) == 55 A: OP has asked, in a comment, for a link to the story about Gauss as a schoolchild. He may want to check out this fascinating article by Brian Hayes. It not only rather convincingly suggests that the Gauss story may be a modern fabrication, but outlines how it would be rather difficult not to see the patterns involved in summing the numbers from 1 to 100. That in fact the only way to miss these patterns would be to solve the problem by writing a program. The article also talks about different ways to sum arithmetic progressions, which is at the heart of OP's question. There is also an ad-free version here. A: Consider that N+1, N-1+2, N-2+3, and so on all add up to the same number, and there are approximately N/2 instances like that (exactly N/2 if N is even). A: What you have there is called arithmetic sequence and as suggested, you can compute it directly without overhead which might result from the recursion. And I would say this is a homework despite what you say.
How do I get the Math equation of Python Algorithm?
ok so I am feeling a little stupid for not knowing this, but a coworker asked so I am asking here: I have written a python algorithm that solves his problem. given x > 0 add all numbers together from 1 to x. def intsum(x): if x > 0: return x + intsum(x - 1) else: return 0 intsum(10) 55 first what is this type of equation is this and what is the correct way to get this answer as it is clearly easier using some other method?
[ "This is recursion, though for some reason you're labeling it like it's factorial.\nIn any case, the sum from 1 to n is also simply: \nn * ( n + 1 ) / 2\n(You can special case it for negative values if you like.)\n", "Transforming recursively-defined sequences of integers into ones that can be expressed in a closed form is a fascinating part of discrete mathematics -- I heartily recommend Concrete Mathematics: A Foundation for Computer Science, by Ronald Graham, Donald Knuth, and Oren Patashnik (see. e.g. the wikipedia entry about it).\nHowever, the specific sequence you show, fac(x) = fac(x - 1) + x, according to a famous anecdote, was solved by Gauss when he was a child in first grade -- the teacher had given the pupils the taksk of summing numbers from 1 to 100 to keep them quet for a while, but two minutes later there was young Gauss with the answer, 5050, and the explanation: \"I noticed that I can sum the first, 1, and the last, 100, that's 101; and the second, 2, and the next-to-last, 99, and that's again 101; and clearly that repeats 50 times, so, 50 times 101, 5050\". Not rigorous as proofs go, but quite correct and appropriate for a 6-years-old;-).\nIn the same way (plus really elementary algebra) you can see that the general case is, as many have already said, (N * (N+1)) / 2 (the product is always even, since one of the numbers must be odd and one even; so the division by two will always produce an integer, as desired, with no remainder).\n", "Here is how to prove the closed form for an arithmetic progression\nS = 1 + 2 + ... + (n-1) + n\nS = n + (n-1) + ... + 2 + 1\n2S = (n+1) + (n+1) + ... + (n+1) + (n+1)\n ^ you'll note that there are n terms there.\n2S = n(n+1)\nS = n(n+1)/2\n\n", "Larry is very correct with his formula, and its the fastest way to calculate the sum of all integers up to n.\nBut for completeness, there are built-in Python functions, that perform what you have done, on lists with arbitrary elements. E.g.\n\nsum()\n>>> sum(range(11))\n55\n>>> sum([2,4,6])\n12\n\nor more general, reduce()\n>>> import operator\n>>> reduce(operator.add, range(11))\n55\n\n\n", "I'm not allowed to comment yet so I'll just add that you'll want to be careful in using range() as it's 0 base. You'll need to use range(n+1) to get the desired effect.\nSorry for the duplication...\nsum(range(10)) != 55\nsum(range(11)) == 55\n", "OP has asked, in a comment, for a link to the story about Gauss as a schoolchild.\nHe may want to check out this fascinating article by Brian Hayes. It not only rather convincingly suggests that the Gauss story may be a modern fabrication, but outlines how it would be rather difficult not to see the patterns involved in summing the numbers from 1 to 100. That in fact the only way to miss these patterns would be to solve the problem by writing a program.\nThe article also talks about different ways to sum arithmetic progressions, which is at the heart of OP's question. There is also an ad-free version here.\n", "Consider that N+1, N-1+2, N-2+3, and so on all add up to the same number, and there are approximately N/2 instances like that (exactly N/2 if N is even).\n", "What you have there is called arithmetic sequence and as suggested, you can compute it directly without overhead which might result from the recursion.\nAnd I would say this is a homework despite what you say.\n" ]
[ 15, 8, 4, 3, 3, 3, 1, 1 ]
[]
[]
[ "algorithm", "math", "python" ]
stackoverflow_0002861996_algorithm_math_python.txt
Q: Replacing empty csv column values with a zero So I'm dealing with a csv file that has missing values. What I want my script to is: #!/usr/bin/python import csv import sys #1. Place each record of a file in a list. #2. Iterate thru each element of the list and get its length. #3. If the length is less than one replace with value x. reader = csv.reader(open(sys.argv[1], "rb")) for row in reader: for x in row[:]: if len(x)< 1: x = 0 print x print row Here is an example of data, I trying it on, ideally it should work on any column lenghth Before: actnum,col2,col4 xxxxx , , xxxxx , 845 , xxxxx , ,545 After actnum,col2,col4 xxxxx , 0 , 0 xxxxx , 845, 0 xxxxx , 0 ,545 Any guidance would be appreciated Update Here is what I have now (thanks): reader = csv.reader(open(sys.argv[1], "rb")) for row in reader: for i, x in enumerate(row): if len(x)< 1: x = row[i] = 0 print row However it only seems to out put one record, I will be piping the output to a new file on the command line. Update 3: Ok now I have the opposite problem, I'm outputting duplicates of each records. Why is that happening? After actnum,col2,col4 actnum,col2,col4 xxxxx , 0 , 0 xxxxx , 0 , 0 xxxxx , 845, 0 xxxxx , 845, 0 xxxxx , 0 ,545 xxxxx , 0 ,545 Ok I fixed it (below) thanks you guys for your help. #!/usr/bin/python import csv import sys #1. Place each record of a file in a list. #2. Iterate thru each element of the list and get its length. #3. If the length is less than one replace with value x. reader = csv.reader(open(sys.argv[1], "rb")) for row in reader: for i, x in enumerate(row): if len(x)< 1: x = row[i] = 0 print ','.join(str(x) for x in row) A: Change your code: for row in reader: for x in row[:]: if len(x)< 1: x = 0 print x into: for row in reader: for i, x in enumerate(row): if len(x)< 1: x = row[i] = 0 print x Not sure what you think you're accomplishing by the print, but the key issue is that you need to modify row, and for that purpose you need an index into it, which enumerate gives you. Note also that all other values, except the empty ones which you're changing into the number 0, will remain strings. If you want to turn them into ints you have to do that explicitly. A: You are very nearly there! There are just a couple of small bugs. len(x)< 1 will not work for the second column in the second row of your data because x will contain ' ' (and have a length > 1). You'll need to strip your strings. print row will probably print an empty list because you've finished iterating. You can probably just remove this line. Also: Are you trying to modify the file or just output the corrections to pipe to some other file or process?
Replacing empty csv column values with a zero
So I'm dealing with a csv file that has missing values. What I want my script to is: #!/usr/bin/python import csv import sys #1. Place each record of a file in a list. #2. Iterate thru each element of the list and get its length. #3. If the length is less than one replace with value x. reader = csv.reader(open(sys.argv[1], "rb")) for row in reader: for x in row[:]: if len(x)< 1: x = 0 print x print row Here is an example of data, I trying it on, ideally it should work on any column lenghth Before: actnum,col2,col4 xxxxx , , xxxxx , 845 , xxxxx , ,545 After actnum,col2,col4 xxxxx , 0 , 0 xxxxx , 845, 0 xxxxx , 0 ,545 Any guidance would be appreciated Update Here is what I have now (thanks): reader = csv.reader(open(sys.argv[1], "rb")) for row in reader: for i, x in enumerate(row): if len(x)< 1: x = row[i] = 0 print row However it only seems to out put one record, I will be piping the output to a new file on the command line. Update 3: Ok now I have the opposite problem, I'm outputting duplicates of each records. Why is that happening? After actnum,col2,col4 actnum,col2,col4 xxxxx , 0 , 0 xxxxx , 0 , 0 xxxxx , 845, 0 xxxxx , 845, 0 xxxxx , 0 ,545 xxxxx , 0 ,545 Ok I fixed it (below) thanks you guys for your help. #!/usr/bin/python import csv import sys #1. Place each record of a file in a list. #2. Iterate thru each element of the list and get its length. #3. If the length is less than one replace with value x. reader = csv.reader(open(sys.argv[1], "rb")) for row in reader: for i, x in enumerate(row): if len(x)< 1: x = row[i] = 0 print ','.join(str(x) for x in row)
[ "Change your code:\nfor row in reader:\n for x in row[:]:\n if len(x)< 1:\n x = 0\n print x\n\ninto:\nfor row in reader:\n for i, x in enumerate(row):\n if len(x)< 1:\n x = row[i] = 0\n print x\n\nNot sure what you think you're accomplishing by the print, but the key issue is that you need to modify row, and for that purpose you need an index into it, which enumerate gives you.\nNote also that all other values, except the empty ones which you're changing into the number 0, will remain strings. If you want to turn them into ints you have to do that explicitly.\n", "You are very nearly there!\nThere are just a couple of small bugs.\n\nlen(x)< 1 will not work for the second column in the second row of your data because x will contain ' ' (and have a length > 1). You'll need to strip your strings.\nprint row will probably print an empty list because you've finished iterating. You can probably just remove this line.\n\nAlso: Are you trying to modify the file or just output the corrections to pipe to some other file or process?\n" ]
[ 4, 1 ]
[]
[]
[ "csv", "list", "python" ]
stackoverflow_0002862709_csv_list_python.txt
Q: How to pass variables using Unittest suite Hello I have test's using unittest. I have a test suite and I am trying to pass variables through into each of the tests. The below code shows the test suite used. class suite(): def suite(self): #Function stores all the modules to be tested modules_to_test = ('testmodule1', 'testmodule2') alltests = unittest.TestSuite() for module in map(__import__, modules_to_test): alltests.addTest(unittest.findTestCases(module)) return alltests It calls tests, I would like to know how to pass variables into the tests from this class. An example test script is below: class TestThis(unittest.TestCase): def runTest(self): assertEqual('1', '1') class TestThisTestSuite(unittest.TestSuite): # Tests to be tested by test suite def makeTestThisTestSuite(): suite = unittest.TestSuite() suite.addTest("TestThis") return suite def suite(): return unittest.makeSuite(TestThis) if __name__ == '__main__': unittest.main() So from the class suite() I would like to enter in a value to change the value that is in assert value. Eg. assertEqual(self.value, '1'). I have tried sys.argv for unittest and it doesn't seem to work. Thanks for any help. A: Passing interactive values on the command line is not really in line with the intention of automated unit tests. How about using the ConfigParser library module and have your TestCase subclass's __init__ method load some variable test input data that way? Of course, sticking with the code you have, what about either module global variables or class constant members to hold your test data? For example, after you import a test module by name, couldn't you just do module.testVars = [1, 2, 3, "foo"] And have the tests in the test modules reference that variable (which might be an empty list by default)?
How to pass variables using Unittest suite
Hello I have test's using unittest. I have a test suite and I am trying to pass variables through into each of the tests. The below code shows the test suite used. class suite(): def suite(self): #Function stores all the modules to be tested modules_to_test = ('testmodule1', 'testmodule2') alltests = unittest.TestSuite() for module in map(__import__, modules_to_test): alltests.addTest(unittest.findTestCases(module)) return alltests It calls tests, I would like to know how to pass variables into the tests from this class. An example test script is below: class TestThis(unittest.TestCase): def runTest(self): assertEqual('1', '1') class TestThisTestSuite(unittest.TestSuite): # Tests to be tested by test suite def makeTestThisTestSuite(): suite = unittest.TestSuite() suite.addTest("TestThis") return suite def suite(): return unittest.makeSuite(TestThis) if __name__ == '__main__': unittest.main() So from the class suite() I would like to enter in a value to change the value that is in assert value. Eg. assertEqual(self.value, '1'). I have tried sys.argv for unittest and it doesn't seem to work. Thanks for any help.
[ "Passing interactive values on the command line is not really in line with the intention of automated unit tests. How about using the ConfigParser library module and have your TestCase subclass's __init__ method load some variable test input data that way?\nOf course, sticking with the code you have, what about either module global variables or class constant members to hold your test data? For example, after you import a test module by name, couldn't you just do\nmodule.testVars = [1, 2, 3, \"foo\"]\n\nAnd have the tests in the test modules reference that variable (which might be an empty list by default)?\n" ]
[ 4 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0002812132_python_unit_testing.txt
Q: Inverting image using the Python Image Library module I'm interested in learning how to invert (make a negative of) an image using the python image libary module. I cannot however, use the ImageOps function 'invert.' I need another solution, using the RGB values. I've searched and tried to no avail. A: Just subtract each RGB value from 255 (or the max) to obtain the new RGB values. this post tells you how to get the RBG values from a picture. A: One obvious way is to use Image.getpixel and Image.putpixel, for RGB, each should be a tuple of three integers. You can get (255-r, 255-g, 255-b), then put it back. Or use pix = Image.load(), which seems faster. Or if you look into ImageOps.py, it's using a lookup table (lut list) to map an image to an inverted one. Or if it's not against the rules of your assignment, you may use Numpy. Then you can use the faster matrix operation. A: If you are working with the media module, then you could do this: import media def invert(): filename = media.choose_file() # opens a select file dialog pic = media.load_picture(filename) # converts the picture file into a "picture" as recognized by the module. for pixel in pic: media.set_red(pixel, 255-media.get_red(pixel)) # the inverting algorithm as suggested by @Dingle media.set_green(pixel, 255-media.get_green(pixel)) media.set_blue(pixel, 255-media.get_blue(pixel)) print 'Done!' The process is similar if you are using the picture module, and looks like this: import picture def invert(): filename = picture.pick_a_file() # opens a select file dialog pic = picture.make_picture(filename) # converts the picture file into a "picture" as recognized by the module. for pixel in picture.get_pixels(pic): picture.set_red(pixel, 255-picture.get_red(pixel)) # the inverting algorithm as suggested by @Dingle picture.set_green(pixel, 255-picture.get_green(pixel)) picture.set_blue(pixel, 255-picture.get_blue(pixel)) print 'Done!' Hope this helps
Inverting image using the Python Image Library module
I'm interested in learning how to invert (make a negative of) an image using the python image libary module. I cannot however, use the ImageOps function 'invert.' I need another solution, using the RGB values. I've searched and tried to no avail.
[ "Just subtract each RGB value from 255 (or the max) to obtain the new RGB values.\nthis post tells you how to get the RBG values from a picture.\n", "One obvious way is to use Image.getpixel and Image.putpixel, for RGB, each should be a tuple of three integers. You can get (255-r, 255-g, 255-b), then put it back. \nOr use pix = Image.load(), which seems faster.\nOr if you look into ImageOps.py, it's using a lookup table (lut list) to map an image to an inverted one.\nOr if it's not against the rules of your assignment, you may use Numpy. Then you can use the faster matrix operation.\n", "If you are working with the media module, then you could do this:\nimport media\ndef invert():\n filename = media.choose_file() # opens a select file dialog\n pic = media.load_picture(filename) # converts the picture file into a \"picture\" as recognized by the module.\n for pixel in pic:\n media.set_red(pixel, 255-media.get_red(pixel)) # the inverting algorithm as suggested by @Dingle\n media.set_green(pixel, 255-media.get_green(pixel))\n media.set_blue(pixel, 255-media.get_blue(pixel))\nprint 'Done!'\n\nThe process is similar if you are using the picture module, and looks like this:\nimport picture\ndef invert():\n filename = picture.pick_a_file() # opens a select file dialog\n pic = picture.make_picture(filename) # converts the picture file into a \"picture\" as recognized by the module.\n for pixel in picture.get_pixels(pic):\n picture.set_red(pixel, 255-picture.get_red(pixel)) # the inverting algorithm as suggested by @Dingle\n picture.set_green(pixel, 255-picture.get_green(pixel))\n picture.set_blue(pixel, 255-picture.get_blue(pixel))\nprint 'Done!'\n\nHope this helps\n" ]
[ 0, 0, 0 ]
[]
[]
[ "image_manipulation", "python", "python_imaging_library" ]
stackoverflow_0002862659_image_manipulation_python_python_imaging_library.txt
Q: POSTing a form using Python and Curl I am relatively new (as in a few days) to Python - I am looking for an example that would show me how to post a form to a website (say www.example.com). I already know how to use Curl. Infact, I have written C+++ code that does exactly the same thing (i.e. POST a form using Curl), but I would like some starting point (a few lines from which I can build on), which will show me how to do this using Python. A: Here is an example using urllib and urllib2 for both POST and GET: POST - If urlopen() has a second parameter then it is a POST request. import urllib import urllib2 url = 'http://www.example.com' values = {'var' : 500} data = urllib.urlencode(values) response = urllib2.urlopen(url, data) page = response.read() GET - If urlopen() has a single parameter then it is a GET request. import urllib import urllib2 url = 'http://www.example.com' values = {'var' : 500} data = urllib.urlencode(values) fullurl = url + '?' + data response = urllib2.urlopen(fullurl) page = response.read() You could also use curl if you call it using os.system(). Here are some helpful links: http://docs.python.org/library/urllib2.html#urllib2.urlopen http://docs.python.org/library/os.html#os.system A: curl -d "birthyear=1990&press=AUD" www.site.com/register/user.php http://curl.haxx.se/docs/httpscripting.html A: There are two major Python packages for automating web interactions: Mechanize Twill Twill has apparently not been updated for a couple years and seems to have been at version 0.9 since Dec. 2007. Mechanize shows changelog and releases from just a few days ago: 2010-05-16 with the release of version 0.2.1. Of course you'll find examples listed in their respective web pages. Twill essentially provides a simple shell like interpreter while Mechanize provides a class and API in which you set form values using Python dictionary-like (__setattr__() method) statements, for example. Both use BeautifulSoup for parsing "real world" (sloppy tag soup) HTML. (This is highly recommended for dealing with HTML that you encounter in the wild, and strongly discouraged for your own HTML which should be written to pass standards conforming, validating, parsers).
POSTing a form using Python and Curl
I am relatively new (as in a few days) to Python - I am looking for an example that would show me how to post a form to a website (say www.example.com). I already know how to use Curl. Infact, I have written C+++ code that does exactly the same thing (i.e. POST a form using Curl), but I would like some starting point (a few lines from which I can build on), which will show me how to do this using Python.
[ "Here is an example using urllib and urllib2 for both POST and GET:\nPOST - If urlopen() has a second parameter then it is a POST request.\nimport urllib\nimport urllib2\n\nurl = 'http://www.example.com'\nvalues = {'var' : 500}\n\ndata = urllib.urlencode(values)\nresponse = urllib2.urlopen(url, data)\npage = response.read()\n\nGET - If urlopen() has a single parameter then it is a GET request.\nimport urllib\nimport urllib2\n\nurl = 'http://www.example.com'\nvalues = {'var' : 500}\n\ndata = urllib.urlencode(values)\nfullurl = url + '?' + data\nresponse = urllib2.urlopen(fullurl)\npage = response.read()\n\nYou could also use curl if you call it using os.system().\nHere are some helpful links:\nhttp://docs.python.org/library/urllib2.html#urllib2.urlopen \nhttp://docs.python.org/library/os.html#os.system\n", "curl -d \"birthyear=1990&press=AUD\" www.site.com/register/user.php\n\nhttp://curl.haxx.se/docs/httpscripting.html\n", "There are two major Python packages for automating web interactions:\n\nMechanize\nTwill\nTwill has apparently not been updated for a couple years and seems to have been at version 0.9 since Dec. 2007. Mechanize shows changelog and releases from just a few days ago: 2010-05-16 with the release of version 0.2.1.\nOf course you'll find examples listed in their respective web pages. Twill essentially provides a simple shell like interpreter while Mechanize provides a class and API in which you set form values using Python dictionary-like (__setattr__() method) statements, for example. Both use BeautifulSoup for parsing \"real world\" (sloppy tag soup) HTML. (This is highly recommended for dealing with HTML that you encounter in the wild, and strongly discouraged for your own HTML which should be written to pass standards conforming, validating, parsers).\n\n" ]
[ 2, 0, 0 ]
[]
[]
[ "curl", "python" ]
stackoverflow_0002863260_curl_python.txt
Q: Uploading file from file object with PyCurl I'm attempting to upload a file like this: import pycurl c = pycurl.Curl() values = [ ("name", "tom"), ("image", (pycurl.FORM_FILE, "tom.png")) ] c.setopt(c.URL, "http://upload.com/submit") c.setopt(c.HTTPPOST, values) c.perform() c.close() This works fine. However, this only works if the file is local. If I was to fetch the image such that: import urllib2 resp = urllib2.urlopen("http://upload.com/people/tom.png") How would I pass resp.fp as a file object instead of writing it to a file and passing the filename? Is this possible? A: It might be possible in perfect situations to basically connect the two streams, but it wouldn't be a very robust solution. There are a bunch of ugly boundary conditions: The response socket might still be receiving data, and/or be stalled, thus causing you to starve out and break the POST (because PycURL is not expecting to have to wait for data beyond the current end of the "file"). The response might reset, and then you don't have the complete file, but you've already POSTed a bunch of data - what to do in this case? The file you're fetching with urllib might be chunked-encoded, so you need to perform some operations on the MIME headers for reassembly - you can't just blindly forward the data. You don't necessarily know how big the file you're getting is, so it's hard to provide the proper content-length on the POST, so then you have to write chunked. Probably a bunch of other problems I can't think of off the top of my head... You'll be much better off writing the file to disk temporarily and then POSTing it once you know you have the whole thing. If you did want to do this, the best way would probably be to implement your own file-like object which would manage the bridge between the two connections (could properly buffer, handle decoding, etc.). EDIT: Based on the comment you left - absolutely - you just need to setopt READFUNCTION. Check out the file_upload example at: http://pycurl.cvs.sourceforge.net/viewvc/pycurl/pycurl/examples/file_upload.py?revision=1.5&view=markup It does exactly this by making a tiny wrapper on a file object with a callback to read the data from it, or alternatively if you don't need to do any processing, you can literally set the READFUNCTION callback to be fp.read.
Uploading file from file object with PyCurl
I'm attempting to upload a file like this: import pycurl c = pycurl.Curl() values = [ ("name", "tom"), ("image", (pycurl.FORM_FILE, "tom.png")) ] c.setopt(c.URL, "http://upload.com/submit") c.setopt(c.HTTPPOST, values) c.perform() c.close() This works fine. However, this only works if the file is local. If I was to fetch the image such that: import urllib2 resp = urllib2.urlopen("http://upload.com/people/tom.png") How would I pass resp.fp as a file object instead of writing it to a file and passing the filename? Is this possible?
[ "It might be possible in perfect situations to basically connect the two streams, but it wouldn't be a very robust solution. There are a bunch of ugly boundary conditions:\n\nThe response socket might still be\nreceiving data, and/or be stalled,\nthus causing you to starve out and\nbreak the POST (because PycURL is not\nexpecting to have to wait for data\nbeyond the current end of the\n\"file\").\nThe response might reset, and then you don't have the complete file, but you've already POSTed a bunch of data - what to do in this case?\nThe file you're fetching with urllib might be chunked-encoded, so you need to perform some operations on the MIME headers for reassembly - you can't just blindly forward the data.\nYou don't necessarily know how big the file you're getting is, so it's hard to provide the proper content-length on the POST, so then you have to write chunked.\nProbably a bunch of other problems I can't think of off the top of my head...\n\nYou'll be much better off writing the file to disk temporarily and then POSTing it once you know you have the whole thing.\nIf you did want to do this, the best way would probably be to implement your own file-like object which would manage the bridge between the two connections (could properly buffer, handle decoding, etc.).\nEDIT:\nBased on the comment you left - absolutely - you just need to setopt READFUNCTION. Check out the file_upload example at:\nhttp://pycurl.cvs.sourceforge.net/viewvc/pycurl/pycurl/examples/file_upload.py?revision=1.5&view=markup\nIt does exactly this by making a tiny wrapper on a file object with a callback to read the data from it, or alternatively if you don't need to do any processing, you can literally set the READFUNCTION callback to be fp.read.\n" ]
[ 4 ]
[]
[]
[ "pycurl", "python" ]
stackoverflow_0002863406_pycurl_python.txt
Q: The anatomy of a Python web project: development, packaging, deployment I'm new to Python (from Java+Ant) and was wondering if someone could detail how to best use Fabric+Pip+Virtualenv to set up a Python web application package skeleton. The end goal is to be able to do any of the following with a single command: Set up a development environment on a fresh dev box (installing all deps) Run all tests Package and deploy to staging Deploy staging to production Other typical dev flow tasks: migrate schema, etc. I'm using Debian+git+Tornado, but I'd like to keep this OS/SCM/framework agnostic if possible. I've done some searching but I'm yet to find something definitive that covers this from top to bottom. I would find this very helpful, I imagine there are a few other ex-Java/PHP/whatever guys out there who would too. Thanks! A: Check out my answer here. It doesn't address all of your questions (mostly the first bullet-point, in fact), but hopefully it gets you started. A: Keeping it framework agnostic will probably be quite hard. But maybe you'll find the following paster templates (for Django projects though) quite useful too. http://morethanseven.net/2010/03/28/More-django-project-templates.html Though Paster has quite a learning curve (at least from my point of view), it'll cover your needs for "project skeletons" quite nicely. Actually, with Paster templates, you can achieve similar things to what Maven Archetypes do for you.
The anatomy of a Python web project: development, packaging, deployment
I'm new to Python (from Java+Ant) and was wondering if someone could detail how to best use Fabric+Pip+Virtualenv to set up a Python web application package skeleton. The end goal is to be able to do any of the following with a single command: Set up a development environment on a fresh dev box (installing all deps) Run all tests Package and deploy to staging Deploy staging to production Other typical dev flow tasks: migrate schema, etc. I'm using Debian+git+Tornado, but I'd like to keep this OS/SCM/framework agnostic if possible. I've done some searching but I'm yet to find something definitive that covers this from top to bottom. I would find this very helpful, I imagine there are a few other ex-Java/PHP/whatever guys out there who would too. Thanks!
[ "Check out my answer here. It doesn't address all of your questions (mostly the first bullet-point, in fact), but hopefully it gets you started.\n", "Keeping it framework agnostic will probably be quite hard. \nBut maybe you'll find the following paster templates (for Django projects though) quite useful too. http://morethanseven.net/2010/03/28/More-django-project-templates.html\nThough Paster has quite a learning curve (at least from my point of view), it'll cover your needs for \"project skeletons\" quite nicely. Actually, with Paster templates, you can achieve similar things to what Maven Archetypes do for you.\n" ]
[ 2, 0 ]
[]
[]
[ "deployment", "fabric", "python", "virtualenv" ]
stackoverflow_0002848942_deployment_fabric_python_virtualenv.txt
Q: Why doesn't appending binary pickles work? I know this isn't exactly how the pickle module was intended to be used, but I would have thought this would work. I'm using Python 3.1.2 Here's the background code: import pickle FILEPATH='/tmp/tempfile' class HistoryFile(): """ Persistent store of a history file Each line should be a separate Python object Usually, pickle is used to make a file for each object, but here, I'm trying to use the append mode of writing a file to store a sequence """ def validate(self, obj): """ Returns whether or not obj is the right Pythonic object """ return True def add(self, obj): if self.validate(obj): with open(FILEPATH, mode='ba') as f: # appending, not writing f.write(pickle.dumps(obj)) else: raise "Did not validate" def unpack(self): """ Go through each line in the file and put each python object into a list, which is returned """ lst = [] with open(FILEPATH, mode='br') as f: # problem must be here, does it not step through the file? for l in f: lst.append(pickle.loads(l)) return lst Now, when I run it, it only prints out the first object that is passed to the class. if __name__ == '__main__': L = HistoryFile() L.add('a') L.add('dfsdfs') L.add(['dfdkfjdf', 'errree', 'cvcvcxvx']) print(L.unpack()) # only prints the first item, 'a'! Is this because it's seeing an early EOF? Maybe appending is intended only for ascii? (in which case, why is it letting me do mode='ba'?) Is there a much simpler duh way to do this? A: Why would you think appending binary pickles would produce a single pickle?! Pickling lets you put (and get back) several items one after the other, so obviously it must be a "self-terminating" serialization format. Forget lines and just get them back! For example: >>> import pickle >>> import cStringIO >>> s = cStringIO.StringIO() >>> pickle.dump(23, s) >>> pickle.dump(45, s) >>> s.seek(0) >>> pickle.load(s) 23 >>> pickle.load(s) 45 >>> pickle.load(s) Traceback (most recent call last): ... EOFError >>> just catch the EOFError to tell you when you're done unpickling. A: The answer is that it DOES work, but without the '+' in mode the newlines automatically added by the append feature of open mixes up the binary with the string data (a definite no-no). Change this line: with open(FILEPATH, mode='ab') as f: # appending, not writing f.write(pickle.dumps(obj)) to with open(FILEPATH, mode='a+b') as f: # appending, not writing pickle.dump(obj, f) Alex also points out that for more flexibility use mode='r+b', but this requires the appropriate seeking. Since I wanted to make a history file that behaved like a first-in, last-out sort of sequence of pythonic objects, it actually made sense for me to try appending objects in a file. I just wasn't doing it correctly :) There is no need to step through the file because (duh!) it is serialized. So replace: for l in f: lst.append(pickle.loads(l)) with while 1: try: lst.append(pickle.load(f)) except IOError: break
Why doesn't appending binary pickles work?
I know this isn't exactly how the pickle module was intended to be used, but I would have thought this would work. I'm using Python 3.1.2 Here's the background code: import pickle FILEPATH='/tmp/tempfile' class HistoryFile(): """ Persistent store of a history file Each line should be a separate Python object Usually, pickle is used to make a file for each object, but here, I'm trying to use the append mode of writing a file to store a sequence """ def validate(self, obj): """ Returns whether or not obj is the right Pythonic object """ return True def add(self, obj): if self.validate(obj): with open(FILEPATH, mode='ba') as f: # appending, not writing f.write(pickle.dumps(obj)) else: raise "Did not validate" def unpack(self): """ Go through each line in the file and put each python object into a list, which is returned """ lst = [] with open(FILEPATH, mode='br') as f: # problem must be here, does it not step through the file? for l in f: lst.append(pickle.loads(l)) return lst Now, when I run it, it only prints out the first object that is passed to the class. if __name__ == '__main__': L = HistoryFile() L.add('a') L.add('dfsdfs') L.add(['dfdkfjdf', 'errree', 'cvcvcxvx']) print(L.unpack()) # only prints the first item, 'a'! Is this because it's seeing an early EOF? Maybe appending is intended only for ascii? (in which case, why is it letting me do mode='ba'?) Is there a much simpler duh way to do this?
[ "Why would you think appending binary pickles would produce a single pickle?! Pickling lets you put (and get back) several items one after the other, so obviously it must be a \"self-terminating\" serialization format. Forget lines and just get them back! For example:\n>>> import pickle\n>>> import cStringIO\n>>> s = cStringIO.StringIO()\n>>> pickle.dump(23, s)\n>>> pickle.dump(45, s)\n>>> s.seek(0)\n>>> pickle.load(s)\n23\n>>> pickle.load(s)\n45\n>>> pickle.load(s)\nTraceback (most recent call last):\n ...\nEOFError\n>>> \n\njust catch the EOFError to tell you when you're done unpickling.\n", "The answer is that it DOES work, but without the '+' in mode the newlines automatically added by the append feature of open mixes up the binary with the string data (a definite no-no). Change this line:\nwith open(FILEPATH, mode='ab') as f: # appending, not writing\n f.write(pickle.dumps(obj))\n\nto \nwith open(FILEPATH, mode='a+b') as f: # appending, not writing\n pickle.dump(obj, f)\n\nAlex also points out that for more flexibility use mode='r+b', but this requires the appropriate seeking. Since I wanted to make a history file that behaved like a first-in, last-out sort of sequence of pythonic objects, it actually made sense for me to try appending objects in a file. I just wasn't doing it correctly :)\nThere is no need to step through the file because (duh!) it is serialized. So replace:\nfor l in f:\n lst.append(pickle.loads(l))\n\nwith\nwhile 1:\n try:\n lst.append(pickle.load(f))\n except IOError:\n break\n\n" ]
[ 6, 4 ]
[]
[]
[ "pickle", "python" ]
stackoverflow_0002857970_pickle_python.txt
Q: sqlalchemy natural sorting Currently, i am querying with this code: meta.Session.query(Label).order_by(Label.name).all() and it returns me objects sorted by Label.name in this manner ['1','7','1a','5c']. Is there a way i can have the objects returned in the order with their Label.name sorted like this ['1','1a','5c','7'] Thanks! A: Sorting is done by the database. If you database doesn't support natural sorting your are out of luck and have to sort your rows manually after retrieving them via sqlalchemy.
sqlalchemy natural sorting
Currently, i am querying with this code: meta.Session.query(Label).order_by(Label.name).all() and it returns me objects sorted by Label.name in this manner ['1','7','1a','5c']. Is there a way i can have the objects returned in the order with their Label.name sorted like this ['1','1a','5c','7'] Thanks!
[ "Sorting is done by the database. If you database doesn't support natural sorting your are out of luck and have to sort your rows manually after retrieving them via sqlalchemy.\n" ]
[ 2 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0002863748_python_sqlalchemy.txt
Q: Autoproperty failing in IronPython works in Python? I have this following python code, it works fine in python but fails with the following error in IronPython 2.6 any ideas as to why? ====================================================================== ERROR: testAutoProp (__main__.testProperty) ---------------------------------------------------------------------- Traceback (most recent call last): File "oproperty.py", line 66, in testAutoProp a.x = 200 File "oproperty.py", line 31, in __set__ getattr(obj, self.fset.__name__)(value) AttributeError: 'A' object has no attribute '<lambda$48>' ---------------------------------------------------------------------- Ran 1 test in 0.234s FAILED (errors=1) Here is the code #provides an overridable version of the property keyword import unittest #provides an overridable version of the property keyword class OProperty(object): """Based on the emulation of PyProperty_Type() in Objects/descrobject.c""" def __init__(self, fget=None, fset=None, fdel=None, doc=None): self.fget = fget self.fset = fset self.fdel = fdel self.__doc__ = doc def __get__(self, obj, objtype=None): if obj is None: return self if self.fget is None: raise AttributeError, "unreadable attribute" if self.fget.__name__ == '<lambda>' or not self.fget.__name__: return self.fget(obj) else: return getattr(obj, self.fget.__name__)() def __set__(self, obj, value): if self.fset is None: raise AttributeError, "can't set attribute" if self.fset.__name__ == '<lambda>' or not self.fset.__name__: self.fset(obj, value) else: getattr(obj, self.fset.__name__)(value) def __delete__(self, obj): if self.fdel is None: raise AttributeError, "can't delete attribute" if self.fdel.__name__ == '<lambda>' or not self.fdel.__name__: self.fdel(obj) else: getattr(obj, self.fdel.__name__)() def autoProperty( attrname, desc ): "Try to auto gen getters and setting for any property type" getFn = lambda self: getattr( self, attrname ) setFn = lambda self, v: setattr( self, attrname, v ) #set the corresponding function in the descriptor desc.fget = getFn desc.fset = setFn #if there is a blank colname let X property sort it out #if hasattr( desc, "colname") and desc.colname == "": # i = 0 # while attrname[ i ] == "_": # i = i + 1 # desc.colname = attrname[i:] return desc class testProperty(unittest.TestCase): def testAutoProp(self): class A(object): def __init__(self): self._x = 50 x = autoProperty( "_x", OProperty() ) a = A() a.x = 200 if __name__ == "__main__": unittest.main() A: Just looking at your code and traceback, it looks to me as though lambdas on IronPython have a name such as <lambda$48> instead of just <lambda>. That means your test if self.fset.__name__ == '<lambda>' or not self.fset.__name__: will take the wrong branch. Try: if self.fset.__name__.startswith('<lambda') or not self.fset.__name__: and so on.
Autoproperty failing in IronPython works in Python?
I have this following python code, it works fine in python but fails with the following error in IronPython 2.6 any ideas as to why? ====================================================================== ERROR: testAutoProp (__main__.testProperty) ---------------------------------------------------------------------- Traceback (most recent call last): File "oproperty.py", line 66, in testAutoProp a.x = 200 File "oproperty.py", line 31, in __set__ getattr(obj, self.fset.__name__)(value) AttributeError: 'A' object has no attribute '<lambda$48>' ---------------------------------------------------------------------- Ran 1 test in 0.234s FAILED (errors=1) Here is the code #provides an overridable version of the property keyword import unittest #provides an overridable version of the property keyword class OProperty(object): """Based on the emulation of PyProperty_Type() in Objects/descrobject.c""" def __init__(self, fget=None, fset=None, fdel=None, doc=None): self.fget = fget self.fset = fset self.fdel = fdel self.__doc__ = doc def __get__(self, obj, objtype=None): if obj is None: return self if self.fget is None: raise AttributeError, "unreadable attribute" if self.fget.__name__ == '<lambda>' or not self.fget.__name__: return self.fget(obj) else: return getattr(obj, self.fget.__name__)() def __set__(self, obj, value): if self.fset is None: raise AttributeError, "can't set attribute" if self.fset.__name__ == '<lambda>' or not self.fset.__name__: self.fset(obj, value) else: getattr(obj, self.fset.__name__)(value) def __delete__(self, obj): if self.fdel is None: raise AttributeError, "can't delete attribute" if self.fdel.__name__ == '<lambda>' or not self.fdel.__name__: self.fdel(obj) else: getattr(obj, self.fdel.__name__)() def autoProperty( attrname, desc ): "Try to auto gen getters and setting for any property type" getFn = lambda self: getattr( self, attrname ) setFn = lambda self, v: setattr( self, attrname, v ) #set the corresponding function in the descriptor desc.fget = getFn desc.fset = setFn #if there is a blank colname let X property sort it out #if hasattr( desc, "colname") and desc.colname == "": # i = 0 # while attrname[ i ] == "_": # i = i + 1 # desc.colname = attrname[i:] return desc class testProperty(unittest.TestCase): def testAutoProp(self): class A(object): def __init__(self): self._x = 50 x = autoProperty( "_x", OProperty() ) a = A() a.x = 200 if __name__ == "__main__": unittest.main()
[ "Just looking at your code and traceback, it looks to me as though lambdas on IronPython have a name such as <lambda$48> instead of just <lambda>. That means your test if self.fset.__name__ == '<lambda>' or not self.fset.__name__: will take the wrong branch.\nTry:\nif self.fset.__name__.startswith('<lambda') or not self.fset.__name__:\n\nand so on.\n" ]
[ 3 ]
[]
[]
[ "ironpython", "lambda", "overriding", "properties", "python" ]
stackoverflow_0002863750_ironpython_lambda_overriding_properties_python.txt
Q: Unable to control requests for static files on Google App Engine My simple GAE app is not redirecting to the /static directory for requests when url is multiple levels. Dir structure: /app/static/css/main.css App: I have two handlers one for /app and one for /app/new app.yaml: handlers: - url: /static static_dir: static - url: /app/static/(.*) static_dir: static\1 - url: /app/.* script: app.py login: required HTML: Description: When page is loaded from /app HTTP request for main.css is successful GET /static/css/main.css But when page is loaded from /app/new I see the following request: GET /app/static/css/main.cs That's when I tried adding the /app/static/(.*) in the app.yaml but it is not having any effect. A: In HTML an internal link starting with "/" is an absolute link, a link starting without a "/" is a relative link. So if you are requesting: /app and have a relative link: static/css/main.css the request becomes: /static/css/main.css the relative link uses the "/" in "/app" because the "app" part is considered to be the page and the "/" is considered to be the directory. If you are requesting: /app/new Your request becomes: /app/static/css/main.css the relative link uses the "/app/" because "/app/" is considered the directory and "new" is considered the page.
Unable to control requests for static files on Google App Engine
My simple GAE app is not redirecting to the /static directory for requests when url is multiple levels. Dir structure: /app/static/css/main.css App: I have two handlers one for /app and one for /app/new app.yaml: handlers: - url: /static static_dir: static - url: /app/static/(.*) static_dir: static\1 - url: /app/.* script: app.py login: required HTML: Description: When page is loaded from /app HTTP request for main.css is successful GET /static/css/main.css But when page is loaded from /app/new I see the following request: GET /app/static/css/main.cs That's when I tried adding the /app/static/(.*) in the app.yaml but it is not having any effect.
[ "In HTML an internal link starting with \"/\" is an absolute link, a link starting without a \"/\" is a relative link. So if you are requesting:\n/app\nand have a relative link:\nstatic/css/main.css\nthe request becomes:\n/static/css/main.css\nthe relative link uses the \"/\" in \"/app\" because the \"app\" part is considered to be the page and the \"/\" is considered to be the directory.\nIf you are requesting:\n/app/new\nYour request becomes:\n/app/static/css/main.css\nthe relative link uses the \"/app/\" because \"/app/\" is considered the directory and \"new\" is considered the page.\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002853915_google_app_engine_python.txt
Q: gdata youtube api 302 'The document has moved' I'm trying to get YouTube feeds with the python gdata library. Authentication features work ok, yt_service.ProgrammaticLogin() works, generating subauth token works, etc., but when I try to get some feeds (GetMostRecentVideoFeed, GetYouTubeVideoEntry, even GetFeed, and any other) I get: RequestError: {'status': 302, 'body': '<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">\n<TITLE>302 Moved</TITLE></HEAD><BODY>\n<H1>302 Moved</H1>\nThe document has moved\n<A HREF="http://www.google.com">here</A>.\r\n</BODY></HTML>\r\n', 'reason': 'Redirect received, but redirects_remaining <= 0'} 302 to 'google.com'??? I've even tried to do something from the google online tutorials and I get the same error. What's going on? A: Solved. You need to add ssl=False to the YouTubeService object. Don't see nothing about it in the docs though. yt = gdata.youtube.service.YouTubeService() yt.ssl = False
gdata youtube api 302 'The document has moved'
I'm trying to get YouTube feeds with the python gdata library. Authentication features work ok, yt_service.ProgrammaticLogin() works, generating subauth token works, etc., but when I try to get some feeds (GetMostRecentVideoFeed, GetYouTubeVideoEntry, even GetFeed, and any other) I get: RequestError: {'status': 302, 'body': '<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">\n<TITLE>302 Moved</TITLE></HEAD><BODY>\n<H1>302 Moved</H1>\nThe document has moved\n<A HREF="http://www.google.com">here</A>.\r\n</BODY></HTML>\r\n', 'reason': 'Redirect received, but redirects_remaining <= 0'} 302 to 'google.com'??? I've even tried to do something from the google online tutorials and I get the same error. What's going on?
[ "Solved.\nYou need to add ssl=False to the YouTubeService object. Don't see nothing about it in the docs though.\nyt = gdata.youtube.service.YouTubeService()\nyt.ssl = False\n\n" ]
[ 1 ]
[]
[]
[ "api", "gdata", "python", "youtube", "youtube_api" ]
stackoverflow_0002863785_api_gdata_python_youtube_youtube_api.txt
Q: flymake and python-execute-region I got an error from flymake-get-file-name-mode-and-masks "Invalid file name" when I have called py-execute-region (bind to C-c |). Also void buffer with name like /tmp/python-3434.py appears. My flymake setup: (when (load "flymake" t) (defun flymake-pylint-init () (let* ((temp-file (flymake-init-create-temp-buffer-copy 'flymake-create-temp-inplace)) (local-file (file-relative-name temp-file (file-name-directory buffer-file-name)))) (list "epylint" (list local-file)))) (add-to-list 'flymake-allowed-file-name-masks '("\.py\'" flymake-pylint-init))) (add-hook 'python-mode-hook 'flymake-mode) A: I had this same problem, and solved it by making emacs not load flymake for temporary buffers passed to the interpreter. I The relevant bits of my flymake setup for Python: (when (load "flymake" t) (defun flymake-python-init () (let* ((temp-file (flymake-init-create-temp-buffer-copy 'flymake-create-temp-inplace)) (local-file (file-relative-name temp-file (file-name-directory buffer-file-name)))) (list "pyflymake" (list local-file)))) ; substitute epylint for this (push '(".+\\.py$" flymake-python-init) flymake-allowed-file-name-masks)) (add-hook 'python-mode-hook (lambda () ; Activate flymake unless buffer is a tmp buffer for the interpreter (unless (eq buffer-file-name nil) (flymake-mode t)) ; this should fix your problem ;; Bind a few keys for navigating errors (local-set-key (kbd "C-c w") 'show-fly-err-at-point) ; remove these if you want (local-set-key (kbd "M-n") 'flymake-goto-next-error) (local-set-key (kbd "M-p") 'flymake-goto-prev-error)))
flymake and python-execute-region
I got an error from flymake-get-file-name-mode-and-masks "Invalid file name" when I have called py-execute-region (bind to C-c |). Also void buffer with name like /tmp/python-3434.py appears. My flymake setup: (when (load "flymake" t) (defun flymake-pylint-init () (let* ((temp-file (flymake-init-create-temp-buffer-copy 'flymake-create-temp-inplace)) (local-file (file-relative-name temp-file (file-name-directory buffer-file-name)))) (list "epylint" (list local-file)))) (add-to-list 'flymake-allowed-file-name-masks '("\.py\'" flymake-pylint-init))) (add-hook 'python-mode-hook 'flymake-mode)
[ "I had this same problem, and solved it by making emacs not load flymake for temporary buffers passed to the interpreter. I\nThe relevant bits of my flymake setup for Python:\n(when (load \"flymake\" t)\n (defun flymake-python-init ()\n (let* ((temp-file (flymake-init-create-temp-buffer-copy\n 'flymake-create-temp-inplace))\n (local-file (file-relative-name\n temp-file\n (file-name-directory buffer-file-name))))\n (list \"pyflymake\" (list local-file)))) ; substitute epylint for this\n (push '(\".+\\\\.py$\" flymake-python-init) flymake-allowed-file-name-masks))\n\n(add-hook 'python-mode-hook\n (lambda ()\n ; Activate flymake unless buffer is a tmp buffer for the interpreter\n (unless (eq buffer-file-name nil) (flymake-mode t)) ; this should fix your problem\n ;; Bind a few keys for navigating errors\n (local-set-key (kbd \"C-c w\") 'show-fly-err-at-point) ; remove these if you want\n (local-set-key (kbd \"M-n\") 'flymake-goto-next-error)\n (local-set-key (kbd \"M-p\") 'flymake-goto-prev-error)))\n\n" ]
[ 4 ]
[]
[]
[ "emacs", "python" ]
stackoverflow_0002681203_emacs_python.txt
Q: Executing Multiple Lines in Python When Python is first installed, the default setting executes users' code input line-by-line. But sometimes I need to write programs that executes multiple lines at once. Is there a setting in Python where I can change the code execution to one block at once? Thanks >>> if (n/2) * 2 == n:; print 'Even'; else: print 'Odd' SyntaxError: invalid syntax When I tried to run the above code, I got an invalid syntax error on ELSE A: Your indentation is wrong. Try this: >>> if (n/2) * 2 == n: ... print 'Even' ... else: print 'Odd' Also you might want to write it on four lines: >>> if (n/2) * 2 == n: ... print 'Even' ... else: ... print 'Odd' Or even just one line: >>> print 'Even' if (n/2) * 2 == n else 'Odd' A: One step towards the solution is to remove the semicolon after the if: if True:; print 'true'; print 'not ok'; # syntax error! if True: print 'true'; print 'ok'; # ok You cannot have an else in the same line because it would be ambiguous: if True: print 't'; if True: print 'tt; else: ... # <- which if is that else for?? It is also clearly stated in the docs that you need a DEDENT before the else statement can start. A: Since python 2.5 you can do one line ifs print ('Even' if n % 2 == 0 else 'Odd') Still to answer your question you can either: 1. enter the code properly without syntax errors and your blocks will be executed as blocks regardless if they span multiple lines or not, even in interactive shell. See tutorials in dive into python 2. write code in the script and execute that script using either command line or some IDE (idle, eclipse, etc..) One of the idea behind python is to prefer multiple lines and to aim for uniform formatting of source, so what you try to do is not pythonic, you should not aim to cram multiple statements into single line unless you have a good reason. A: print n % 2 == 0 and 'Even' or 'Odd' :-)
Executing Multiple Lines in Python
When Python is first installed, the default setting executes users' code input line-by-line. But sometimes I need to write programs that executes multiple lines at once. Is there a setting in Python where I can change the code execution to one block at once? Thanks >>> if (n/2) * 2 == n:; print 'Even'; else: print 'Odd' SyntaxError: invalid syntax When I tried to run the above code, I got an invalid syntax error on ELSE
[ "Your indentation is wrong. Try this:\n>>> if (n/2) * 2 == n:\n... print 'Even'\n... else: print 'Odd'\n\nAlso you might want to write it on four lines:\n>>> if (n/2) * 2 == n:\n... print 'Even'\n... else:\n... print 'Odd'\n\nOr even just one line:\n>>> print 'Even' if (n/2) * 2 == n else 'Odd'\n\n", "One step towards the solution is to remove the semicolon after the if:\nif True:; print 'true'; print 'not ok'; # syntax error!\n\nif True: print 'true'; print 'ok'; # ok\n\nYou cannot have an else in the same line because it would be ambiguous:\nif True: print 't'; if True: print 'tt; else: ... # <- which if is that else for??\n\nIt is also clearly stated in the docs that you need a DEDENT before the else statement can start.\n", "Since python 2.5 you can do one line ifs\nprint ('Even' if n % 2 == 0 else 'Odd')\n\nStill to answer your question you can either:\n1. enter the code properly without syntax errors and your blocks will be executed as blocks regardless if they span multiple lines or not, even in interactive shell. See tutorials in dive into python\n2. write code in the script and execute that script using either command line or some IDE (idle, eclipse, etc..)\nOne of the idea behind python is to prefer multiple lines and to aim for uniform formatting of source, so what you try to do is not pythonic, you should not aim to cram multiple statements into single line unless you have a good reason.\n", "print n % 2 == 0 and 'Even' or 'Odd'\n\n:-)\n" ]
[ 9, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002863526_python.txt
Q: call external program in python, watch output for specific text then take action i'm looking for a way in python to run an external binary and watch it's output for: "up to date" If "up to date" isn't returned i want to run the original command again, once "up to date" is displayed i would like to be able to run another script. So far I've figured out how to run the binary with options using subprocess but thats as far as I've gotten. Thanks! A: Use Popen from subprocess like this process = Popen("cmd", shell=True, bufsize=bufsize, stdout=PIPE) Then use process.stdout to read from program's stdout (like reading from any other file like object).
call external program in python, watch output for specific text then take action
i'm looking for a way in python to run an external binary and watch it's output for: "up to date" If "up to date" isn't returned i want to run the original command again, once "up to date" is displayed i would like to be able to run another script. So far I've figured out how to run the binary with options using subprocess but thats as far as I've gotten. Thanks!
[ "Use Popen from subprocess like this\nprocess = Popen(\"cmd\", shell=True, bufsize=bufsize, stdout=PIPE)\nThen use process.stdout to read from program's stdout (like reading from any other file like object).\n" ]
[ 3 ]
[]
[]
[ "linux", "python", "unix" ]
stackoverflow_0002864277_linux_python_unix.txt
Q: How do I specify a relation in SQLAlchemy where one condition requires a column to be null? Not sure what the correct title for this question should be. I have the following schema: Matters have a one-many relationship to WorkItems. WorkItems have a one-one (or one-zero) relationship to LineItems. I am trying to create the following relation between Matters and WorkItems Matter.unbilled_work_items = orm.relation(WorkItem, primaryjoin = (Matter.id == WorkItem.matter_id) and (WorkItem.line_item_id == None), foreign_keys = [WorkItem.matter_id, WorkItem.line_item_id], viewonly=True ) This throws: AttributeError: '_Null' object has no attribute 'table' That seems to be saying that the second clause in the primaryjoin returns an object of type _Null, but it seems to be expecting something with a "table" attribute. This seems like it should be pretty straightforward to me, am I missing something obvious? Update The answer was to change the primaryjoin line to: primaryjoin = "and_(Matter.id == WorkItem.matter_id, WorkItem.line_item_id == None)" A: Try using and_ as and is not overloaded: and_((Matter.id == WorkItem.matter_id), (WorkItem.line_item_id == None)) A: Apart from the _Null issue, this requires a left outer join to do correctly. I've decided that unbilled_work_items should be a property that executes a query and returns the result. # like this @property def unbilled_work_items(self): return Session.object_session(self).query.filter(...).all()
How do I specify a relation in SQLAlchemy where one condition requires a column to be null?
Not sure what the correct title for this question should be. I have the following schema: Matters have a one-many relationship to WorkItems. WorkItems have a one-one (or one-zero) relationship to LineItems. I am trying to create the following relation between Matters and WorkItems Matter.unbilled_work_items = orm.relation(WorkItem, primaryjoin = (Matter.id == WorkItem.matter_id) and (WorkItem.line_item_id == None), foreign_keys = [WorkItem.matter_id, WorkItem.line_item_id], viewonly=True ) This throws: AttributeError: '_Null' object has no attribute 'table' That seems to be saying that the second clause in the primaryjoin returns an object of type _Null, but it seems to be expecting something with a "table" attribute. This seems like it should be pretty straightforward to me, am I missing something obvious? Update The answer was to change the primaryjoin line to: primaryjoin = "and_(Matter.id == WorkItem.matter_id, WorkItem.line_item_id == None)"
[ "Try using and_ as and is not overloaded:\nand_((Matter.id == WorkItem.matter_id), (WorkItem.line_item_id == None))\n\n", "Apart from the _Null issue, this requires a left outer join to do correctly. I've decided that unbilled_work_items should be a property that executes a query and returns the result.\n# like this\n\n@property\ndef unbilled_work_items(self):\n return Session.object_session(self).query.filter(...).all()\n\n" ]
[ 6, 1 ]
[]
[]
[ "foreign_key_relationship", "python", "sqlalchemy" ]
stackoverflow_0002863786_foreign_key_relationship_python_sqlalchemy.txt
Q: Are classes in Python in different files? Much like Java (or php), I'm use to seperating the classes to files. Is it the same deal in Python? plus, how should I name the file? Lowercase like classname.py or the same like ClassName.py? Do I need to do something special if I want to create an object from this class or does the fact that it's in the same "project" (netbeans) makes it ok to create an object from it? A: In Python, one file is called a module. A module can consist of multiple classes or functions. As Python is not an OO language only, it does not make sense do have a rule that says, one file should only contain one class. One file (module) should contain classes / functions that belong together, i.e. provide similar functionality or depend on each other. Of course you should not exaggerate this. Readability really suffers if your module consist of too much classes or functions. Then it is probably time to regroup the functionality into different modules and create packages. For naming conventions, you might want to read PEP 8 but in short: Class Names Almost without exception, class names use the CapWords convention. Classes for internal use have a leading underscore in addition. and Package and Module Names Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged. Since module names are mapped to file names, and some file systems are case insensitive and truncate long names, it is important that module names be chosen to be fairly short -- this won't be a problem on Unix, but it may be a problem when the code is transported to older Mac or Windows versions, or DOS. To instantiate an object, you have to import the class in your file. E.g >>> from mymodule import MyClass >>> obj = MyClass() or >>> import mymodule >>> obj = mymodule.MyClass() or >>> from mypackage.mymodule import MyClass >>> obj = MyClass() You are asking essential basic stuff, so I recommend to read the tutorial. A: No, you can define multiple classes (and functions, etc.) in a single file. A file is also called a module. To use the classes/functions defined in the module/file, you will need to import the module/file.
Are classes in Python in different files?
Much like Java (or php), I'm use to seperating the classes to files. Is it the same deal in Python? plus, how should I name the file? Lowercase like classname.py or the same like ClassName.py? Do I need to do something special if I want to create an object from this class or does the fact that it's in the same "project" (netbeans) makes it ok to create an object from it?
[ "In Python, one file is called a module. A module can consist of multiple classes or functions.\nAs Python is not an OO language only, it does not make sense do have a rule that says, one file should only contain one class.\nOne file (module) should contain classes / functions that belong together, i.e. provide similar functionality or depend on each other.\nOf course you should not exaggerate this. Readability really suffers if your module consist of too much classes or functions. Then it is probably time to regroup the functionality into different modules and create packages.\n\nFor naming conventions, you might want to read PEP 8 but in short:\n\nClass Names\nAlmost without exception, class names use the CapWords convention.\n Classes for internal use have a leading underscore in addition.\n\nand\n\nPackage and Module Names\nModules should have short, all-lowercase names. Underscores can be used\n in the module name if it improves readability. Python packages should\n also have short, all-lowercase names, although the use of underscores is\n discouraged.\nSince module names are mapped to file names, and some file systems are\n case insensitive and truncate long names, it is important that module\n names be chosen to be fairly short -- this won't be a problem on Unix,\n but it may be a problem when the code is transported to older Mac or\n Windows versions, or DOS.\n\n\nTo instantiate an object, you have to import the class in your file. E.g\n>>> from mymodule import MyClass\n>>> obj = MyClass()\n\nor\n>>> import mymodule\n>>> obj = mymodule.MyClass()\n\nor\n>>> from mypackage.mymodule import MyClass\n>>> obj = MyClass()\n\n\nYou are asking essential basic stuff, so I recommend to read the tutorial.\n", "No, you can define multiple classes (and functions, etc.) in a single file. A file is also called a module.\nTo use the classes/functions defined in the module/file, you will need to import the module/file.\n" ]
[ 91, 9 ]
[]
[]
[ "class", "naming_conventions", "python" ]
stackoverflow_0002864366_class_naming_conventions_python.txt
Q: Why does Ruby have Rails while Python has no central framework? This is a(n) historical question, not a comparison-between-languages question: This article from 2005 talks about the lack of a single, central framework for Python. For Ruby, this framework is clearly Rails. Why, historically speaking, did this happen for Ruby but not for Python? (or did it happen, and that framework is Django?) Also, the hypothetical questions: would Python be more popular if it had one, good framework? Would Ruby be less popular if it had no central framework? [Please avoid discussions of whether Ruby or Python is better, which is just too open-ended to answer.] Edit: Though I thought this is obvious, I'm not saying that other frameworks do not exist for Ruby, but rather that the big one in terms of popularity is Rails. Also, I should mention that I'm not saying that frameworks for Python are not as good (or better than) Rails. Every framework has its pros and cons, but Rails seems to, as Ben Blank says in the one of the comments below, have surpassed Ruby in terms of popularity. There are no examples of that on the Python side. WHY? That's the question. A: As I see it, Rails put Ruby on the map. The simple fact is that before Rails, Ruby was a minor esoteric language, with very little adoption. Ruby owes its success to Rails. As such, Rails has a central place in the Ruby ecosystem. As slim points out, there are other web frameworks, but it's going to be very difficult to overtake Rails as the leader. Python on the other hand, had a very different adoption curve. Before Rails, Python was much more widely used than Ruby, and so had a number of competing web frameworks, each slowly building their constituencies. Django has done a good job consolidating support, and becoming the leader in the Python web framework world, but it will never be the One True Framework simply because of the way the community developed. A: I don't think it's right to characterise Rails as 'the' 'single' 'central' Ruby framework. Other frameworks for Ruby include Merb, Camping and Ramaze. ... which sort of invalidates the question. A: The real technical answer is that there are three major approaches to web-development in Python: one is CGI-based, where the application is built just like an old one-off Perl application to run through CGI or FastCGI, e.g. Trac; then there is Zope, which is a bizarro overengineered framework with its own DB concept, a strange misguided through-the-web software development concept, etc. (but Plone is still quite popular); and then there is Django (and Turbogears, etc.), which is guided by the same just-the-tools-needed philosophy as Rails (it can be argued who got there first or who did it better). A lot of people would probably agree that the Django/Rails/CakePHP approach is better than the older approaches, but as the older language Python has a lot more legacy frameworks that are still trying to evolve and stay relevant. These frameworks will hang on because there is already developer buy-in for them. For example, in hindsight many people would probably say that Zope (especially ZODB) was a terrible mistake, but Zope 3 is much better than Zope 2, and there are already whole companies built around Zope technologies. A: Rails was somewhat revolutionary in its extreme "convention over configuration" approach which set it apart from pretty much anything else and made it the "killer app" of Ruby, causing a lot of people to notice Ruby in the first place. So the question is really "Why did David Hansson decide to write Rails in Ruby rather than Python?" A: Remember that Ruby had existed for a long time before Rails was created. According to Wikipedia, Ruby was created in the mid-90's; Rails didn't come around until 2004. Ruby is simply the language that David Hansson chose to use for Rails. And yes, I would say Ruby is to Rails as Python is to Django. A: I agree with Ned. I'd bet that more than 90% of Ruby installations are for no other purpose than running Rails. Rails dominates Ruby - there is no single application that dominates Python, mainly because the Python community is somewhat bigger than the Ruby community. A: Would ruby be less popular without Rails? absolutely. Would Python be more popular with one true framework? You mean as opposed to several? May be, who knows. In any case most agree Django is a very good framework. Why, historically, did it happen to Ruby? Because DHH chose Ruby after doing his own research. To add to the answer regarding Rails having made a breakthrough because of 'convention over configuration' there is also another reason and that is that Rails has been using the meta-programming abilities of Ruby superbly. A lot of the magic of Rails which has contributed to removing a lot of the pain of developing web apps came through this clever use of ruby meta-programming. A: I'd have to agree that Django is basically the "Rails for Python" equivalent. Why did it take so long? The simple answer is too many options. In Python, there are many request/response systems, url rewriters, ORMs, templating languages, etc. that you could build a web stack in dozens of different configurations. In fact, this is exactly what Pylons and TurboGears do is provide a reliable, predictable stack to build MVC web apps. What Django did differently was they encapsulated everything. Rather than go the components route, they built one contiguous system. They built their own ORM, their own template language, their own middleware system, etc. Their reasoning was that there was no unified system like this for Python. A: Python is not a one-trick pony. Therefore, there's no single "central framework" for it. Many people first heard of Python as "another nice OO language" or through one of the many uses to which it has been put. To be fair, Ruby is not a one-trick pony either. It's just that many people regarded Rails as the "killer app" that got them to look at a previously-not-well-known language. I suspect many people never heard of Ruby before Rails, but that's by no means the only thing Ruby can do. A: If you followed the news, you have read that Merb and Rails will merge. This is a good move IMHO. I think it's because of the common goal that the developers have: They want a simple framework for webdev, which comes with a OR mapper, routing, template language, etc which fits for most tasks.. A: Check out this article on why we'll never see Python-on-Rails. The author gives some of the basic reasons why Python has never had and will never have a central framework. I might add, myself, that Java doesn't have one either, and for the same reasons. According to the author, Rails is strictly tied to its "implementation," which is Ruby. Rails was adopted by many developers and Ruby was just part of it. Rails works perfectly on Ruby (or Ruby wanna-bes like Groovy), but more importantly, as many other answers say, Rails led the way to Ruby adoption. This is why Rails-for-Python won't work, or at least what people have been focusing on with Rails isn't correct. It's not about the implementation or the quality of the framework, it's about the pattern of adoption. It's about putting the framework up front, and the implementation in the back -- even if this wasn't the Rails developers intentions (though maybe they are clever and this was their intention). Basically, you can't get a bunch of language-loving folk to gather around a single framework. On the Java side, while Spring is well-loved, it's no Rails in terms of popularity in the Java community. In a mature community developers have their own ideas about what metaphors work and don't work in a framework. This is why Rails leads to Ruby and not the other way around (typically, mostly, not in all cases).
Why does Ruby have Rails while Python has no central framework?
This is a(n) historical question, not a comparison-between-languages question: This article from 2005 talks about the lack of a single, central framework for Python. For Ruby, this framework is clearly Rails. Why, historically speaking, did this happen for Ruby but not for Python? (or did it happen, and that framework is Django?) Also, the hypothetical questions: would Python be more popular if it had one, good framework? Would Ruby be less popular if it had no central framework? [Please avoid discussions of whether Ruby or Python is better, which is just too open-ended to answer.] Edit: Though I thought this is obvious, I'm not saying that other frameworks do not exist for Ruby, but rather that the big one in terms of popularity is Rails. Also, I should mention that I'm not saying that frameworks for Python are not as good (or better than) Rails. Every framework has its pros and cons, but Rails seems to, as Ben Blank says in the one of the comments below, have surpassed Ruby in terms of popularity. There are no examples of that on the Python side. WHY? That's the question.
[ "As I see it, Rails put Ruby on the map. The simple fact is that before Rails, Ruby was a minor esoteric language, with very little adoption. Ruby owes its success to Rails. As such, Rails has a central place in the Ruby ecosystem. As slim points out, there are other web frameworks, but it's going to be very difficult to overtake Rails as the leader.\nPython on the other hand, had a very different adoption curve. Before Rails, Python was much more widely used than Ruby, and so had a number of competing web frameworks, each slowly building their constituencies. Django has done a good job consolidating support, and becoming the leader in the Python web framework world, but it will never be the One True Framework simply because of the way the community developed.\n", "I don't think it's right to characterise Rails as 'the' 'single' 'central' Ruby framework.\nOther frameworks for Ruby include Merb, Camping and Ramaze.\n... which sort of invalidates the question.\n", "The real technical answer is that there are three major approaches to web-development in Python: one is CGI-based, where the application is built just like an old one-off Perl application to run through CGI or FastCGI, e.g. Trac; then there is Zope, which is a bizarro overengineered framework with its own DB concept, a strange misguided through-the-web software development concept, etc. (but Plone is still quite popular); and then there is Django (and Turbogears, etc.), which is guided by the same just-the-tools-needed philosophy as Rails (it can be argued who got there first or who did it better). A lot of people would probably agree that the Django/Rails/CakePHP approach is better than the older approaches, but as the older language Python has a lot more legacy frameworks that are still trying to evolve and stay relevant. These frameworks will hang on because there is already developer buy-in for them. For example, in hindsight many people would probably say that Zope (especially ZODB) was a terrible mistake, but Zope 3 is much better than Zope 2, and there are already whole companies built around Zope technologies.\n", "Rails was somewhat revolutionary in its extreme \"convention over configuration\" approach which set it apart from pretty much anything else and made it the \"killer app\" of Ruby, causing a lot of people to notice Ruby in the first place. \nSo the question is really \"Why did David Hansson decide to write Rails in Ruby rather than Python?\"\n", "Remember that Ruby had existed for a long time before Rails was created. According to Wikipedia, Ruby was created in the mid-90's; Rails didn't come around until 2004. Ruby is simply the language that David Hansson chose to use for Rails.\nAnd yes, I would say Ruby is to Rails as Python is to Django.\n", "I agree with Ned. I'd bet that more than 90% of Ruby installations are for no other purpose than running Rails. Rails dominates Ruby - there is no single application that dominates Python, mainly because the Python community is somewhat bigger than the Ruby community. \n", "Would ruby be less popular without Rails? absolutely.\nWould Python be more popular with one true framework? You mean as opposed to several? May be, who knows. In any case most agree Django is a very good framework.\nWhy, historically, did it happen to Ruby? Because DHH chose Ruby after doing his own research. \nTo add to the answer regarding Rails having made a breakthrough because of 'convention over configuration' there is also another reason and that is that Rails has been using the meta-programming abilities of Ruby superbly. A lot of the magic of Rails which has contributed to removing a lot of the pain of developing web apps came through this clever use of ruby meta-programming.\n", "I'd have to agree that Django is basically the \"Rails for Python\" equivalent. Why did it take so long? The simple answer is too many options.\nIn Python, there are many request/response systems, url rewriters, ORMs, templating languages, etc. that you could build a web stack in dozens of different configurations. In fact, this is exactly what Pylons and TurboGears do is provide a reliable, predictable stack to build MVC web apps.\nWhat Django did differently was they encapsulated everything. Rather than go the components route, they built one contiguous system. They built their own ORM, their own template language, their own middleware system, etc. Their reasoning was that there was no unified system like this for Python.\n", "Python is not a one-trick pony. Therefore, there's no single \"central framework\" for it. Many people first heard of Python as \"another nice OO language\" or through one of the many uses to which it has been put.\nTo be fair, Ruby is not a one-trick pony either. It's just that many people regarded Rails as the \"killer app\" that got them to look at a previously-not-well-known language. I suspect many people never heard of Ruby before Rails, but that's by no means the only thing Ruby can do.\n", "If you followed the news, you have read that Merb and Rails will merge. This is a good move IMHO. I think it's because of the common goal that the developers have: They want a simple framework for webdev, which comes with a OR mapper, routing, template language, etc which fits for most tasks..\n", "Check out this article on why we'll never see Python-on-Rails. The author gives some of the basic reasons why Python has never had and will never have a central framework. I might add, myself, that Java doesn't have one either, and for the same reasons.\nAccording to the author, Rails is strictly tied to its \"implementation,\" which is Ruby. Rails was adopted by many developers and Ruby was just part of it. Rails works perfectly on Ruby (or Ruby wanna-bes like Groovy), but more importantly, as many other answers say, Rails led the way to Ruby adoption.\n\nThis is why Rails-for-Python won't\n work, or at least what people have\n been focusing on with Rails isn't\n correct. It's not about the\n implementation or the quality of the\n framework, it's about the pattern of\n adoption. It's about putting the\n framework up front, and the\n implementation in the back -- even if\n this wasn't the Rails developers\n intentions (though maybe they are\n clever and this was their intention).\n\nBasically, you can't get a bunch of language-loving folk to gather around a single framework. On the Java side, while Spring is well-loved, it's no Rails in terms of popularity in the Java community. In a mature community developers have their own ideas about what metaphors work and don't work in a framework. This is why Rails leads to Ruby and not the other way around (typically, mostly, not in all cases).\n" ]
[ 35, 7, 7, 5, 5, 5, 2, 2, 1, 0, 0 ]
[]
[]
[ "frameworks", "history", "python", "ruby", "ruby_on_rails" ]
stackoverflow_0000406907_frameworks_history_python_ruby_ruby_on_rails.txt
Q: Convert GNU find command to Python function I want to convert this GNU command into a python function: find folder/ 2>/dev/null > file.txt The find will list all files and folders from the directory recursively and write them to a file. What I have now in Python is: import os project="/folder/path" i=0 for (project, dirs, files) in os.walk(project): print project print files i += 1 But now I am trying to make the output exactly as find does. A: import os path = "folder" for dirpath, dirnames, filenames in os.walk(path): print(dirpath) for filename in filenames: print(os.path.join(dirpath, filename)) Instead of print you can write to file.
Convert GNU find command to Python function
I want to convert this GNU command into a python function: find folder/ 2>/dev/null > file.txt The find will list all files and folders from the directory recursively and write them to a file. What I have now in Python is: import os project="/folder/path" i=0 for (project, dirs, files) in os.walk(project): print project print files i += 1 But now I am trying to make the output exactly as find does.
[ "import os\npath = \"folder\"\nfor dirpath, dirnames, filenames in os.walk(path):\n print(dirpath)\n for filename in filenames:\n print(os.path.join(dirpath, filename))\n\nInstead of print you can write to file.\n" ]
[ 4 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0002864474_bash_python.txt
Q: python: importing modules with incorrect import statements => unexhaustive info from resulting ImportError I have a funny problem I'd like to ask you guys ('n gals) about. I'm importing some module A that is importing some non-existent module B. Of course this will result in an ImportError. This is what A.py looks like import B Now let's import A >>> import A Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/tmp/importtest/A.py", line 1, in <module> import B ImportError: No module named B Alright, on to the problem. How can I know if this ImportError results from importing A or from some corrupt import inside A without looking at the error's string representation. The difference is that either A is not there or does have incorrect import statements. Hope you can help me out... Cheers bb A: There is the imp module in the standard lib, so you could do: >>> import imp >>> imp.find_module('collections') (<_io.TextIOWrapper name=4 encoding='utf-8'>, 'C:\\Program Files\\Python31\\lib\\collections.py', ('.py', 'U', 1)) >>> imp.find_module('col') Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> imp.find_module('col') ImportError: No module named col which raises ImportError when module is not found. As it's not trying to import that module it's completely independent on whether ImportError will be raised by that particular module. And of course there's a imp.load_module to actually load that module. A: You can also look at the back-trace, which can be examined in the code. However, why do you want to find out - either way A isn't going to work.
python: importing modules with incorrect import statements => unexhaustive info from resulting ImportError
I have a funny problem I'd like to ask you guys ('n gals) about. I'm importing some module A that is importing some non-existent module B. Of course this will result in an ImportError. This is what A.py looks like import B Now let's import A >>> import A Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/tmp/importtest/A.py", line 1, in <module> import B ImportError: No module named B Alright, on to the problem. How can I know if this ImportError results from importing A or from some corrupt import inside A without looking at the error's string representation. The difference is that either A is not there or does have incorrect import statements. Hope you can help me out... Cheers bb
[ "There is the imp module in the standard lib, so you could do:\n>>> import imp\n>>> imp.find_module('collections')\n(<_io.TextIOWrapper name=4 encoding='utf-8'>, 'C:\\\\Program Files\\\\Python31\\\\lib\\\\collections.py', ('.py', 'U', 1))\n>>> imp.find_module('col')\nTraceback (most recent call last):\n File \"<pyshell#2>\", line 1, in <module>\n imp.find_module('col')\nImportError: No module named col\n\nwhich raises ImportError when module is not found. As it's not trying to import that module it's completely independent on whether ImportError will be raised by that particular module.\nAnd of course there's a imp.load_module to actually load that module.\n", "You can also look at the back-trace, which can be examined in the code.\nHowever, why do you want to find out - either way A isn't going to work.\n" ]
[ 2, 0 ]
[]
[]
[ "import", "importerror", "python" ]
stackoverflow_0002864700_import_importerror_python.txt
Q: Randomly add buttons to Tkinter GUI? How do I randomly add buttons to a Tkinter GUI? I need it to be able to create a button, then put it anywhere on the window, is this possible? I am using Python 2.6 on Windows. A: If you want random button placement (or anything not aligned along a grid, etc.), you can use the place geometry manager. Depending on platform, overlapped buttons may not behave as you expect, though, so you may want to avoid them. Here's a simple example: from Tkinter import * from random import random root = Tk() frame = Frame(root, height=200, width=200) for i in range(10): Button(frame, text=str(i)).place(x=random() * 150, y=random() * 180) frame.pack() root.mainloop() A: There are several options to choose from. For example, you could design on a grid where you have six buttons per row. Then it's just a matter of starting at row 0, incrementing the column for each button. When you get to the last column, reset the column to 0 and increment the row by one. Another option is to use a text widget as the container, and embed your buttons in the text widget with wrapping enabled. With this trick the buttons will fill a row automatically and wrap if the user grows or shrinks the main windows. It's a tiny bit more work, but it works well if that's the behavior you want.
Randomly add buttons to Tkinter GUI?
How do I randomly add buttons to a Tkinter GUI? I need it to be able to create a button, then put it anywhere on the window, is this possible? I am using Python 2.6 on Windows.
[ "If you want random button placement (or anything not aligned along a grid, etc.), you can use the place geometry manager. Depending on platform, overlapped buttons may not behave as you expect, though, so you may want to avoid them.\nHere's a simple example:\nfrom Tkinter import *\nfrom random import random\n\nroot = Tk()\nframe = Frame(root, height=200, width=200)\n\nfor i in range(10):\n Button(frame, text=str(i)).place(x=random() * 150, y=random() * 180)\n\nframe.pack()\nroot.mainloop()\n\n", "There are several options to choose from. For example, you could design on a grid where you have six buttons per row. Then it's just a matter of starting at row 0, incrementing the column for each button. When you get to the last column, reset the column to 0 and increment the row by one.\nAnother option is to use a text widget as the container, and embed your buttons in the text widget with wrapping enabled. With this trick the buttons will fill a row automatically and wrap if the user grows or shrinks the main windows. It's a tiny bit more work, but it works well if that's the behavior you want.\n" ]
[ 2, 0 ]
[]
[]
[ "button", "python", "random", "tkinter", "windows" ]
stackoverflow_0002853933_button_python_random_tkinter_windows.txt
Q: removing elements incrementally from a list I've a list of float numbers and I would like to delete incrementally a set of elements in a given range of indexes, sth. like: for j in range(beginIndex, endIndex+1): print ("remove [%d] => val: %g" % (j, myList[j])) del myList[j] However, since I'm iterating over the same list, the indexes (range) are not valid any more for the new list. Does anybody has some suggestions on how to delete the elements properly? Best wishes A: Do you really need to remove them incrementaly? If not, you can do it like this: del myList[beginIndex:endIndex+1] A: You can iterate from the end to beginning of the sequence: for j in range(endIndex, beginIndex-1, -1): print ("remove [%d] => val: %g" % (j, myList[j])) del myList[j] A: Something like this? >>> list1 = [1,2,3,4,5,6] >>> start, end = 2, 4 >>> list1[:start] + list1[end:] [1, 2, 5, 6]
removing elements incrementally from a list
I've a list of float numbers and I would like to delete incrementally a set of elements in a given range of indexes, sth. like: for j in range(beginIndex, endIndex+1): print ("remove [%d] => val: %g" % (j, myList[j])) del myList[j] However, since I'm iterating over the same list, the indexes (range) are not valid any more for the new list. Does anybody has some suggestions on how to delete the elements properly? Best wishes
[ "Do you really need to remove them incrementaly?\nIf not, you can do it like this:\ndel myList[beginIndex:endIndex+1]\n\n", "You can iterate from the end to beginning of the sequence:\nfor j in range(endIndex, beginIndex-1, -1):\n print (\"remove [%d] => val: %g\" % (j, myList[j]))\n del myList[j]\n\n", "Something like this?\n>>> list1 = [1,2,3,4,5,6]\n>>> start, end = 2, 4\n>>> list1[:start] + list1[end:]\n[1, 2, 5, 6]\n\n" ]
[ 9, 2, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0002864854_list_python.txt
Q: logical operators evaluation in return statement in python How does this execute? def f(x): return x>0 and (x%2)+f(x/2) or 0 x is an array, for instance: [1, 1, 1, 3] A: This code is broken. For starters, x>0 is always true. But x%2 and x/2 yield type errors. A: Did you mean this? $ python Python 2.5.5 (r255:77872, Apr 21 2010, 08:40:04) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def f(x): ... return x>0 and (x%2)+f(x/2) or 0 ... >>> f([1, 1, 1, 3]) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in f TypeError: unsupported operand type(s) for %: 'list' and 'int' A: evaluation in return statement is no different from evaluation in any other place. if x is a list this whole thing makes no sense and raises TypeError. x should be a numeric for this to work. If x is a number it would work as follows: evaluate x>0 statement if it was True return (x%2)+f(x/2) part. Which, of course, recurses infinitely if it was False return 0 A: The function recursively counts the number of 1's in the binary form of the number x. Each time the function adds sums the lowest bit (either 1 or 0) with the bit count of a number without the last bit (dividing by 2 is like shifting right by 1), or with 0 if there are no more bits. For example: The function will return 2 for 5 as an input (5 is 101 in binary) The function will return 3 for 13 as an input (13 is 1101 in binary) ...
logical operators evaluation in return statement in python
How does this execute? def f(x): return x>0 and (x%2)+f(x/2) or 0 x is an array, for instance: [1, 1, 1, 3]
[ "This code is broken. For starters, x>0 is always true. But x%2 and x/2 yield type errors.\n", "Did you mean this?\n$ python\nPython 2.5.5 (r255:77872, Apr 21 2010, 08:40:04) \n[GCC 4.4.3] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> def f(x):\n... return x>0 and (x%2)+f(x/2) or 0\n... \n>>> f([1, 1, 1, 3])\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 2, in f\nTypeError: unsupported operand type(s) for %: 'list' and 'int'\n\n", "evaluation in return statement is no different from evaluation in any other place. if x is a list this whole thing makes no sense and raises TypeError. x should be a numeric for this to work.\nIf x is a number it would work as follows:\n\nevaluate x>0 statement\nif it was True return (x%2)+f(x/2) part. Which, of course, recurses infinitely\nif it was False return 0\n\n", "The function recursively counts the number of 1's in the binary form of the number x.\nEach time the function adds sums the lowest bit (either 1 or 0) with the bit count of a number without the last bit (dividing by 2 is like shifting right by 1), or with 0 if there are no more bits.\nFor example:\nThe function will return 2 for 5 as an input (5 is 101 in binary)\nThe function will return 3 for 13 as an input (13 is 1101 in binary)\n...\n" ]
[ 2, 0, 0, 0 ]
[]
[]
[ "logical_operators", "python" ]
stackoverflow_0002865140_logical_operators_python.txt
Q: How can i read bzr repository from python script? like getting information about changesets/comments etc. A: First off, if you are on Windows, you should consider using the "Python 2.x" installers rather than the standalone installer for Bazaar. This will install bzrlib in Python's site-packages directory, so you don't have to mess around with %PYTHONPATH%. If you have already used the stanadalone installer, you'll need to add lib/ and lib/library.zip from your Bazaar installation directory to the PYTHONPATH environment variable. If you chose the default, this is C:\Program Files\Bazaar Once you can successfully import bzrlib, some examples showing how to actually interact with the bzr backend can be found on the Bazaar wiki. For details, see Integrating with Bazaar in the Bazaar developer documentation A: Found: http://wiki.bazaar.canonical.com/BzrLib
How can i read bzr repository from python script?
like getting information about changesets/comments etc.
[ "First off, if you are on Windows, you should consider using the \"Python 2.x\" installers rather than the standalone installer for Bazaar. This will install bzrlib in Python's site-packages directory, so you don't have to mess around with %PYTHONPATH%. If you have already used the stanadalone installer, you'll need to add lib/ and lib/library.zip from your Bazaar installation directory to the PYTHONPATH environment variable. If you chose the default, this is C:\\Program Files\\Bazaar\nOnce you can successfully import bzrlib, some examples showing how to actually interact with the bzr backend can be found on the Bazaar wiki.\nFor details, see Integrating with Bazaar in the Bazaar developer documentation\n", "Found: http://wiki.bazaar.canonical.com/BzrLib\n" ]
[ 3, 1 ]
[]
[]
[ "bazaar", "python" ]
stackoverflow_0002864789_bazaar_python.txt
Q: Python Class Variables Question I have some doubt about python's class variables. As my understanding, if I define a class variable, which is declared outside the __init__() function, this variable will create only once as a static variable in C++. This seems right for some python types, for instance, dict and list type, but for those base type, e.g. int,float, is not the same. For example: class A: dict1={} list1=list() int1=3 def add_stuff(self, k, v): self.dict1[k]=v self.list1.append(k) self.int1=k def print_stuff(self): print self.dict1,self.list1,self.int1 a1 = A() a1.add_stuff(1, 2) a1.print_stuff() a2=A() a2.print_stuff() The output is: {1: 2} [1] 1 {1: 2} [1] 3 I understand the results of dict1 and list1, but why does int1 behavior different? A: The difference is that you never assign to self.dict1 or self.list1 — you only ever read those fields from the class — whereas you do assign to self.int1, thus creating an instance field that hides the class field.
Python Class Variables Question
I have some doubt about python's class variables. As my understanding, if I define a class variable, which is declared outside the __init__() function, this variable will create only once as a static variable in C++. This seems right for some python types, for instance, dict and list type, but for those base type, e.g. int,float, is not the same. For example: class A: dict1={} list1=list() int1=3 def add_stuff(self, k, v): self.dict1[k]=v self.list1.append(k) self.int1=k def print_stuff(self): print self.dict1,self.list1,self.int1 a1 = A() a1.add_stuff(1, 2) a1.print_stuff() a2=A() a2.print_stuff() The output is: {1: 2} [1] 1 {1: 2} [1] 3 I understand the results of dict1 and list1, but why does int1 behavior different?
[ "The difference is that you never assign to self.dict1 or self.list1 — you only ever read those fields from the class — whereas you do assign to self.int1, thus creating an instance field that hides the class field.\n" ]
[ 7 ]
[]
[]
[ "class_variables", "python" ]
stackoverflow_0002865538_class_variables_python.txt
Q: Openid not working in OSQA hosted on hostgator I have installed osqa on server hosted on hostgator. Openid is not working at all. When I click on google under login I get a Page not found (404) error. What could be the reason for this? A: as you noted in your comment on a similar question at http://meta.osqa.net this was a problem with some whitelist issue between Google and hostgator, and apparently they have resolved it. As far as we know, the OSQA openid support works beautifully, and this issue was entirely on the hostgator side.
Openid not working in OSQA hosted on hostgator
I have installed osqa on server hosted on hostgator. Openid is not working at all. When I click on google under login I get a Page not found (404) error. What could be the reason for this?
[ "as you noted in your comment on a similar question at http://meta.osqa.net this was a problem with some whitelist issue between Google and hostgator, and apparently they have resolved it. As far as we know, the OSQA openid support works beautifully, and this issue was entirely on the hostgator side.\n" ]
[ 1 ]
[]
[]
[ "openid", "osqa", "python" ]
stackoverflow_0002856789_openid_osqa_python.txt
Q: For Django models, is there a shortcut for seeing if a record exists? Say I have a table People, is there a way to just quickly check if a People object exists with a name of 'Fred'? I know I can query People.objects.filter(Name='Fred') and then check the length of the returned result, but is there a way to do it in a more elegant way? A: Update: As mentioned in more recent answers, since Django 1.2 you can use the exists() method instead (link). Original Answer: Dont' use len() on the result, you should use People.objects.filter(Name='Fred').count(). According to the django documentation, count() performs a SELECT COUNT(*) behind the scenes, so you should always use count() rather than loading all of the record into Python objects and calling len() on the result (unless you need to load the objects into memory anyway, in which case len() will be faster). source: Django docs A: An exists() method in the QuerySet API is available since Django 1.2. A: You could use count() For example: People.objects.filter(Name='Fred').count() If the Name column is unique then you could do: try: person = People.objects.get(Name='Fred') except (People.DoesNotExist): # Do something else... You could also use get_object_or_404() For example: from django.shortcuts import get_object_or_404 get_object_or_404(People, Name='Fred') A: As of Django 1.2 you could use .exists() on a QuerySet, but in previous versions you may enjoy very effective trick described in this ticket.
For Django models, is there a shortcut for seeing if a record exists?
Say I have a table People, is there a way to just quickly check if a People object exists with a name of 'Fred'? I know I can query People.objects.filter(Name='Fred') and then check the length of the returned result, but is there a way to do it in a more elegant way?
[ "Update: \nAs mentioned in more recent answers, since Django 1.2 you can use the exists() method instead (link).\n\nOriginal Answer:\nDont' use len() on the result, you should use People.objects.filter(Name='Fred').count(). According to the django documentation, \n\ncount() performs a SELECT COUNT(*)\n behind the scenes, so you should\n always use count() rather than loading\n all of the record into Python objects\n and calling len() on the result\n (unless you need to load the objects\n into memory anyway, in which case\n len() will be faster).\n\nsource: Django docs\n", "An exists() method in the QuerySet API is available since Django 1.2.\n", "You could use count() For example:\nPeople.objects.filter(Name='Fred').count()\n\nIf the Name column is unique then you could do:\ntry:\n person = People.objects.get(Name='Fred')\nexcept (People.DoesNotExist):\n # Do something else...\n\nYou could also use get_object_or_404() For example:\nfrom django.shortcuts import get_object_or_404\nget_object_or_404(People, Name='Fred')\n\n", "As of Django 1.2 you could use .exists() on a QuerySet, but in previous versions you may enjoy very effective trick described in this ticket.\n" ]
[ 49, 47, 10, 8 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002854080_django_django_models_python.txt
Q: How do I get the application title of a Google AppEngine app from within that app Under the application settings page in the Administration console, it is possible to specify a name for the application, AFAIK this is used in the login page when using the users API to login. I would like to be able to use this information within an application, currently, the title is also specified in a separate configuration file, but configuration repetition is something I would like to avoid if at all possible. Is there some way for a GAE application to determine the "Application Title"? Oh, also, I am using python. A: There's actually a way to do it, but it might be a little too much on the hacky side.. you can get the title (ab)using the users API like this: >>> from google.appengine.api import users >>> import urllib >>> url = users.create_login_url() >>> url_dict = dict((p.split('=') for p in url.split('&'))) >>> urllib.unquote_plus(url_dict['ahname']) 'App Engine Console' I tried it on the App Engine Console linked by jbochi (great link btw, thanks!). Not to sure weather I'd put such code into production, though. Further diving into google.appengine.api.user_service might turn up a saner way. A: I believe that's not possible, unfortunately. Using the app enine console, I could not find the application title on the environment variables. >>> for key, value in os.environ.iteritems(): ... print key, value ... HTTP_REFERER http://con.appspot.com/console/ SERVER_SOFTWARE Google App Engine/1.3.4 SCRIPT_NAME REQUEST_METHOD POST PATH_INFO /console/statement HTTP_ORIGIN http://con.appspot.com SERVER_PROTOCOL HTTP/1.1 QUERY_STRING USER_IS_ADMIN 0 CONTENT_LENGTH 68 HTTP_ACCEPT_CHARSET ISO-8859-1,utf-8;q=0.7,*;q=0.3 HTTP_USER_AGENT Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.1.249.1064 Safari/532.5,gzip(gfe) TZ UTC HTTP_COOKIE __utmz=2586530.1263046728.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); ACSID=AJKiYcHZZt2WuvaQNPhvMLL3RhbTYHNsWUo54MIQVw8RCJDiiLZHChRq46hwNj6EN7mdJ9GRYXgYC33jDlHu4iq1-zNHRzr9-0V8vWSuKWIUb7wwErYzRtddAkzZKq_nOrCR4p5UxV5zwRnDCQVJn8QT1ZzXJe3cLsF3flKIIQzcGYNXWc_vLcIBOTm-FcXVdeFCXdRhppZRbXi5j-stKvcdrj7q8cv95YGX94a6FYA_P_UfDRkEZ5mc_UxMnHM5J1LcQQhzyJEtb6sDxQEuMUzcve5AoaXDxCCLgaWPq6f4YlNeINM8pm7x5-LWhV7-kCgSW1KqygZaR1q-qtsfnWJwOjtxvOOD_ERudh85LMb9p1kJXVxHuWoWoRxCfN_tRFpVPiZJM6UBnsI6nmtQGjhLLN6rpamyn6RXG5uxf6paQQKXwG3cM0ujx3e7-RpsRM18gMFTdrncs1zcrR5ZjKKeAjKrw_sX69V31KiHx4XAjwRz2lR61PymJDw57OyamUXMuDuLYrc_; __utma=2586530.845840213.1263046728.1264248611.1274271554.4; __utmc=2586530; __utmb=2586530.3.10.1274271554 SERVER_NAME con.appspot.com REMOTE_ADDR 64.209.18.36 HTTP_VIA 1.1 BRSOPRX002 PATH_TRANSLATED /base/data/home/apps/con/1-0beta3.330900106084229577/console/app/console.py SERVER_PORT 80 CONTENT_TYPE application/x-www-form-urlencoded HTTP_X_REQUESTED_WITH XMLHttpRequest CURRENT_VERSION_ID 1-0beta3.330900106084229577 USER_ORGANIZATION HTTP_HOST con.appspot.com HTTPS off APPLICATION_ID con HTTP_CONTENT_TYPE application/x-www-form-urlencoded USER_EMAIL XXXXX@gmail.com HTTP_ACCEPT application/json, text/javascript, */* DATACENTER na5 USER_ID 105014683574647550247 HTTP_ACCEPT_LANGUAGE en-US,en;q=0.8 USER_NICKNAME XXXXX HTTP_CONTENT_LENGTH 68 AUTH_DOMAIN gmail.com USER apphosting
How do I get the application title of a Google AppEngine app from within that app
Under the application settings page in the Administration console, it is possible to specify a name for the application, AFAIK this is used in the login page when using the users API to login. I would like to be able to use this information within an application, currently, the title is also specified in a separate configuration file, but configuration repetition is something I would like to avoid if at all possible. Is there some way for a GAE application to determine the "Application Title"? Oh, also, I am using python.
[ "There's actually a way to do it, but it might be a little too much on the hacky side.. you can get the title (ab)using the users API like this:\n>>> from google.appengine.api import users\n>>> import urllib\n>>> url = users.create_login_url()\n>>> url_dict = dict((p.split('=') for p in url.split('&')))\n>>> urllib.unquote_plus(url_dict['ahname'])\n'App Engine Console'\n\nI tried it on the App Engine Console linked by jbochi (great link btw, thanks!). Not to sure weather I'd put such code into production, though. Further diving into google.appengine.api.user_service might turn up a saner way.\n", "I believe that's not possible, unfortunately.\nUsing the app enine console, I could not find the application title on the environment variables.\n>>> for key, value in os.environ.iteritems():\n... print key, value\n... \nHTTP_REFERER http://con.appspot.com/console/\nSERVER_SOFTWARE Google App Engine/1.3.4\nSCRIPT_NAME \nREQUEST_METHOD POST\nPATH_INFO /console/statement\nHTTP_ORIGIN http://con.appspot.com\nSERVER_PROTOCOL HTTP/1.1\nQUERY_STRING \nUSER_IS_ADMIN 0\nCONTENT_LENGTH 68\nHTTP_ACCEPT_CHARSET ISO-8859-1,utf-8;q=0.7,*;q=0.3\nHTTP_USER_AGENT Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.1.249.1064 Safari/532.5,gzip(gfe)\nTZ UTC\nHTTP_COOKIE __utmz=2586530.1263046728.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); ACSID=AJKiYcHZZt2WuvaQNPhvMLL3RhbTYHNsWUo54MIQVw8RCJDiiLZHChRq46hwNj6EN7mdJ9GRYXgYC33jDlHu4iq1-zNHRzr9-0V8vWSuKWIUb7wwErYzRtddAkzZKq_nOrCR4p5UxV5zwRnDCQVJn8QT1ZzXJe3cLsF3flKIIQzcGYNXWc_vLcIBOTm-FcXVdeFCXdRhppZRbXi5j-stKvcdrj7q8cv95YGX94a6FYA_P_UfDRkEZ5mc_UxMnHM5J1LcQQhzyJEtb6sDxQEuMUzcve5AoaXDxCCLgaWPq6f4YlNeINM8pm7x5-LWhV7-kCgSW1KqygZaR1q-qtsfnWJwOjtxvOOD_ERudh85LMb9p1kJXVxHuWoWoRxCfN_tRFpVPiZJM6UBnsI6nmtQGjhLLN6rpamyn6RXG5uxf6paQQKXwG3cM0ujx3e7-RpsRM18gMFTdrncs1zcrR5ZjKKeAjKrw_sX69V31KiHx4XAjwRz2lR61PymJDw57OyamUXMuDuLYrc_; __utma=2586530.845840213.1263046728.1264248611.1274271554.4; __utmc=2586530; __utmb=2586530.3.10.1274271554\nSERVER_NAME con.appspot.com\nREMOTE_ADDR 64.209.18.36\nHTTP_VIA 1.1 BRSOPRX002\nPATH_TRANSLATED /base/data/home/apps/con/1-0beta3.330900106084229577/console/app/console.py\nSERVER_PORT 80\nCONTENT_TYPE application/x-www-form-urlencoded\nHTTP_X_REQUESTED_WITH XMLHttpRequest\nCURRENT_VERSION_ID 1-0beta3.330900106084229577\nUSER_ORGANIZATION \nHTTP_HOST con.appspot.com\nHTTPS off\nAPPLICATION_ID con\nHTTP_CONTENT_TYPE application/x-www-form-urlencoded\nUSER_EMAIL XXXXX@gmail.com\nHTTP_ACCEPT application/json, text/javascript, */*\nDATACENTER na5\nUSER_ID 105014683574647550247\nHTTP_ACCEPT_LANGUAGE en-US,en;q=0.8\nUSER_NICKNAME XXXXX\nHTTP_CONTENT_LENGTH 68\nAUTH_DOMAIN gmail.com\nUSER apphosting\n\n" ]
[ 2, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002864747_google_app_engine_python.txt
Q: From interpeted to native code: "dynamic" languages compiler support First, I am aware that dynamic languages is a term used mainly by a vendor; I am using it just to have a container word to include languages like Perl (a favorite of mine), Python, Tcl, Ruby, PHP and so on. They are interpreted but I am interested here to refer to languages featuring strong capability to support the programmer efficiency and the support for typical constructs of modern interpreted languages My question is: there are dynamic languages can be compiled efficiently in native executable code - typically for Windows platforms? Which ones? Maybe using some third part ad-hoc tools? I am not talking about huge executables carrying with them a full interpreter or some similar tricks nor some smart module able to include its own dependances or some required modules, but a honest, straight, standard, solid executable code. If not, there is some technical reason inhibiting the availability of such a best-of-both-world feature? Thanks! Daniel A: I think you're operating under a misunderstanding: These executables aren't huge because they just lump the interpreter in there, they're huge because the whole runtime is in there. On Windows, most of your runtime is already installed, so you don't have to ship it. You think your program is small, but a quick look at the virtual memory mappings will tell you that even a small "hello-world" type program written in C is a couple megabytes big. That's just how big useful runtimes are. If you really want to keep your ship-size small, your only choice is to use the runtimes that are already there, and that means C/C++ and (recently) dot-net. If you really can't swallow the runtime, Forth is as small as it gets. The best, most aggressive dynamic languages with the best compilers for Windows are the commercial Lisps. They do a lot of inlining and pruning when producing executables, so you end up shipping only what you use. They are still 1.5x to 5x larger than C/C++ programs. As far as languages that you know: Perl is as fat as they get. ActiveState has perlapp which I'm sure you're already aware of, but you dismissed because of it's size. Revisit it if you can. Now, to answer your question (is) there is some technical reason inhibiting the availability of such a best-of-both-world feature?: Yes. Perl cannot be statically analyzed (proof), which means there's no way for a perl compiler to tell what can be discarded. That means every part of Perl's runtime needs to be available to your program becuase there's no way for your program to indicate what parts can be discarded. That means that getting a smaller executable is equivalent to getting a smaller runtime, and you should be comfortable accepting that if the perl developers knew how to make the perl runtime smaller without discarding any features, they'd probably do it. If you are willing to write in a strict subset of Python or PHP, these languages can be analyzed. Shed Skin and HipHop-php are pretty good, but they're still quite large, and they don't support all of Pythons and PHP's features which means that some modules will simply not work. To my knowledge, nobody has implemented pruning for either of these languages (most of the focus in these compilers is in improving their lackluster performance) and it may be another decade or more before anyone bothers, however these still will be the restrictions you have to accept when doing this sort of thing. A: The PyPy project does what you describe for a fairly complete subset of Python. In the general case, this is a very hard problem to solve, largely due to the very attributes that make these languages "dynamic": late binding, weakly-typed variables, data structures and containers, eval facilities, a fuzzy divide between programming and meta-programming, etc. But a lot of effort is being poured into it, such as the JavaScript JIT-compiler projects listed here. A: Shed Skin is an experimental (and restricted) Python-to-C++ compiler that can do what you describe. As Marcelo indicates above with PyPy, there are limitations on what you can compile with Shed Skin, but if you are willing to accept the restrictions, you can achieve large speedups.
From interpeted to native code: "dynamic" languages compiler support
First, I am aware that dynamic languages is a term used mainly by a vendor; I am using it just to have a container word to include languages like Perl (a favorite of mine), Python, Tcl, Ruby, PHP and so on. They are interpreted but I am interested here to refer to languages featuring strong capability to support the programmer efficiency and the support for typical constructs of modern interpreted languages My question is: there are dynamic languages can be compiled efficiently in native executable code - typically for Windows platforms? Which ones? Maybe using some third part ad-hoc tools? I am not talking about huge executables carrying with them a full interpreter or some similar tricks nor some smart module able to include its own dependances or some required modules, but a honest, straight, standard, solid executable code. If not, there is some technical reason inhibiting the availability of such a best-of-both-world feature? Thanks! Daniel
[ "I think you're operating under a misunderstanding: These executables aren't huge because they just lump the interpreter in there, they're huge because the whole runtime is in there.\nOn Windows, most of your runtime is already installed, so you don't have to ship it. You think your program is small, but a quick look at the virtual memory mappings will tell you that even a small \"hello-world\" type program written in C is a couple megabytes big.\nThat's just how big useful runtimes are.\nIf you really want to keep your ship-size small, your only choice is to use the runtimes that are already there, and that means C/C++ and (recently) dot-net.\nIf you really can't swallow the runtime, Forth is as small as it gets. \nThe best, most aggressive dynamic languages with the best compilers for Windows are the commercial Lisps. They do a lot of inlining and pruning when producing executables, so you end up shipping only what you use. They are still 1.5x to 5x larger than C/C++ programs.\nAs far as languages that you know: Perl is as fat as they get. ActiveState has perlapp which I'm sure you're already aware of, but you dismissed because of it's size. Revisit it if you can.\nNow, to answer your question (is) there is some technical reason inhibiting the availability of such a best-of-both-world feature?: Yes.\nPerl cannot be statically analyzed (proof), which means there's no way for a perl compiler to tell what can be discarded. That means every part of Perl's runtime needs to be available to your program becuase there's no way for your program to indicate what parts can be discarded.\nThat means that getting a smaller executable is equivalent to getting a smaller runtime, and you should be comfortable accepting that if the perl developers knew how to make the perl runtime smaller without discarding any features, they'd probably do it.\nIf you are willing to write in a strict subset of Python or PHP, these languages can be analyzed. Shed Skin and HipHop-php are pretty good, but they're still quite large, and they don't support all of Pythons and PHP's features which means that some modules will simply not work. To my knowledge, nobody has implemented pruning for either of these languages (most of the focus in these compilers is in improving their lackluster performance) and it may be another decade or more before anyone bothers, however these still will be the restrictions you have to accept when doing this sort of thing.\n", "The PyPy project does what you describe for a fairly complete subset of Python.\nIn the general case, this is a very hard problem to solve, largely due to the very attributes that make these languages \"dynamic\": late binding, weakly-typed variables, data structures and containers, eval facilities, a fuzzy divide between programming and meta-programming, etc. But a lot of effort is being poured into it, such as the JavaScript JIT-compiler projects listed here.\n", "Shed Skin is an experimental (and restricted) Python-to-C++ compiler that can do what you describe. As Marcelo indicates above with PyPy, there are limitations on what you can compile with Shed Skin, but if you are willing to accept the restrictions, you can achieve large speedups.\n" ]
[ 4, 2, 1 ]
[]
[]
[ "perl", "programming_languages", "python" ]
stackoverflow_0002865669_perl_programming_languages_python.txt
Q: Python3 function annotations for type hinting versus Boo I've started on a medium-sized project in python, and I decided to use python 3 because I'm not using any large external libraries and py3k has some nice new syntactic sugar and more importantly function annotations. However, it seems like none of WingIDE, Pydev, or pycharm actually have any support for type hinting using function annotations. If I want something resembling static typing in python, is switching to boo a reasonable option? A: Boo is a great Python-like statically-typed language, but keep in mind that there more differences than just static typing. Actually you can also do duck typing on Boo. Technically, I'd say the biggest difference is that Boo runs on Mono/.Net so the libraries and framework are totally different. SharpDevelop and MonoDevelop both have good support for Boo. There's also a Visual Studio 2010 plugin that adds Boo support. It's still alpha, yet already usable. A: You could try with Cython. It is in some way CPython with static typing. See also this link
Python3 function annotations for type hinting versus Boo
I've started on a medium-sized project in python, and I decided to use python 3 because I'm not using any large external libraries and py3k has some nice new syntactic sugar and more importantly function annotations. However, it seems like none of WingIDE, Pydev, or pycharm actually have any support for type hinting using function annotations. If I want something resembling static typing in python, is switching to boo a reasonable option?
[ "Boo is a great Python-like statically-typed language, but keep in mind that there more differences than just static typing. Actually you can also do duck typing on Boo.\nTechnically, I'd say the biggest difference is that Boo runs on Mono/.Net so the libraries and framework are totally different.\nSharpDevelop and MonoDevelop both have good support for Boo. There's also a Visual Studio 2010 plugin that adds Boo support. It's still alpha, yet already usable.\n", "You could try with Cython. It is in some way CPython with static typing.\nSee also this link\n" ]
[ 4, 1 ]
[]
[]
[ "boo", "ide", "pydev", "python" ]
stackoverflow_0002865130_boo_ide_pydev_python.txt
Q: Comparable type in extension module To implement != and == for my CPython extension type, should I implement tp_compare, tp_richcompare or both? Under what circumstances is each of them called? A: tp_richcompare is analogous to the rich comparison special methods in the Python language itself. It is chosen in preference to tp_compare when the comparison operators are invoked on the class. Use tp_richcompare when you want finer control over the comparison logic. For instance, there might be a very cheap way to determine equality, but not precedence. Say memcmp(a, b, sizeof(*a)) == 0 indicates that two very complex data structures are equal, but memcmp(a, b, sizeof(*a)) < 0 doesn't indicate that a is less than b, which instead requires an expensive algorithm to determine. The tp_compare function would require that you always use the expensive algorithm in order to return either a -1, 0 or 1. The tp_richcompare function, OTOH, tells you which comparison is intended, so you can choose either the expensive or the cheap algorithm, depending on the need at hand. An additional advantage of tp_richcompare is that you can raise exceptions for operations that don't make sense, such as u < v where u and v are points in space.
Comparable type in extension module
To implement != and == for my CPython extension type, should I implement tp_compare, tp_richcompare or both? Under what circumstances is each of them called?
[ "tp_richcompare is analogous to the rich comparison special methods in the Python language itself. It is chosen in preference to tp_compare when the comparison operators are invoked on the class.\nUse tp_richcompare when you want finer control over the comparison logic. For instance, there might be a very cheap way to determine equality, but not precedence. Say memcmp(a, b, sizeof(*a)) == 0 indicates that two very complex data structures are equal, but memcmp(a, b, sizeof(*a)) < 0 doesn't indicate that a is less than b, which instead requires an expensive algorithm to determine. The tp_compare function would require that you always use the expensive algorithm in order to return either a -1, 0 or 1. The tp_richcompare function, OTOH, tells you which comparison is intended, so you can choose either the expensive or the cheap algorithm, depending on the need at hand.\nAn additional advantage of tp_richcompare is that you can raise exceptions for operations that don't make sense, such as u < v where u and v are points in space.\n" ]
[ 6 ]
[]
[]
[ "cpython", "python" ]
stackoverflow_0002865982_cpython_python.txt
Q: gstreamer: interleaving 2 audios - link error I am trying to interleave two audio files as given in the interleave GStreamer documentation: gst-launch interleave name=i ! audioconvert ! wavenc ! filesink location=file.wav filesrc location=file1.wav ! \ decodebin ! audioconvert ! "audio/x-raw-int,channels=1" ! queue ! i.sink0 filesrc location=file2.wav ! \ decodebin ! audioconvert ! "audio/x-raw-int,channels=1" ! queue ! i.sink1 But executing this command gives the following error: 0:00:00.125000000 2264 00332BC0 ERROR GST_PIPELINE grammar.tab.c:656:gst_parse_perform_link: could not link queue0 to i If I remove the second filesrc related commands i.e. all the command after "filesrc location=file2.wav, the command runs fine. What is wrong with the above command? Thanks A: try gst-launch interleave name=i ! audioconvert ! wavenc ! filesink location=file.wav filesrc location=file1.wav ! \ decodebin ! audioconvert ! "audio/x-raw-int,channels=1" ! queue ! i. filesrc location=file2.wav ! \ decodebin ! audioconvert ! "audio/x-raw-int,channels=1" ! queue ! i. the sink pads for the interleave element are request only, so i'm betting the i.sink0 pad does not exist when gst-launch tries to link the elements. leaving a single period (i.) tells gst-launch to try all pads until a suitable one is found. for anything but the most basic examples, you're better off to create the pipeline manually in an easy high-level language like python. see also man gst-launch
gstreamer: interleaving 2 audios - link error
I am trying to interleave two audio files as given in the interleave GStreamer documentation: gst-launch interleave name=i ! audioconvert ! wavenc ! filesink location=file.wav filesrc location=file1.wav ! \ decodebin ! audioconvert ! "audio/x-raw-int,channels=1" ! queue ! i.sink0 filesrc location=file2.wav ! \ decodebin ! audioconvert ! "audio/x-raw-int,channels=1" ! queue ! i.sink1 But executing this command gives the following error: 0:00:00.125000000 2264 00332BC0 ERROR GST_PIPELINE grammar.tab.c:656:gst_parse_perform_link: could not link queue0 to i If I remove the second filesrc related commands i.e. all the command after "filesrc location=file2.wav, the command runs fine. What is wrong with the above command? Thanks
[ "try\ngst-launch interleave name=i ! audioconvert ! wavenc ! filesink location=file.wav filesrc location=file1.wav ! \\\ndecodebin ! audioconvert ! \"audio/x-raw-int,channels=1\" ! queue ! i. filesrc location=file2.wav ! \\\ndecodebin ! audioconvert ! \"audio/x-raw-int,channels=1\" ! queue ! i.\n\nthe sink pads for the interleave element are request only, so i'm betting the i.sink0 pad does not exist when gst-launch tries to link the elements. leaving a single period (i.) tells gst-launch to try all pads until a suitable one is found.\nfor anything but the most basic examples, you're better off to create the pipeline manually in an easy high-level language like python.\nsee also\nman gst-launch\n\n" ]
[ 0 ]
[]
[]
[ "c#", "c++", "gstreamer", "python" ]
stackoverflow_0002306605_c#_c++_gstreamer_python.txt
Q: Reading a binary file in Python into a struct How do I go about opening a binary data file in Python and reading back the values one long at a time, into a struct. I have something like this at the moment but I think this will keep overwriting idList, I want to append to it, so I end up with a tuple of all the long values in the file - file = open(filename, "rb") try: bytes_read = file.read(struct.calcsize("=l")) while bytes_read: # Read 4 bytes(long integer) idList = struct.unpack("=l", bytes_read) bytes_read = file.read(struct.calcsize("=l")) finally: file.close() A: Simplest (python 2.6 or better): import array idlist = array.array('l') with open(filename, "rb") as f: while True: try: idlist.fromfile(f, 2000) except EOFError: break idtuple = tuple(idlist) Tuples are immutable, so they can't be built incrementally: so you have to build a different (mutable) sequence, then call tuple on it at the end. If you don't actually need specifically a tuple, of course, you can save the last, costly step and keep the array or list or whatever. Avoiding trampling over built-in names like file is advisable anyway;-). If you have to use the struct module for a job that's best handled by the array module (e.g., because of a bet), idlist = [ ] with open(filename, "rb") as f: while True: bytes_read = f.read(struct.calcsize("=l")) if not bytes_read: break oneid = struct.unpack("=l", bytes_read)[0] idlist.append(oneid) The with statement (also available in 2.5 with an import form the future) is better than the old try/finally in clarity and conciseness. A: Change idList = struct.unpack("=l", bytes_read) to idList.append(struct.unpack("=l", bytes_read)[0])
Reading a binary file in Python into a struct
How do I go about opening a binary data file in Python and reading back the values one long at a time, into a struct. I have something like this at the moment but I think this will keep overwriting idList, I want to append to it, so I end up with a tuple of all the long values in the file - file = open(filename, "rb") try: bytes_read = file.read(struct.calcsize("=l")) while bytes_read: # Read 4 bytes(long integer) idList = struct.unpack("=l", bytes_read) bytes_read = file.read(struct.calcsize("=l")) finally: file.close()
[ "Simplest (python 2.6 or better):\nimport array\nidlist = array.array('l')\nwith open(filename, \"rb\") as f:\n while True:\n try: idlist.fromfile(f, 2000)\n except EOFError: break\nidtuple = tuple(idlist)\n\nTuples are immutable, so they can't be built incrementally: so you have to build a different (mutable) sequence, then call tuple on it at the end. If you don't actually need specifically a tuple, of course, you can save the last, costly step and keep the array or list or whatever. Avoiding trampling over built-in names like file is advisable anyway;-).\nIf you have to use the struct module for a job that's best handled by the array module (e.g., because of a bet),\nidlist = [ ]\nwith open(filename, \"rb\") as f:\n while True:\n bytes_read = f.read(struct.calcsize(\"=l\"))\n if not bytes_read: break\n oneid = struct.unpack(\"=l\", bytes_read)[0]\n idlist.append(oneid)\n\nThe with statement (also available in 2.5 with an import form the future) is better than the old try/finally in clarity and conciseness.\n", "Change \nidList = struct.unpack(\"=l\", bytes_read)\n\nto\nidList.append(struct.unpack(\"=l\", bytes_read)[0])\n\n" ]
[ 6, 0 ]
[]
[]
[ "binaryfiles", "python", "struct" ]
stackoverflow_0002865996_binaryfiles_python_struct.txt
Q: How to save to two tables using one SQLAlchemy model I have an SQLAlchemy ORM class, linked to MySQL, which works great at saving the data I need down to the underlying table. However, I would like to also save the identical data to a second archive table. Here's some psudocode to try and explain what I mean my_data = Data() #An ORM Class my_data.name = "foo" #This saves just to the 'data' table session.add(my_data) #This will save it to the identical 'backup_data' table my_data_archive = my_data my_data_archive.__tablename__ = 'backup_data' session.add(my_data_archive) #And commits them both session.commit() Just a heads up, I am not interested in mapping a class to a JOIN, as in: http://www.sqlalchemy.org/docs/05/mappers.html#mapping-a-class-against-multiple-tables A: I list some options below. I would go for the DB trigger if you do not need to work on those objects in your model. use database trigger to do this job for you create a SessionExtension which will create and add to session copy-objects (usually on before_flush). Edit-1: You can take versioning example from SA as a basic; this code is doing even more then you need. see SA Versioning example which will not only give you a copy of the object, but the whole version history, which might be what you wish for see Reverse mapping from a table to a model in SQLAlchemy question, where the proposed solution is described in the blogpost. A: Create 2 identical models: one mapped to main table and another mapped to archive table. Create a MapperExtension with redefined method after_insert() (depending on your demands you might also need after_update() and after_delete()). This method should copy data from main model to archive and add it to the session. There are some tricks to copy all columns and many-to-many relations automagically. Note, that you'll have to flush() session twice to store both objects since unit of work is computed before mapper extension adds new object to the session. You can redefine Session.flush() to take care of this problem. Also auto-incremented fields are assigned when the object is flushed, so you'll have to delay copying if you need them too. It is one possible scenario which is proved to work. I'd like to know if there is a better way.
How to save to two tables using one SQLAlchemy model
I have an SQLAlchemy ORM class, linked to MySQL, which works great at saving the data I need down to the underlying table. However, I would like to also save the identical data to a second archive table. Here's some psudocode to try and explain what I mean my_data = Data() #An ORM Class my_data.name = "foo" #This saves just to the 'data' table session.add(my_data) #This will save it to the identical 'backup_data' table my_data_archive = my_data my_data_archive.__tablename__ = 'backup_data' session.add(my_data_archive) #And commits them both session.commit() Just a heads up, I am not interested in mapping a class to a JOIN, as in: http://www.sqlalchemy.org/docs/05/mappers.html#mapping-a-class-against-multiple-tables
[ "I list some options below. I would go for the DB trigger if you do not need to work on those objects in your model.\n\nuse database trigger to do this job for you\ncreate a SessionExtension which will create and add to session copy-objects (usually on before_flush). Edit-1: You can take versioning example from SA as a basic; this code is doing even more then you need.\nsee SA Versioning example which will not only give you a copy of the object, but the whole version history, which might be what you wish for\nsee Reverse mapping from a table to a model in SQLAlchemy question, where the proposed solution is described in the blogpost.\n\n", "Create 2 identical models: one mapped to main table and another mapped to archive table. Create a MapperExtension with redefined method after_insert() (depending on your demands you might also need after_update() and after_delete()). This method should copy data from main model to archive and add it to the session. There are some tricks to copy all columns and many-to-many relations automagically.\nNote, that you'll have to flush() session twice to store both objects since unit of work is computed before mapper extension adds new object to the session. You can redefine Session.flush() to take care of this problem. Also auto-incremented fields are assigned when the object is flushed, so you'll have to delay copying if you need them too.\nIt is one possible scenario which is proved to work. I'd like to know if there is a better way.\n" ]
[ 3, 1 ]
[]
[]
[ "mysql", "python", "sql", "sqlalchemy" ]
stackoverflow_0002864904_mysql_python_sql_sqlalchemy.txt
Q: Using Python, How to copy files in 'temporary internet files' folder in Windows I am using this code to find files recursively in a folder , with size greater than 50000 bytes. def listall(parent): lis=[] for root, dirs, files in os.walk(parent): for name in files: if os.path.getsize(os.path.join(root,name))>500000: lis.append(os.path.join(root,name)) return lis This is working fine. But when I used this on 'temporary internet files' folder in windows, am getting this error. Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> listall(a) File "<pyshell#2>", line 5, in listall if os.path.getsize(os.path.join(root,name))>500000: File "C:\Python26\lib\genericpath.py", line 49, in getsize return os.stat(filename).st_size WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: 'C:\\Documents and Settings\\khedarnatha\\Local Settings\\Temporary Internet Files\\Content.IE5\\EDS8C2V7\\??????+1[1].jpg' I think this is because windows gives names with special characters in this specific folder... Please help to sort out this issue. A: It's because the saved file ‘(something)+1[1].jpg’ has non-ASCII characters in its name, characters that don't fit into the ‘system default code page’ (also misleadingly known as ‘ANSI’). Programs like Python that use the byte-based C standard library (stdio) file access functions have big problems with Unicode filenames. On other platforms they can just use UTF-8 and everyone's happy, but on Windows the system default code page is never UTF-8, so there will always be characters that can't be represented in the given encoding. They'll get replaced with ? or sometimes other similar-looking characters, and then when you try to read the files with mangled names you'll get errors like the above. Which code page you get depends on your locale: on Western Windows installs it'll be cp1252 (similar to ISO-8859-1, ‘Latin-1’), so you'll only be to use these characters. Luckily, reasonably recent versions of Python (2.3+, according to PEP277) can also directly support Unicode filenames by using the native Win32 APIs instead of stdio. If you pass a Unicode string into os.listdir(), Python will use these native-Unicode APIs and you'll get Unicode strings back, which will include the original characters in the filename instead of mangled ones. So if you call listall with a Unicode pathname: listall(ur'C:\Documents and Settings\khedarnatha\Local Settings\Temporary Internet Files') it should Just Work.
Using Python, How to copy files in 'temporary internet files' folder in Windows
I am using this code to find files recursively in a folder , with size greater than 50000 bytes. def listall(parent): lis=[] for root, dirs, files in os.walk(parent): for name in files: if os.path.getsize(os.path.join(root,name))>500000: lis.append(os.path.join(root,name)) return lis This is working fine. But when I used this on 'temporary internet files' folder in windows, am getting this error. Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> listall(a) File "<pyshell#2>", line 5, in listall if os.path.getsize(os.path.join(root,name))>500000: File "C:\Python26\lib\genericpath.py", line 49, in getsize return os.stat(filename).st_size WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: 'C:\\Documents and Settings\\khedarnatha\\Local Settings\\Temporary Internet Files\\Content.IE5\\EDS8C2V7\\??????+1[1].jpg' I think this is because windows gives names with special characters in this specific folder... Please help to sort out this issue.
[ "It's because the saved file ‘(something)+1[1].jpg’ has non-ASCII characters in its name, characters that don't fit into the ‘system default code page’ (also misleadingly known as ‘ANSI’).\nPrograms like Python that use the byte-based C standard library (stdio) file access functions have big problems with Unicode filenames. On other platforms they can just use UTF-8 and everyone's happy, but on Windows the system default code page is never UTF-8, so there will always be characters that can't be represented in the given encoding. They'll get replaced with ? or sometimes other similar-looking characters, and then when you try to read the files with mangled names you'll get errors like the above.\nWhich code page you get depends on your locale: on Western Windows installs it'll be cp1252 (similar to ISO-8859-1, ‘Latin-1’), so you'll only be to use these characters.\nLuckily, reasonably recent versions of Python (2.3+, according to PEP277) can also directly support Unicode filenames by using the native Win32 APIs instead of stdio. If you pass a Unicode string into os.listdir(), Python will use these native-Unicode APIs and you'll get Unicode strings back, which will include the original characters in the filename instead of mangled ones. So if you call listall with a Unicode pathname:\nlistall(ur'C:\\Documents and Settings\\khedarnatha\\Local Settings\\Temporary Internet Files')\n\nit should Just Work.\n" ]
[ 3 ]
[]
[]
[ "path", "python", "unicode" ]
stackoverflow_0002866455_path_python_unicode.txt
Q: Regex to ensure group match doesn't end with a specific character I'm having trouble coming up with a regular expression to match a particular case. I have a list of tv shows in about 4 formats: Name.Of.Show.S01E01 Name.Of.Show.0101 Name.Of.Show.01x01 Name.Of.Show.101 What I want to match is the show name. My main problem is that my regex matches the name of the show with a preceding '.'. My regex is the following: "^([0-9a-zA-Z\.]+)(S[0-9]{2}E[0-9]{2}|[0-9]{4}|[0-9]{2}x[0-9]{2}|[0-9]{3})" Some Examples: >>> import re >>> SHOW_INFO = re.compile("^([0-9a-zA-Z\.]+)(S[0-9]{2}E[0-9]{2}|[0-9]{4}|[0-9]{2}x[0-9]{2}|[0-9]{3})") >>> match = SHOW_INFO.match("Name.Of.Show.S01E01") >>> match.groups() ('Name.Of.Show.', 'S01E01') >>> match = SHOW_INFO.match("Name.Of.Show.0101") >>> match.groups() ('Name.Of.Show.0', '101') >>> match = SHOW_INFO.match("Name.Of.Show.01x01") >>> match.groups() ('Name.Of.Show.', '01x01') >>> match = SHOW_INFO.match("Name.Of.Show.101") >>> match.groups() ('Name.Of.Show.', '101') So the question is how do I avoid the first group ending with a period? I realize I could simply do: var.strip(".") However, that doesn't handle the case of "Name.Of.Show.0101". Is there a way I could improve the regex to handle that case better? Thanks in advance. A: So the only real restriction on the last group is that it doesn’t contain a dot? Easy: ^(.*?)(\.[^.]+)$ This matches anything, non-greedily. The important part is the second group, which starts with a dot and then matches any non-dot character until the end of the string. This works with all your test cases. A: I think this will do: >>> regex = re.compile(r'^([0-9a-z.]+)\.(S[0-9]{2}E[0-9]{2}|[0-9]{3,4}|[0-9]{2}x[0-9]{2})$', re.I) >>> regex.match('Name.Of.Show.01x01').groups() ('Name.Of.Show', '01x01') >>> regex.match('Name.Of.Show.101').groups() ('Name.Of.Show', '101') ETA: Of course, if you're just trying to extract different bits from trusted strings you could just use string methods: >>> 'Name.Of.Show.101'.rpartition('.') ('Name.Of.Show', '.', '101') A: I believe this will do what you want: ^([0-9a-z\.]+)\.(?:S[0-9]{2}E[0-9]{2}|[0-9]{3,4}|[0-9]{2}(?:x[0-9]+)?)$ I tested this against the following list of shows: 30.Rock.S01E01 The.Office.0101 Lost.01x01 How.I.Met.Your.Mother.101 If those 4 cases are representative of the types of files you have, then that regex should place the show title in its own capture group and toss away the rest. This filter is, perhaps, a bit more restrictive than some others, but I'm a big fan of matching exactly what you need. A: It seems like the problem is that you haven't specified that the period before the last group is required, so something like ^([0-9a-zA-Z\.]+)\.(S[0-9]{2}E[0-9]{2}|[0-9]{4}|[0-9]{2}x[0-9]{2}|[0-9]{3}) might work. A: If the last part never contains a dot: ^(.*)\.([^\.]+)$
Regex to ensure group match doesn't end with a specific character
I'm having trouble coming up with a regular expression to match a particular case. I have a list of tv shows in about 4 formats: Name.Of.Show.S01E01 Name.Of.Show.0101 Name.Of.Show.01x01 Name.Of.Show.101 What I want to match is the show name. My main problem is that my regex matches the name of the show with a preceding '.'. My regex is the following: "^([0-9a-zA-Z\.]+)(S[0-9]{2}E[0-9]{2}|[0-9]{4}|[0-9]{2}x[0-9]{2}|[0-9]{3})" Some Examples: >>> import re >>> SHOW_INFO = re.compile("^([0-9a-zA-Z\.]+)(S[0-9]{2}E[0-9]{2}|[0-9]{4}|[0-9]{2}x[0-9]{2}|[0-9]{3})") >>> match = SHOW_INFO.match("Name.Of.Show.S01E01") >>> match.groups() ('Name.Of.Show.', 'S01E01') >>> match = SHOW_INFO.match("Name.Of.Show.0101") >>> match.groups() ('Name.Of.Show.0', '101') >>> match = SHOW_INFO.match("Name.Of.Show.01x01") >>> match.groups() ('Name.Of.Show.', '01x01') >>> match = SHOW_INFO.match("Name.Of.Show.101") >>> match.groups() ('Name.Of.Show.', '101') So the question is how do I avoid the first group ending with a period? I realize I could simply do: var.strip(".") However, that doesn't handle the case of "Name.Of.Show.0101". Is there a way I could improve the regex to handle that case better? Thanks in advance.
[ "So the only real restriction on the last group is that it doesn’t contain a dot? Easy:\n^(.*?)(\\.[^.]+)$\n\nThis matches anything, non-greedily. The important part is the second group, which starts with a dot and then matches any non-dot character until the end of the string.\nThis works with all your test cases.\n", "I think this will do:\n>>> regex = re.compile(r'^([0-9a-z.]+)\\.(S[0-9]{2}E[0-9]{2}|[0-9]{3,4}|[0-9]{2}x[0-9]{2})$', re.I)\n>>> regex.match('Name.Of.Show.01x01').groups()\n('Name.Of.Show', '01x01')\n>>> regex.match('Name.Of.Show.101').groups()\n('Name.Of.Show', '101')\n\nETA: Of course, if you're just trying to extract different bits from trusted strings you could just use string methods:\n>>> 'Name.Of.Show.101'.rpartition('.')\n('Name.Of.Show', '.', '101')\n\n", "I believe this will do what you want:\n^([0-9a-z\\.]+)\\.(?:S[0-9]{2}E[0-9]{2}|[0-9]{3,4}|[0-9]{2}(?:x[0-9]+)?)$\n\nI tested this against the following list of shows:\n\n30.Rock.S01E01\nThe.Office.0101\nLost.01x01\nHow.I.Met.Your.Mother.101\n\nIf those 4 cases are representative of the types of files you have, then that regex should place the show title in its own capture group and toss away the rest. This filter is, perhaps, a bit more restrictive than some others, but I'm a big fan of matching exactly what you need.\n", "It seems like the problem is that you haven't specified that the period before the last group is required, so something like ^([0-9a-zA-Z\\.]+)\\.(S[0-9]{2}E[0-9]{2}|[0-9]{4}|[0-9]{2}x[0-9]{2}|[0-9]{3}) might work.\n", "If the last part never contains a dot: ^(.*)\\.([^\\.]+)$\n" ]
[ 2, 2, 1, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002866783_python_regex.txt
Q: adding a header to pyqt list i want to add a headers and index to a list in pyqt , it's really not important what list of QT (qlistwidget , qlistview , qtablewidget, qtreeview) in short .. i want something like the spin box delegate example in the pyqt demo ... but instead of the index in the column headers i want a strings ... hope the idea is clear enough thanx in advance A: QTableWidget is likely your best choice - it uses setHorizontalHeaderLabels() and setVerticalHeaderLabels() to let you control both axes. from PyQt4 import QtGui class MyWindow(QtGui.QMainWindow): def __init__(self, parent): QtGui.QMainWindow.__init__(self, parent) table = QtGui.QTableWidget(3, 3, self) # create 3x3 table table.setHorizontalHeaderLabels(('Col 1', 'Col 2', 'Col 3')) table.setVerticalHeaderLabels(('Row 1', 'Row 2', 'Row 3')) for column in range(3): for row in range(3): table.setItem(row, column, QtGui.QWidget(self)) # your contents self.setCentralWidget(table) self.show() Of course, if you want full control over the contents and formatting of the headers, then you could use the .setHorizontalHeaderItem() and .setVerticalHeaderItem() methods to define a QTableWidgetItem for each header... See the official documentation for full details.
adding a header to pyqt list
i want to add a headers and index to a list in pyqt , it's really not important what list of QT (qlistwidget , qlistview , qtablewidget, qtreeview) in short .. i want something like the spin box delegate example in the pyqt demo ... but instead of the index in the column headers i want a strings ... hope the idea is clear enough thanx in advance
[ "QTableWidget is likely your best choice - it uses setHorizontalHeaderLabels() and setVerticalHeaderLabels() to let you control both axes. \nfrom PyQt4 import QtGui\n\nclass MyWindow(QtGui.QMainWindow):\n\n def __init__(self, parent):\n QtGui.QMainWindow.__init__(self, parent)\n\n table = QtGui.QTableWidget(3, 3, self) # create 3x3 table\n table.setHorizontalHeaderLabels(('Col 1', 'Col 2', 'Col 3'))\n table.setVerticalHeaderLabels(('Row 1', 'Row 2', 'Row 3'))\n for column in range(3):\n for row in range(3):\n table.setItem(row, column, QtGui.QWidget(self)) # your contents\n\n self.setCentralWidget(table)\n self.show()\n\nOf course, if you want full control over the contents and formatting of the headers, then you could use the .setHorizontalHeaderItem() and .setVerticalHeaderItem() methods to define a QTableWidgetItem for each header...\nSee the official documentation for full details.\n" ]
[ 9 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt" ]
stackoverflow_0002749529_pyqt_pyqt4_python_qt.txt
Q: In Python, how to find all the files under a directory, including the files in subdirectories? Is there any built in functions to find all the files under a particular directory including files under subdirectories ? I have tried this code, but not working...may be the logic itself is wrong... def fun(mydir): lis=glob.glob(mydir) length=len(lis) l,i=0,0 if len(lis): while(l+i<length): if os.path.isfile(lis[i]): final.append(lis[i]) lis.pop(i) l=l+1 i=i+1 else: i=i+1 print final fun(lis) else: print final A: There is no built-in function, but using os.walk it's trivial to construct it: import os def recursive_file_gen(mydir): for root, dirs, files in os.walk(mydir): for file in files: yield os.path.join(root, file) ETA: the os.walk function walks directory tree recursively; the recursive_file_gen function is a generator (uses yield keyword to produce next file). To get the resulting list do: list(recursive_file_gen(mydir)) A: I highly recommend this path module, written by Jason Orendorff: http://pypi.python.org/pypi/path.py/2.2 Unfortunately, his website is down now, but you can still download from the above link (or through easy_install, if you prefer). Using this path module, you can do various actions on paths, including the walking files you requested. Here's an example: from path import path my_path = path('.') for file in my_path.walkfiles(): print file for file in my_path.walkfiles('*.pdf'): print file There are also convenience functions for many other things to do with paths: In [1]: from path import path In [2]: my_dir = path('my_dir') In [3]: my_file = path('readme.txt') In [5]: print my_dir / my_file my_dir/readme.txt In [6]: joined_path = my_dir / my_file In [7]: print joined_path my_dir/readme.txt In [8]: print joined_path.parent my_dir In [9]: print joined_path.name readme.txt In [10]: print joined_path.namebase readme In [11]: print joined_path.ext .txt In [12]: joined_path.copy('some_output_path.txt') In [13]: print path('some_output_path.txt').isfile() True In [14]: print path('some_output_path.txt').isdir() False There are more operations that can be done too, but these are some of the ones that I use most often. Notice that the path class inherits from string, so it can be used wherever a string is used. Also, notice that two or more path objects can easily be joined together by using the overridden / operator. Hope this helps! A: os.walk() is what you need. But for added performance, try the package scandir. It also part of the standard library in Python 3.5 and is described in PEP 471
In Python, how to find all the files under a directory, including the files in subdirectories?
Is there any built in functions to find all the files under a particular directory including files under subdirectories ? I have tried this code, but not working...may be the logic itself is wrong... def fun(mydir): lis=glob.glob(mydir) length=len(lis) l,i=0,0 if len(lis): while(l+i<length): if os.path.isfile(lis[i]): final.append(lis[i]) lis.pop(i) l=l+1 i=i+1 else: i=i+1 print final fun(lis) else: print final
[ "There is no built-in function, but using os.walk it's trivial to construct it:\nimport os\ndef recursive_file_gen(mydir):\n for root, dirs, files in os.walk(mydir):\n for file in files:\n yield os.path.join(root, file)\n\nETA: the os.walk function walks directory tree recursively; the recursive_file_gen function is a generator (uses yield keyword to produce next file). To get the resulting list do:\nlist(recursive_file_gen(mydir))\n\n", "I highly recommend this path module, written by Jason Orendorff:\nhttp://pypi.python.org/pypi/path.py/2.2\nUnfortunately, his website is down now, but you can still download from the above link (or through easy_install, if you prefer).\nUsing this path module, you can do various actions on paths, including the walking files you requested. Here's an example:\nfrom path import path\n\nmy_path = path('.')\n\nfor file in my_path.walkfiles():\n print file\n\nfor file in my_path.walkfiles('*.pdf'):\n print file\n\nThere are also convenience functions for many other things to do with paths:\nIn [1]: from path import path\n\nIn [2]: my_dir = path('my_dir')\n\nIn [3]: my_file = path('readme.txt')\n\nIn [5]: print my_dir / my_file\nmy_dir/readme.txt\n\nIn [6]: joined_path = my_dir / my_file\n\nIn [7]: print joined_path\nmy_dir/readme.txt\n\nIn [8]: print joined_path.parent\nmy_dir\n\nIn [9]: print joined_path.name\nreadme.txt\n\nIn [10]: print joined_path.namebase\nreadme\n\nIn [11]: print joined_path.ext\n.txt\n\nIn [12]: joined_path.copy('some_output_path.txt')\n\nIn [13]: print path('some_output_path.txt').isfile()\nTrue\n\nIn [14]: print path('some_output_path.txt').isdir()\nFalse\n\nThere are more operations that can be done too, but these are some of the ones that I use most often. Notice that the path class inherits from string, so it can be used wherever a string is used. Also, notice that two or more path objects can easily be joined together by using the overridden / operator.\nHope this helps!\n", "os.walk() is what you need.\nBut for added performance, try the package scandir. It also part of the standard library in Python 3.5 and is described in PEP 471\n" ]
[ 13, 3, 2 ]
[]
[]
[ "file", "list", "python" ]
stackoverflow_0002865278_file_list_python.txt
Q: why datetime.now() shows invalid result when executed inside django server? Case 1 >>> datetime.__file__ '/usr/lib/python2.6/lib-dynload/datetime.so' >>> print datetime.datetime.now() 2010-05-19 19:45:40.202634 Case 2 from django.db import models import datetime print datetime.__file__ print "--------------------------", datetime.datetime.now() -----------Result-------- Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Validating models... /usr/lib/python2.6/lib-dynload/datetime.so -------------------------- 2010-05-19 09:16:43.987508 0 errors found A: As Mark pointed it looks like time zone difference for Japan: >>> from dateutil import tz >>> from datetime import datetime >>> utc_time = datetime(2010, 5, 19, 9, 16, 43, tzinfo=tz.tzutc()) >>> jst_time = utc_time.astimezone(tz.gettz('Japan')) >>> print utc_time 2010-05-19 09:16:43+00:00 >>> print jst_time 2010-05-19 18:16:43+09:00 Standard datetime module handle naive time only, you can add a support of time zones with dateutil (especially dateutil.tz.tzlocal() constructor).
why datetime.now() shows invalid result when executed inside django server?
Case 1 >>> datetime.__file__ '/usr/lib/python2.6/lib-dynload/datetime.so' >>> print datetime.datetime.now() 2010-05-19 19:45:40.202634 Case 2 from django.db import models import datetime print datetime.__file__ print "--------------------------", datetime.datetime.now() -----------Result-------- Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Validating models... /usr/lib/python2.6/lib-dynload/datetime.so -------------------------- 2010-05-19 09:16:43.987508 0 errors found
[ "As Mark pointed it looks like time zone difference for Japan:\n>>> from dateutil import tz\n>>> from datetime import datetime\n>>> utc_time = datetime(2010, 5, 19, 9, 16, 43, tzinfo=tz.tzutc())\n>>> jst_time = utc_time.astimezone(tz.gettz('Japan'))\n>>> print utc_time\n2010-05-19 09:16:43+00:00\n>>> print jst_time\n2010-05-19 18:16:43+09:00\n\nStandard datetime module handle naive time only, you can add a support of time zones with dateutil (especially dateutil.tz.tzlocal() constructor).\n" ]
[ 3 ]
[]
[]
[ "datetime", "django", "python" ]
stackoverflow_0002866343_datetime_django_python.txt
Q: Scraping digg rss feed with python is there a way to get the link from digg through its rss feed? or do i have to get the website and manually scrape it with a regex? i want to get the real link digg points to, not to the comments feed, from rss. example - http://feeds.digg.com/~r/digg/popular/~3/Hx0VATaafSw/Apple_Scaling_Final_Cut_Studio_Apps_to_Fit_Prosumers_2 goes to http://www.appleinsider.com/articles/10/05/18/apple_scaling_final_cut_studio_apps_to_fit_prosumers.html A: Take a look at the feedparser module. >>> import feedparser >>> d = feedparser.parse('http://feeds.digg.com/digg/popular.rss') >>> for entry in d.entries: ... print entry.link ... http://feeds.digg.com/~r/digg/popular/~3/Hx0VATaafSw/Apple_Scaling_Final_Cut_Studio_Apps_to_Fit_Prosumers_2 http://feeds.digg.com/~r/digg/popular/~3/mXb8b0QH3Rc/Skateboarder_Lives_Any_Man_s_Worst_Nightmare_video http://feeds.digg.com/~r/digg/popular/~3/61N9gFUth1k/CBS_A_bloodbath_of_cancellations http://feeds.digg.com/~r/digg/popular/~3/vZ3_6F1RAcI/Red_Dead_Redemption_Free_Roam_Done_Right (snip) A: You can use the story.getInfo method of the Digg API. One of its possible arguments is clean_title which you can parse from the link in the RSS feed. Here's a sample implementation: import feedparser import urllib2 from xml.etree import ElementTree rss_link = 'http://feeds.digg.com/digg/popular.rss' api_link = 'http://services.digg.com/1.0/endpoint?method=story.getInfo&clean_title=%s' data = feedparser.parse(rss_link) for i, e in enumerate(data.entries, 1): print '%d. Digg link: %s' % (i, e.link) title = e.link[e.link.rfind('/') + 1 :] xml = urllib2.urlopen(api_link % title).read() tree = ElementTree.fromstring(xml) print '%d. Real link: %s' % (i, tree.find('story').get('link')) ... which outputs: 1. Digg link: http://feeds.digg.com/~r/digg/popular/~3/V58R-d7nd2M/Pakistan_court_bans_Facebook_site 1. Real link: http://news.bbc.co.uk/2/hi/south_asia/8691406.stm 2. Digg link: http://feeds.digg.com/~r/digg/popular/~3/LoF6h1fTtk/Britons_spend_more_webtime_reading_news_than_looking_at_porn 2. Real link: http://www.telegraph.co.uk/technology/news/7740500/Britons-spend-more-web-time-reading-news-than-looking-at-pornography.html 3. Digg link: http://feeds.digg.com/~r/digg/popular/~3/XQUD2tR-qGQ/Sludgy_oil_begins_washing_into_Lousiana_s_coastal_marshes 3. Real link: http://www.washingtonpost.com/wp-dyn/content/article/2010/05/18/AR2010051801676.html?hpid=topnews 4. Digg link: http://feeds.digg.com/~r/digg/popular/~3/4HBB7lvCpoM/Professor_examines_the_complex_evolution_of_human_morality 4. Real link: http://www.physorg.com/news193472479.html 5. Digg link: http://feeds.digg.com/~r/digg/popular/~3/9__2-MVmSp4/How_Are_America_s_Top_Companies_Taxed_Infographic 5. Real link: http://www.mint.com/blog/trends/how-are-americas-top-companies-taxed/ ... A: It looks like you will need to use the Digg API to get the actual links to the stories, and not just the link to the digg comments. The API can give you data in XML or JSON, both of which are easily handled in python -- lxml and simplejson both work well. The other option, if you are really keen to using the RSS feeds, is to parse the digg links and then scrape the links off of that page -- but that is going to be less efficient and more prone to breaking. I've run into this issue on similar social news and blog sites -- basically they want you to land on their page before you go off to read the actual story. Understandable, but kind of annoying from a scripting point-of-view. A: Take a look at the YQL @ Yahoo... Here is a query that returns XML from digg http://developer.yahoo.com/yql/console/?q=select%20title%2Clink%20from%20rss%20where%20url%3D%22http%3A%2F%2Ffeeds.digg.com%2Fdigg%2Fpopular.rss%22 You can parse JSON or XML. Good Luck!
Scraping digg rss feed with python
is there a way to get the link from digg through its rss feed? or do i have to get the website and manually scrape it with a regex? i want to get the real link digg points to, not to the comments feed, from rss. example - http://feeds.digg.com/~r/digg/popular/~3/Hx0VATaafSw/Apple_Scaling_Final_Cut_Studio_Apps_to_Fit_Prosumers_2 goes to http://www.appleinsider.com/articles/10/05/18/apple_scaling_final_cut_studio_apps_to_fit_prosumers.html
[ "Take a look at the feedparser module.\n>>> import feedparser\n>>> d = feedparser.parse('http://feeds.digg.com/digg/popular.rss')\n>>> for entry in d.entries:\n... print entry.link\n...\nhttp://feeds.digg.com/~r/digg/popular/~3/Hx0VATaafSw/Apple_Scaling_Final_Cut_Studio_Apps_to_Fit_Prosumers_2\nhttp://feeds.digg.com/~r/digg/popular/~3/mXb8b0QH3Rc/Skateboarder_Lives_Any_Man_s_Worst_Nightmare_video\nhttp://feeds.digg.com/~r/digg/popular/~3/61N9gFUth1k/CBS_A_bloodbath_of_cancellations\nhttp://feeds.digg.com/~r/digg/popular/~3/vZ3_6F1RAcI/Red_Dead_Redemption_Free_Roam_Done_Right\n(snip)\n\n", "You can use the story.getInfo method of the Digg API. One of its possible arguments is clean_title which you can parse from the link in the RSS feed. Here's a sample implementation:\nimport feedparser\nimport urllib2\nfrom xml.etree import ElementTree\n\nrss_link = 'http://feeds.digg.com/digg/popular.rss'\napi_link = 'http://services.digg.com/1.0/endpoint?method=story.getInfo&clean_title=%s'\n\ndata = feedparser.parse(rss_link)\n\nfor i, e in enumerate(data.entries, 1):\n print '%d. Digg link: %s' % (i, e.link)\n title = e.link[e.link.rfind('/') + 1 :]\n xml = urllib2.urlopen(api_link % title).read()\n tree = ElementTree.fromstring(xml)\n print '%d. Real link: %s' % (i, tree.find('story').get('link'))\n\n... which outputs:\n1. Digg link: http://feeds.digg.com/~r/digg/popular/~3/V58R-d7nd2M/Pakistan_court_bans_Facebook_site\n1. Real link: http://news.bbc.co.uk/2/hi/south_asia/8691406.stm\n2. Digg link: http://feeds.digg.com/~r/digg/popular/~3/LoF6h1fTtk/Britons_spend_more_webtime_reading_news_than_looking_at_porn\n2. Real link: http://www.telegraph.co.uk/technology/news/7740500/Britons-spend-more-web-time-reading-news-than-looking-at-pornography.html\n3. Digg link: http://feeds.digg.com/~r/digg/popular/~3/XQUD2tR-qGQ/Sludgy_oil_begins_washing_into_Lousiana_s_coastal_marshes\n3. Real link: http://www.washingtonpost.com/wp-dyn/content/article/2010/05/18/AR2010051801676.html?hpid=topnews\n4. Digg link: http://feeds.digg.com/~r/digg/popular/~3/4HBB7lvCpoM/Professor_examines_the_complex_evolution_of_human_morality\n4. Real link: http://www.physorg.com/news193472479.html\n5. Digg link: http://feeds.digg.com/~r/digg/popular/~3/9__2-MVmSp4/How_Are_America_s_Top_Companies_Taxed_Infographic\n5. Real link: http://www.mint.com/blog/trends/how-are-americas-top-companies-taxed/\n...\n\n", "It looks like you will need to use the Digg API to get the actual links to the stories, and not just the link to the digg comments. The API can give you data in XML or JSON, both of which are easily handled in python -- lxml and simplejson both work well.\nThe other option, if you are really keen to using the RSS feeds, is to parse the digg links and then scrape the links off of that page -- but that is going to be less efficient and more prone to breaking.\nI've run into this issue on similar social news and blog sites -- basically they want you to land on their page before you go off to read the actual story. Understandable, but kind of annoying from a scripting point-of-view.\n", "Take a look at the YQL @ Yahoo...\nHere is a query that returns XML from digg\nhttp://developer.yahoo.com/yql/console/?q=select%20title%2Clink%20from%20rss%20where%20url%3D%22http%3A%2F%2Ffeeds.digg.com%2Fdigg%2Fpopular.rss%22\nYou can parse JSON or XML.\nGood Luck!\n" ]
[ 3, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002866939_python.txt
Q: Python Type Checking & Inheritance Issue I have a bit of Python code which depends on type checking. I'll try and phrase my problem in the language of math so it's clear. I have a few classes which correspond to subsets of each other and form an inheritance chain. class Real(object): pass class Integer(Real): pass class Natural(Integer): pass And I have a tuples containing types. Each of these corresponds to the domain of some function. t1 = ( Real, Real ) t2 = ( Real , Integer ) I would like to do some form of type checking such that given a another tuple ( Natural , Natural ) if every coordinate in the tuple is a subclass of the specified domains. For example for some function getcompatibles I'd like to have: getcompatibles( ( Real, Real ) ) = [ t1 ] getcompatibles( ( Real, Integer ) ) = [ t1, t2 ] getcompatibles( ( Natural, Natural ) ) = [ t1, t2 ] getcompatibles( ( Natural, Real ) ) = [ t1 ] The only solution I could come up with would be to run through every for domain (t1, t2) run through each of the types in __subclasses__ and check to see whether it isinstance is True for the given input. Thats extremely inefficient though, is there perhaps a more Pythonic way of doing this? A: def compatible_pred(obj_types, fun_signature): if len(obj_types) != len(fun_signature): return False return all(issubclass(of, ft) for of, ft in zip(obj_types, fun_signature)) def is_compatible(obj_types, fun_signatures=(t1, t2)): return [t for t in fun_signatures if compatible_pred(obj_types, t)] The is_compatible name for something that is not a predicate is really, truly confusing: why not give it a sensible name such as getcompatibles, so that the strongly predicate-sounding iscompatible could be used instead for what I've had to name compatible_pred? A: Don't check types when you don't have to and count on exception handling - with try / except to catch the instances where the expectation is violated. In Python, which is a "lazy typed" (but strongly typed, less I upset the purists) language, calling isinstance repeatedly will certainly cost you in overhead. The question I ask myself when facing such design questions is "If you didn't want this function to handle pairs of Naturals, why did you call it with them?" Presumably you are doing some sort of conditional branch predicated on is_compatible, I'd suggest you change that into a conditional call. Seeing how you intend to use the result of is_compatible would allow a more focused answer.
Python Type Checking & Inheritance Issue
I have a bit of Python code which depends on type checking. I'll try and phrase my problem in the language of math so it's clear. I have a few classes which correspond to subsets of each other and form an inheritance chain. class Real(object): pass class Integer(Real): pass class Natural(Integer): pass And I have a tuples containing types. Each of these corresponds to the domain of some function. t1 = ( Real, Real ) t2 = ( Real , Integer ) I would like to do some form of type checking such that given a another tuple ( Natural , Natural ) if every coordinate in the tuple is a subclass of the specified domains. For example for some function getcompatibles I'd like to have: getcompatibles( ( Real, Real ) ) = [ t1 ] getcompatibles( ( Real, Integer ) ) = [ t1, t2 ] getcompatibles( ( Natural, Natural ) ) = [ t1, t2 ] getcompatibles( ( Natural, Real ) ) = [ t1 ] The only solution I could come up with would be to run through every for domain (t1, t2) run through each of the types in __subclasses__ and check to see whether it isinstance is True for the given input. Thats extremely inefficient though, is there perhaps a more Pythonic way of doing this?
[ "def compatible_pred(obj_types, fun_signature):\n if len(obj_types) != len(fun_signature): return False\n return all(issubclass(of, ft) for of, ft in zip(obj_types, fun_signature))\n\ndef is_compatible(obj_types, fun_signatures=(t1, t2)):\n return [t for t in fun_signatures if compatible_pred(obj_types, t)]\n\nThe is_compatible name for something that is not a predicate is really, truly confusing: why not give it a sensible name such as getcompatibles, so that the strongly predicate-sounding iscompatible could be used instead for what I've had to name compatible_pred?\n", "Don't check types when you don't have to and count on exception handling - with try / except to catch the instances where the expectation is violated.\nIn Python, which is a \"lazy typed\" (but strongly typed, less I upset the purists) language, calling isinstance repeatedly will certainly cost you in overhead. The question I ask myself when facing such design questions is \"If you didn't want this function to handle pairs of Naturals, why did you call it with them?\" Presumably you are doing some sort of conditional branch predicated on is_compatible, I'd suggest you change that into a conditional call.\nSeeing how you intend to use the result of is_compatible would allow a more focused answer.\n" ]
[ 4, 2 ]
[]
[]
[ "inheritance", "oop", "python" ]
stackoverflow_0002867449_inheritance_oop_python.txt
Q: Why does Python sometimes upgrade a string to unicode and sometimes not? I'm confused. Consider this code working the way I expect: >>> foo = u'Émilie and Juañ are turncoats.' >>> bar = "foo is %s" % foo >>> bar u'foo is \xc3\x89milie and Jua\xc3\xb1 are turncoats.' And this code not at all working the way I expect: >>> try: ... raise Exception(foo) ... except Exception as e: ... foo2 = e ... >>> bar = "foo2 is %s" % foo2 ------------------------------------------------------------ Traceback (most recent call last): File "<ipython console>", line 1, in <module> UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) Can someone explain what's going on here? Why does it matter whether the unicode data is in a plain unicode string or stored in an Exception object? And why does this fix it: >>> bar = u"foo2 is %s" % foo2 >>> bar u'foo2 is \xc3\x89milie and Jua\xc3\xb1 are turncoats.' I am quite confused! Thanks for the help! UPDATE: My coding buddy Randall has added to my confusion in an attempt to help me! Send in the reinforcements to explain how this is supposed to make sense: >>> class A: ... def __str__(self): return "string" ... def __unicode__(self): return "unicode" ... >>> "%s %s" % (u'niño', A()) u'ni\xc3\xb1o unicode' >>> "%s %s" % (A(), u'niño') u'string ni\xc3\xb1o' Note that the order of the arguments here determines which method is called! A: The Python Language Reference has the answer: If format is a Unicode object, or if any of the objects being converted using the %s conversion are Unicode objects, the result will also be a Unicode object. foo = u'Émilie and Juañ are turncoats.' bar = "foo is %s" % foo This works, because foo is a unicode object. This causes the above rule to take effect and results in a Unicode string. bar = "foo2 is %s" % foo2 In this case, foo2 is an Exception object, which is obviously not a unicode object. So the interpreter tries to convert it to a normal str using your default encoding. This, apparently, is ascii, which cannot represent those characters and bails out with an exception. bar = u"foo2 is %s" % foo2 Here it works again, because the format string is a unicode object. So the interpreter tries to convert foo2 to a unicode object as well, which succeeds. As to Randall's question: this surprises me too. However, this is according to the standard (reformatted for readability): %s converts any Python object using str(). If the object or format provided is a unicode string, the resulting string will also be unicode. How such a unicode object is created is left unclear. So both are legal: call __str__, decode back to a Unicode string, and insert it into the output string call __unicode__ and insert the result directly into the output string The mixed behaviour of the Python interpreter is rather hideous indeed. I would consider this to be a bug in the standard. Edit: Quoting the Python 3.0 changelog, emphasis mine: Everything you thought you knew about binary data and Unicode has changed. [...] As a consequence of this change in philosophy, pretty much all code that uses Unicode, encodings or binary data most likely has to change. The change is for the better, as in the 2.x world there were numerous bugs having to do with mixing encoded and unencoded text.
Why does Python sometimes upgrade a string to unicode and sometimes not?
I'm confused. Consider this code working the way I expect: >>> foo = u'Émilie and Juañ are turncoats.' >>> bar = "foo is %s" % foo >>> bar u'foo is \xc3\x89milie and Jua\xc3\xb1 are turncoats.' And this code not at all working the way I expect: >>> try: ... raise Exception(foo) ... except Exception as e: ... foo2 = e ... >>> bar = "foo2 is %s" % foo2 ------------------------------------------------------------ Traceback (most recent call last): File "<ipython console>", line 1, in <module> UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) Can someone explain what's going on here? Why does it matter whether the unicode data is in a plain unicode string or stored in an Exception object? And why does this fix it: >>> bar = u"foo2 is %s" % foo2 >>> bar u'foo2 is \xc3\x89milie and Jua\xc3\xb1 are turncoats.' I am quite confused! Thanks for the help! UPDATE: My coding buddy Randall has added to my confusion in an attempt to help me! Send in the reinforcements to explain how this is supposed to make sense: >>> class A: ... def __str__(self): return "string" ... def __unicode__(self): return "unicode" ... >>> "%s %s" % (u'niño', A()) u'ni\xc3\xb1o unicode' >>> "%s %s" % (A(), u'niño') u'string ni\xc3\xb1o' Note that the order of the arguments here determines which method is called!
[ "The Python Language Reference has the answer:\n\nIf format is a Unicode object, or if any of the objects being converted using the %s conversion are Unicode objects, the result will also be a Unicode object.\n\nfoo = u'Émilie and Juañ are turncoats.'\nbar = \"foo is %s\" % foo\n\nThis works, because foo is a unicode object. This causes the above rule to take effect and results in a Unicode string.\nbar = \"foo2 is %s\" % foo2\n\nIn this case, foo2 is an Exception object, which is obviously not a unicode object. So the interpreter tries to convert it to a normal str using your default encoding. This, apparently, is ascii, which cannot represent those characters and bails out with an exception.\nbar = u\"foo2 is %s\" % foo2\n\nHere it works again, because the format string is a unicode object. So the interpreter tries to convert foo2 to a unicode object as well, which succeeds.\n\nAs to Randall's question: this surprises me too. However, this is according to the standard (reformatted for readability):\n\n%s converts any Python object using str(). If the object or format provided is a unicode string, the resulting string will also be unicode.\n\nHow such a unicode object is created is left unclear. So both are legal:\n\ncall __str__, decode back to a Unicode string, and insert it into the output string\ncall __unicode__ and insert the result directly into the output string\n\nThe mixed behaviour of the Python interpreter is rather hideous indeed. I would consider this to be a bug in the standard.\nEdit: Quoting the Python 3.0 changelog, emphasis mine:\n\nEverything you thought you knew about binary data and Unicode has changed.\n[...]\n\nAs a consequence of this change in philosophy, pretty much all code that uses Unicode, encodings or binary data most likely has to change. The change is for the better, as in the 2.x world there were numerous bugs having to do with mixing encoded and unencoded text.\n\n\n" ]
[ 10 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0002867773_python_unicode.txt
Q: google datastore - does it do lazy loading? if I have a Customer object with a list of orders, declared using the db.ReferenceProperty after a while I may have huge amount of orders in there, if I pull the Customer object would I be in danger of pulling the complete set of orders? A: Yes, db.ReferenceProperty fields are loaded lazily. From the docs: ReferenceProperty automatically references and dereferences model instances as property values: A model instance can be assigned to a ReferenceProperty directly, and its key will be used. The ReferenceProperty value can be used as if it were a model instance, and the datastore entity will be fetched and the model instance created when it is first used in this way. Untouched reference properties do not query for unneeded data. So, for example: # Any reference properties not loaded yet customer = Customer.get_by_id(1) print customer.name print customer.address # Assuming customer.order is a ReferenceProperty, now is when it # would be loaded from the datastore. print customer.order.created_at
google datastore - does it do lazy loading?
if I have a Customer object with a list of orders, declared using the db.ReferenceProperty after a while I may have huge amount of orders in there, if I pull the Customer object would I be in danger of pulling the complete set of orders?
[ "Yes, db.ReferenceProperty fields are loaded lazily. From the docs:\n\nReferenceProperty automatically references and dereferences model instances as property values: A model instance can be assigned to a ReferenceProperty directly, and its key will be used. The ReferenceProperty value can be used as if it were a model instance, and the datastore entity will be fetched and the model instance created when it is first used in this way. Untouched reference properties do not query for unneeded data.\n\nSo, for example:\n# Any reference properties not loaded yet\ncustomer = Customer.get_by_id(1)\nprint customer.name\nprint customer.address\n\n# Assuming customer.order is a ReferenceProperty, now is when it\n# would be loaded from the datastore.\nprint customer.order.created_at\n\n" ]
[ 6 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002867730_google_app_engine_google_cloud_datastore_python.txt
Q: getting keyboard events with pyqt i converted recently from wxpython to pyqt and im still facing alot of problems since im still noob in pyqt so is it possible to detected if user pressed (CTRL+key ) in pyqt ? and how ? i've been trying to find an answer for this for 3 days . if you know website or a good place to learn pyqt, it will be highly appreciated thanx in advance A: Add a QShortcut and listen to its activated() signal, then perform the action in the slot. Or you could reimplement QWidget and define keyPressEvent to what you like. Check for the event parameter's modifiers() and key() to see if they match with what you want. This listens for shortcut keys when the QWidget has focus. A: As for websites to learn, this is the official documentation - it takes some getting used to, but is quite helpful once you get the lay of the land (so to speak). This tutorial is what I walked through to get the initial idea, before discovering the documentation. Good luck! P.S. You might also look at QAction, if you are trying to map your Ctrl+X to an action that may also be performed by a menu or toolbar button... It incorporates a shortcut along with icons and/or text in a very convenient package. Just FYI.
getting keyboard events with pyqt
i converted recently from wxpython to pyqt and im still facing alot of problems since im still noob in pyqt so is it possible to detected if user pressed (CTRL+key ) in pyqt ? and how ? i've been trying to find an answer for this for 3 days . if you know website or a good place to learn pyqt, it will be highly appreciated thanx in advance
[ "Add a QShortcut and listen to its activated() signal, then perform the action in the slot.\nOr you could reimplement QWidget and define keyPressEvent to what you like. Check for the event parameter's modifiers() and key() to see if they match with what you want. This listens for shortcut keys when the QWidget has focus.\n", "As for websites to learn, this is the official documentation - it takes some getting used to, but is quite helpful once you get the lay of the land (so to speak). This tutorial is what I walked through to get the initial idea, before discovering the documentation.\nGood luck!\nP.S. You might also look at QAction, if you are trying to map your Ctrl+X to an action that may also be performed by a menu or toolbar button... It incorporates a shortcut along with icons and/or text in a very convenient package. Just FYI.\n" ]
[ 8, 2 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt", "qt4" ]
stackoverflow_0002761512_pyqt_pyqt4_python_qt_qt4.txt
Q: Python ctypes in_dll string assignment I could use some help assigning to a global C variable in DLL using ctypes. The following is an example of what I'm trying: test.c contains the following #include <stdio.h> char name[60]; void test(void) { printf("Name is %s\n", name); } On windows (cygwin) I build a DLL (Test.dll) as follows: gcc -g -c -Wall test.c gcc -Wall -mrtd -mno-cygwin -shared -W1,--add-stdcall-alias -o Test.dll test.o When trying to modify the name variable and then calling the C test function using the ctypes interface I get the following... >>> from ctypes import * >>> dll = windll.Test >>> dll <WinDLL 'Test', handle ... at ...> >>> f = c_char_p.in_dll(dll, 'name') >>> f c_char_p(None) >>> f.value = 'foo' >>> f c_char_p('foo') >>> dll.test() Name is Name is 4∞┘☺ 13 Why does the test function print garbage in this case? Update: I have confirmed Alex's response. Here is a working example: >>> from ctypes import * >>> dll = windll.Test >>> dll <WinDLL 'Test', handle ... at ...> >>> f = c_char_p.in_dll(dll, 'name') >>> f c_char_p(None) >>> libc = cdll.msvcrt >>> libc <CDLL 'msvcrt', handle ... at ...> #note that pointer is required in the following strcpy >>> libc.strcpy(pointer(f), c_char_p("foo")) >>> dll.test() Name is foo A: name is not really a character pointer (it's an array, which "decays to" a pointer when accessed, but can never be assigned to). You'll need to call the strcpy function from the C runtime library, instead of assigning to f.value.
Python ctypes in_dll string assignment
I could use some help assigning to a global C variable in DLL using ctypes. The following is an example of what I'm trying: test.c contains the following #include <stdio.h> char name[60]; void test(void) { printf("Name is %s\n", name); } On windows (cygwin) I build a DLL (Test.dll) as follows: gcc -g -c -Wall test.c gcc -Wall -mrtd -mno-cygwin -shared -W1,--add-stdcall-alias -o Test.dll test.o When trying to modify the name variable and then calling the C test function using the ctypes interface I get the following... >>> from ctypes import * >>> dll = windll.Test >>> dll <WinDLL 'Test', handle ... at ...> >>> f = c_char_p.in_dll(dll, 'name') >>> f c_char_p(None) >>> f.value = 'foo' >>> f c_char_p('foo') >>> dll.test() Name is Name is 4∞┘☺ 13 Why does the test function print garbage in this case? Update: I have confirmed Alex's response. Here is a working example: >>> from ctypes import * >>> dll = windll.Test >>> dll <WinDLL 'Test', handle ... at ...> >>> f = c_char_p.in_dll(dll, 'name') >>> f c_char_p(None) >>> libc = cdll.msvcrt >>> libc <CDLL 'msvcrt', handle ... at ...> #note that pointer is required in the following strcpy >>> libc.strcpy(pointer(f), c_char_p("foo")) >>> dll.test() Name is foo
[ "name is not really a character pointer (it's an array, which \"decays to\" a pointer when accessed, but can never be assigned to). You'll need to call the strcpy function from the C runtime library, instead of assigning to f.value.\n" ]
[ 6 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0002867916_ctypes_python.txt
Q: Python: how to execute generated code? I have this code, and I would like to use the app parameter to generate the code instead of duplicating it. if app == 'map': try: from modulo.map.views import map return map(request, *args, **kwargs) except ImportError: pass elif app == 'schedule': try: from modulo.schedule.views import schedule return schedule(request, *args, **kwargs) except ImportError: pass elif app == 'sponsors': try: from modulo.sponsors.views import sponsors return sponsors(request, *args, **kwargs) except ImportError: pass elif app == 'streaming': try: from modulo.streaming.views import streaming return streaming(request, *args, **kwargs) except ImportError: pass Do you have any idea ? Thanks A: I would prefer to use the dispatch-dictionary idiom, coding something like...: import sys dispatch = { 'map': ('modulo.map.views', 'map'), 'schedule': ('modulo.schedule.views', 'schedule_day'), ...etc etc.. } if app in dispatch: modname, funname = dispatch[app] try: __import__(modname) except ImportError: pass else: f = getattr(sys.modules[modname], funname, None) if f is not None: return f(request, *args, **kwargs) Not sure what you think "code generation" would buy you to make it preferable to this kind of approach. A: Why not just pass the function into specific function? def proc_app(request, app, *args, **kwargs): return app(request, *args, **kwargs): def view_1(request): from modulo.map.views import map return proc_app(request, map, *args, **kwargs) def view_2(request): from modulo.schedule.views import schedule_day return proc_app(request, schedule_day, *args, **kwargs)
Python: how to execute generated code?
I have this code, and I would like to use the app parameter to generate the code instead of duplicating it. if app == 'map': try: from modulo.map.views import map return map(request, *args, **kwargs) except ImportError: pass elif app == 'schedule': try: from modulo.schedule.views import schedule return schedule(request, *args, **kwargs) except ImportError: pass elif app == 'sponsors': try: from modulo.sponsors.views import sponsors return sponsors(request, *args, **kwargs) except ImportError: pass elif app == 'streaming': try: from modulo.streaming.views import streaming return streaming(request, *args, **kwargs) except ImportError: pass Do you have any idea ? Thanks
[ "I would prefer to use the dispatch-dictionary idiom, coding something like...:\nimport sys\n\ndispatch = { 'map': ('modulo.map.views', 'map'),\n 'schedule': ('modulo.schedule.views', 'schedule_day'),\n ...etc etc.. }\nif app in dispatch:\n modname, funname = dispatch[app]\n try: __import__(modname)\n except ImportError: pass\n else:\n f = getattr(sys.modules[modname], funname, None)\n if f is not None:\n return f(request, *args, **kwargs)\n\nNot sure what you think \"code generation\" would buy you to make it preferable to this kind of approach.\n", "Why not just pass the function into specific function?\ndef proc_app(request, app, *args, **kwargs):\n return app(request, *args, **kwargs):\n\ndef view_1(request):\n from modulo.map.views import map\n return proc_app(request, map, *args, **kwargs)\n\ndef view_2(request):\n from modulo.schedule.views import schedule_day\n return proc_app(request, schedule_day, *args, **kwargs)\n\n" ]
[ 6, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002868063_django_python.txt
Q: Timestamp server rfc3161 response token generation in Python I'm trying to implement tsa server on python using twisted. Currently I'm using openssl binary to generate response, but this seems ugly to me, that's why I'm trying to figure out how to make response token with m2crypto. Thanks in advance for help! Maris. EDITED: how to achieve with m2crypto?: openssl ts -reply -section tsa_config1 -queryfile query.tsq -out response.tsr A: M2Crypto does not yet wrap those pieces of openssl, so you can't use M2Crypto for what you are using the openssl command line client for. A: You may be also interested in PyASN1 project, however, I should admit there's no adequate library to implement RFC3161 functionality in Python today. I would look towards Perl instead.
Timestamp server rfc3161 response token generation in Python
I'm trying to implement tsa server on python using twisted. Currently I'm using openssl binary to generate response, but this seems ugly to me, that's why I'm trying to figure out how to make response token with m2crypto. Thanks in advance for help! Maris. EDITED: how to achieve with m2crypto?: openssl ts -reply -section tsa_config1 -queryfile query.tsq -out response.tsr
[ "M2Crypto does not yet wrap those pieces of openssl, so you can't use M2Crypto for what you are using the openssl command line client for.\n", "You may be also interested in PyASN1 project, however, I should admit there's no adequate library to implement RFC3161 functionality in Python today. I would look towards Perl instead.\n" ]
[ 1, 0 ]
[]
[]
[ "m2crypto", "python", "rfc3161", "timestamping", "trusted_timestamp" ]
stackoverflow_0002858282_m2crypto_python_rfc3161_timestamping_trusted_timestamp.txt
Q: how to convert a python slicing operation into java code I have this code line: x and k are int. lm is an array lz=[f(x,lm[:j]+lm[j+1:],k) for j in range(n)] My question is: I want to convert the above line into Java... I have created an lm array in Java, but I am thinking of making it an arraylist to avoid the problem of the array length. I know that for instanse lm is [1, 4, 1, 9]. Then the output list will be: [4, 1, 9],[1, 1, 9],[1, 4, 9],[1 ,4,1] But I am a little bit confused about the way to implement it in Java ... Any help is appreciated.. Thanks A: Will that help you? int[] lm = new int[] {1, 4, 1, 9}; for (int i = 0; i < lm.length; i++) { int[] tmp = new int[lm.length - 1]; System.arraycopy(lm, 0, tmp, 0, i); System.arraycopy(lm, i + 1, tmp, i, lm.length - i - 1); System.out.println("tmp = " + Arrays.toString(tmp)); } This of course doesn't use f() as I have no way of knowing what it actually does.
how to convert a python slicing operation into java code
I have this code line: x and k are int. lm is an array lz=[f(x,lm[:j]+lm[j+1:],k) for j in range(n)] My question is: I want to convert the above line into Java... I have created an lm array in Java, but I am thinking of making it an arraylist to avoid the problem of the array length. I know that for instanse lm is [1, 4, 1, 9]. Then the output list will be: [4, 1, 9],[1, 1, 9],[1, 4, 9],[1 ,4,1] But I am a little bit confused about the way to implement it in Java ... Any help is appreciated.. Thanks
[ "Will that help you?\n int[] lm = new int[] {1, 4, 1, 9};\n for (int i = 0; i < lm.length; i++) {\n int[] tmp = new int[lm.length - 1];\n System.arraycopy(lm, 0, tmp, 0, i);\n System.arraycopy(lm, i + 1, tmp, i, lm.length - i - 1);\n\n System.out.println(\"tmp = \" + Arrays.toString(tmp));\n }\n\nThis of course doesn't use f() as I have no way of knowing what it actually does.\n" ]
[ 0 ]
[]
[]
[ "arrays", "java", "python", "slice" ]
stackoverflow_0002868277_arrays_java_python_slice.txt
Q: Reading from CSVs in Python repeatedly? I'm trying to check the value of extracted data against a csv I already have. It will only loop through the rows of the CSV once, I can only check one value of feed.items(). Is there a value I need to reset somewhere? Is there a better/more efficient way to do this? Thanks. orig = csv.reader(open("googlel.csv", "rb"), delimiter = ';') goodrows = [] for feed in gotfeeds: for link,comments in feed.items(): for row in orig: print link if link in row[1]: row.append(comments) goodrows.append(row) A: You can "reset" the CSV iterator by resetting the read position of the file object. data = open("googlel.csv", "rb") orig = csv.reader(data, delimiter = ';') goodrows = [] for feed in gotfeeds: for link,comments in feed.items(): data.seek(0) for row in orig: print link if link in row[1]: row.append(comments) goodrows.append(row) A: Making orig a list avoids the need to reset/reparse the csv: orig = list(csv.reader(open("googlel.csv", "rb"), delimiter = ';'))
Reading from CSVs in Python repeatedly?
I'm trying to check the value of extracted data against a csv I already have. It will only loop through the rows of the CSV once, I can only check one value of feed.items(). Is there a value I need to reset somewhere? Is there a better/more efficient way to do this? Thanks. orig = csv.reader(open("googlel.csv", "rb"), delimiter = ';') goodrows = [] for feed in gotfeeds: for link,comments in feed.items(): for row in orig: print link if link in row[1]: row.append(comments) goodrows.append(row)
[ "You can \"reset\" the CSV iterator by resetting the read position of the file object.\ndata = open(\"googlel.csv\", \"rb\")\norig = csv.reader(data, delimiter = ';')\ngoodrows = []\nfor feed in gotfeeds: \n for link,comments in feed.items():\n data.seek(0)\n for row in orig:\n print link\n if link in row[1]:\n row.append(comments)\n goodrows.append(row)\n\n", "Making orig a list avoids the need to reset/reparse the csv:\norig = list(csv.reader(open(\"googlel.csv\", \"rb\"), delimiter = ';'))\n\n" ]
[ 41, 14 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0002868354_csv_python.txt
Q: How to import classes into other classes within the same file in Python I have the file below and it is part of a django project called projectmanager, this file is projectmanager/projects/models.py . Whenever I use the python interpreter to import a Project just to test the functionality i get a name error for line 8 that FileRepo() cannot be found. How Can I import these classes correctly? Ideally what I am looking for is each Project to contain multiple FileRepos which each contain and unknown number of files. Thanks for any assistance in advance. #imports from django.db import models from django.contrib import admin #Project is responsible for ensuring that each project contains all of the folders and file storage #mechanisms a project needs, as well as a unique CCL# class Project(models.Model): ccl = models.CharField(max_length=30) Techpacks = FileRepo() COAS = FileRepo() Shippingdocs = FileRepo() POchemspecs = FileRepo() Internalpos = FileRepo() Finalreports = FileRepo() Batchrecords = FileRepo() RFPS = FileRepo() Businessdev = FileRepo() QA = FileRepo() Updates = FileRepo() def __unicode__(self): return self.ccl #ProjectFile is the file object used by each FileRepo component class ProjectFile(models.Model): file = models.FileField(uploadto='ProjectFiles') def __unicode__(self): return self.file #FileRepo is the model for the "folders" to be used in a Project class FileRepo(models.Model): typeOf = models.CharField(max_length=30) files = models.ManyToManyField(ProjectFile) def __unicode__(self): return self.typeOf A: Although McPeterson is right in general that for a name to be found, it has to be defined above where it is used, in your case that won't help. In Django, you can't arbitrarily assign classes to be properties of other classes. You need to define proper relationships between them. I suggest you read the documentation on relationship fields. A: Have you declared FileRepo before you call it? IE, moving class FileRepo ahead of class Project in the models.py file?
How to import classes into other classes within the same file in Python
I have the file below and it is part of a django project called projectmanager, this file is projectmanager/projects/models.py . Whenever I use the python interpreter to import a Project just to test the functionality i get a name error for line 8 that FileRepo() cannot be found. How Can I import these classes correctly? Ideally what I am looking for is each Project to contain multiple FileRepos which each contain and unknown number of files. Thanks for any assistance in advance. #imports from django.db import models from django.contrib import admin #Project is responsible for ensuring that each project contains all of the folders and file storage #mechanisms a project needs, as well as a unique CCL# class Project(models.Model): ccl = models.CharField(max_length=30) Techpacks = FileRepo() COAS = FileRepo() Shippingdocs = FileRepo() POchemspecs = FileRepo() Internalpos = FileRepo() Finalreports = FileRepo() Batchrecords = FileRepo() RFPS = FileRepo() Businessdev = FileRepo() QA = FileRepo() Updates = FileRepo() def __unicode__(self): return self.ccl #ProjectFile is the file object used by each FileRepo component class ProjectFile(models.Model): file = models.FileField(uploadto='ProjectFiles') def __unicode__(self): return self.file #FileRepo is the model for the "folders" to be used in a Project class FileRepo(models.Model): typeOf = models.CharField(max_length=30) files = models.ManyToManyField(ProjectFile) def __unicode__(self): return self.typeOf
[ "Although McPeterson is right in general that for a name to be found, it has to be defined above where it is used, in your case that won't help. In Django, you can't arbitrarily assign classes to be properties of other classes. You need to define proper relationships between them. I suggest you read the documentation on relationship fields.\n", "Have you declared FileRepo before you call it? IE, moving class FileRepo ahead of class Project in the models.py file?\n" ]
[ 3, 0 ]
[]
[]
[ "django", "import", "python" ]
stackoverflow_0002868418_django_import_python.txt
Q: Problem with python urllib I'm getting an error when ever I try to pull down a web page with urllib.urlopen. I've disabled windows firewall and my AV so its not that. I can access the pages in my browser. I even reinstalled python to rule out it being a broken urllib. Any help would be greatly appreciated. >>> import urllib >>> h = urllib.urlopen("http://www.google.com").read() Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> h = urllib.urlopen("http://www.google.com").read() File "C:\Python26\lib\urllib.py", line 86, in urlopen return opener.open(url) File "C:\Python26\lib\urllib.py", line 205, in open return getattr(self, name)(url) File "C:\Python26\lib\urllib.py", line 344, in open_http h.endheaders() File "C:\Python26\lib\httplib.py", line 904, in endheaders self._send_output() File "C:\Python26\lib\httplib.py", line 776, in _send_output self.send(msg) File "C:\Python26\lib\httplib.py", line 735, in send self.connect() File "C:\Python26\lib\httplib.py", line 716, in connect self.timeout) File "C:\Python26\lib\socket.py", line 514, in create_connection raise error, msg IOError: [Errno socket error] [Errno 10061] No connection could be made because the target machine actively refused it >>> A: this could be the case: Just found the problem I had set a proxy through internet options, that proxy went offline, and so did my python shell. A: urllib is working just fine. Try using ethereal (or some similar network sniffer) on your box to determine if the denial coming from your machine or a machine beyond.
Problem with python urllib
I'm getting an error when ever I try to pull down a web page with urllib.urlopen. I've disabled windows firewall and my AV so its not that. I can access the pages in my browser. I even reinstalled python to rule out it being a broken urllib. Any help would be greatly appreciated. >>> import urllib >>> h = urllib.urlopen("http://www.google.com").read() Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> h = urllib.urlopen("http://www.google.com").read() File "C:\Python26\lib\urllib.py", line 86, in urlopen return opener.open(url) File "C:\Python26\lib\urllib.py", line 205, in open return getattr(self, name)(url) File "C:\Python26\lib\urllib.py", line 344, in open_http h.endheaders() File "C:\Python26\lib\httplib.py", line 904, in endheaders self._send_output() File "C:\Python26\lib\httplib.py", line 776, in _send_output self.send(msg) File "C:\Python26\lib\httplib.py", line 735, in send self.connect() File "C:\Python26\lib\httplib.py", line 716, in connect self.timeout) File "C:\Python26\lib\socket.py", line 514, in create_connection raise error, msg IOError: [Errno socket error] [Errno 10061] No connection could be made because the target machine actively refused it >>>
[ "this could be the case:\n\nJust found the problem I had set a\n proxy through internet options, that\n proxy went offline, and so did my\n python shell.\n\n", "urllib is working just fine.\nTry using ethereal (or some similar network sniffer) on your box to determine if the denial coming from your machine or a machine beyond.\n" ]
[ 5, 0 ]
[]
[]
[ "python", "urllib" ]
stackoverflow_0002868935_python_urllib.txt
Q: Python - Removing duplicates from a string def remove_duplicates(strng): """ Returns a string which is the same as the argument except only the first occurrence of each letter is present. Upper and lower case letters are treated as different. Only duplicate letters are removed, other characters such as spaces or numbers are not changed. >>> remove_duplicates('apple') 'aple' >>> remove_duplicates('Mississippi') 'Misp' >>> remove_duplicates('The quick brown fox jumps over the lazy dog') 'The quick brown fx jmps v t lazy dg' >>> remove_duplicates('121 balloons 2 u') '121 balons 2 u' """ s = strng.split() return strng.replace(s[0],"") Writing a function to get rid of duplicate letters but so far have been playing around for an hour and can't get anything. Help would be appreciated, thanks. A: Not the most efficient, but the most straightforward way is: >>> s = 'The quick brown fox jumps over the lazy dog' >>> import string >>> n = '' >>> for i in s: if i not in string.ascii_letters: n += i elif i not in n: n += i >>> n 'The quick brown fx jmps v t lazy dg' A: Using a list comprehension : >>> from string import whitespace, digits >>> s = 'The quick brown fox jumps over the lazy dog' >>> ''.join([c for i, c in enumerate(s) if c in whitespace+digits \ or not c in s[:i]]) A: try this ... def remove_duplicates(s): result = "" dic = {} for i in s: if i not in dic: result+=i if ord(i.lower()) >= ord('a') and ord(i.lower()) <= ord('z'): dic[i] = 1 return result
Python - Removing duplicates from a string
def remove_duplicates(strng): """ Returns a string which is the same as the argument except only the first occurrence of each letter is present. Upper and lower case letters are treated as different. Only duplicate letters are removed, other characters such as spaces or numbers are not changed. >>> remove_duplicates('apple') 'aple' >>> remove_duplicates('Mississippi') 'Misp' >>> remove_duplicates('The quick brown fox jumps over the lazy dog') 'The quick brown fx jmps v t lazy dg' >>> remove_duplicates('121 balloons 2 u') '121 balons 2 u' """ s = strng.split() return strng.replace(s[0],"") Writing a function to get rid of duplicate letters but so far have been playing around for an hour and can't get anything. Help would be appreciated, thanks.
[ "Not the most efficient, but the most straightforward way is:\n>>> s = 'The quick brown fox jumps over the lazy dog'\n>>> import string\n>>> n = ''\n>>> for i in s:\n if i not in string.ascii_letters:\n n += i\n elif i not in n:\n n += i\n\n\n>>> n\n'The quick brown fx jmps v t lazy dg'\n\n", "Using a list comprehension :\n>>> from string import whitespace, digits\n>>> s = 'The quick brown fox jumps over the lazy dog'\n>>> ''.join([c for i, c in enumerate(s) if c in whitespace+digits \\\n or not c in s[:i]])\n\n", "try this ...\ndef remove_duplicates(s):\n result = \"\"\n dic = {}\n for i in s:\n if i not in dic:\n result+=i\n if ord(i.lower()) >= ord('a') and ord(i.lower()) <= ord('z'):\n dic[i] = 1\n return result\n\n" ]
[ 3, 2, 0 ]
[]
[]
[ "duplicate_removal", "python" ]
stackoverflow_0002865150_duplicate_removal_python.txt
Q: How to make this gaema demo running on google-app-engine? This is the package which has a webapp demo in it. However, when I login use this demo, I get an error. How to make this demo running on the gae-launcher? A: Looks like a bug in gaema. The line that's failing is trying to urlencode a dictionary of arguments that get passed to the OpenID endpoint. One or more of the values, perhaps your first or last name, has non-ASCII characters. You might be able to work around it by replacing instances of this: urllib.urlencode(args) With this: urllib.urlencode(dict([(k, args[k].encode('utf-8')) for k in args])) For a more permanent fix, I would report the issue here: http://code.google.com/p/gaema/issues/list
How to make this gaema demo running on google-app-engine?
This is the package which has a webapp demo in it. However, when I login use this demo, I get an error. How to make this demo running on the gae-launcher?
[ "Looks like a bug in gaema.\nThe line that's failing is trying to urlencode a dictionary of arguments that get passed to the OpenID endpoint. One or more of the values, perhaps your first or last name, has non-ASCII characters.\nYou might be able to work around it by replacing instances of this:\nurllib.urlencode(args)\n\nWith this:\nurllib.urlencode(dict([(k, args[k].encode('utf-8')) for k in args]))\n\nFor a more permanent fix, I would report the issue here:\nhttp://code.google.com/p/gaema/issues/list\n" ]
[ 0 ]
[]
[]
[ "gaema", "google_app_engine", "python" ]
stackoverflow_0002863839_gaema_google_app_engine_python.txt
Q: Setting opacity on a PyGTK label Is there a way to make a PyGTK widget partly transparent, so that the widgets behind it can be seen through it? Specifically I'm trying to do this on a label, for typographic effect; I don't want to change the color instead, as it may not look right on all themes. A: No, not possible. It is possible to make entire windows partially transparent, if window manager supports compositing, but not individual widgets. I guess what you want can be achieved differently by "blending" colors: def blend (color1, color2, weight = 0.5): return gtk.gdk.Color ( color1.red_float * weight + color2.red_float * (1 - weight), color1.green_float * weight + color2.green_float * (1 - weight), color1.blue_float * weight + color2.blue_float * (1 - weight)) for state in gtk.StateType.__enum_values__: label.modify_fg (state, blend (label.style.fg[state], label.style.bg[state])) To make it completely correct you can also listen to "style-set" signal.
Setting opacity on a PyGTK label
Is there a way to make a PyGTK widget partly transparent, so that the widgets behind it can be seen through it? Specifically I'm trying to do this on a label, for typographic effect; I don't want to change the color instead, as it may not look right on all themes.
[ "No, not possible. It is possible to make entire windows partially transparent, if window manager supports compositing, but not individual widgets.\nI guess what you want can be achieved differently by \"blending\" colors:\ndef blend (color1, color2, weight = 0.5):\n return gtk.gdk.Color (\n color1.red_float * weight + color2.red_float * (1 - weight),\n color1.green_float * weight + color2.green_float * (1 - weight),\n color1.blue_float * weight + color2.blue_float * (1 - weight))\n\nfor state in gtk.StateType.__enum_values__:\n label.modify_fg (state, blend (label.style.fg[state], label.style.bg[state]))\n\nTo make it completely correct you can also listen to \"style-set\" signal.\n" ]
[ 2 ]
[]
[]
[ "gtk", "opacity", "pygtk", "python", "transparency" ]
stackoverflow_0002869169_gtk_opacity_pygtk_python_transparency.txt
Q: In Python, how to I create a datetime with X hours? How do I create the datetime that is 24 hours before NOW()? 48 before NOW()? X hours or days before now?? A: from datetime import datetime, timedelta def hours_ago(hours): return datetime.today() - timedelta(hours=hours) def days_ago(days): return datetime.today() - timedelta(days=days) A: >>> from datetime import datetime, timedelta >>> datetime.now() - timedelta(hours=24) datetime.datetime(2010, 5, 18, 14, 5, 56, 128000)
In Python, how to I create a datetime with X hours?
How do I create the datetime that is 24 hours before NOW()? 48 before NOW()? X hours or days before now??
[ "from datetime import datetime, timedelta\n\ndef hours_ago(hours):\n return datetime.today() - timedelta(hours=hours)\n\ndef days_ago(days):\n return datetime.today() - timedelta(days=days)\n\n", ">>> from datetime import datetime, timedelta\n>>> datetime.now() - timedelta(hours=24)\ndatetime.datetime(2010, 5, 18, 14, 5, 56, 128000)\n\n" ]
[ 9, 3 ]
[]
[]
[ "datetime", "python", "time" ]
stackoverflow_0002869407_datetime_python_time.txt
Q: how to encode a url with urllib or urllib2 I want a url like example.com/page.html to somthing like example.com/a$xDzf9D84qGBOeXkXNstw%3D%3D106 A: In case you mean this: >>> import urllib, base64 >>> urllib.quote_plus('example.com/page.html') 'example.com%2Fpage.html' >>> base64.urlsafe_b64encode('example.com/page.html') 'ZXhhbXBsZS5jb20vcGFnZS5odG1s' A: you probably wanted something like this: >>> url = 'stackoverflow.com/questions/2841879/how-to-encode-a-url-with-urllib-or-urllib2' >>> host, path = url.split('/', 1) >>> path_mangled = ''.join(['%%%02x' % ord(x) if x not in '/?&' else x for x in path]) >>> url_mangled = '/'.join([host, path_mangled]) >>> url_mangled 'stackoverflow.com/%71%75%65%73%74%69%6f%6e%73/%32%38%34%31%38%37%39/%68%6f%77%2d%74%6f%2d%65%6e%63%6f%64%65%2d%61%2d%75%72%6c%2d%77%69%74%68%2d%75%72%6c%6c%69%62%2d%6f%72%2d%75%72%6c%6c%69%62%32' (note that for full urls with scheme (http://...), you you have to change the second line)
how to encode a url with urllib or urllib2
I want a url like example.com/page.html to somthing like example.com/a$xDzf9D84qGBOeXkXNstw%3D%3D106
[ "In case you mean this:\n >>> import urllib, base64\n >>> urllib.quote_plus('example.com/page.html')\n 'example.com%2Fpage.html'\n >>> base64.urlsafe_b64encode('example.com/page.html')\n 'ZXhhbXBsZS5jb20vcGFnZS5odG1s'\n\n", "you probably wanted something like this:\n>>> url = 'stackoverflow.com/questions/2841879/how-to-encode-a-url-with-urllib-or-urllib2'\n>>> host, path = url.split('/', 1)\n>>> path_mangled = ''.join(['%%%02x' % ord(x) if x not in '/?&' else x for x in path])\n>>> url_mangled = '/'.join([host, path_mangled])\n>>> url_mangled\n'stackoverflow.com/%71%75%65%73%74%69%6f%6e%73/%32%38%34%31%38%37%39/%68%6f%77%2d%74%6f%2d%65%6e%63%6f%64%65%2d%61%2d%75%72%6c%2d%77%69%74%68%2d%75%72%6c%6c%69%62%2d%6f%72%2d%75%72%6c%6c%69%62%32'\n\n(note that for full urls with scheme (http://...), you you have to change the second line)\n" ]
[ 3, 2 ]
[]
[]
[ "python", "urllib", "urllib2" ]
stackoverflow_0002841879_python_urllib_urllib2.txt
Q: Multiple data series in real time plot I'm kind of new to Python and trying to create a plotting app for values read via RS232 from a sensor. I've managed (after some reading and copying examples online) to get a plot working that updates on a timer which is great. My only trouble is that I can't manage to get multiple data series into the same plot. Does anyone have a solution to this? This is the code that I've worked out this far: import os import pprint import random import sys import wx # The recommended way to use wx with mpl is with the WXAgg backend import matplotlib matplotlib.use('WXAgg') from matplotlib.figure import Figure from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigCanvas, NavigationToolbar2WxAgg as NavigationToolbar import numpy as np import pylab DATA_LENGTH = 100 REDRAW_TIMER_MS = 20 def getData(): return int(random.uniform(1000, 1020)) class GraphFrame(wx.Frame): # the main frame of the application def __init__(self): wx.Frame.__init__(self, None, -1, "Usart plotter", size=(800,600)) self.Centre() self.data = [] self.paused = False self.create_menu() self.create_status_bar() self.create_main_panel() self.redraw_timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.on_redraw_timer, self.redraw_timer) self.redraw_timer.Start(REDRAW_TIMER_MS) def create_menu(self): self.menubar = wx.MenuBar() menu_file = wx.Menu() m_expt = menu_file.Append(-1, "&Save plot\tCtrl-S", "Save plot to file") self.Bind(wx.EVT_MENU, self.on_save_plot, m_expt) menu_file.AppendSeparator() m_exit = menu_file.Append(-1, "E&xit\tCtrl-X", "Exit") self.Bind(wx.EVT_MENU, self.on_exit, m_exit) self.menubar.Append(menu_file, "&File") self.SetMenuBar(self.menubar) def create_main_panel(self): self.panel = wx.Panel(self) self.init_plot() self.canvas = FigCanvas(self.panel, -1, self.fig) # pause button self.pause_button = wx.Button(self.panel, -1, "Pause") self.Bind(wx.EVT_BUTTON, self.on_pause_button, self.pause_button) self.Bind(wx.EVT_UPDATE_UI, self.on_update_pause_button, self.pause_button) self.hbox1 = wx.BoxSizer(wx.HORIZONTAL) self.hbox1.Add(self.pause_button, border=5, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL) self.vbox = wx.BoxSizer(wx.VERTICAL) self.vbox.Add(self.canvas, 1, flag=wx.LEFT | wx.TOP | wx.GROW) self.vbox.Add(self.hbox1, 0, flag=wx.ALIGN_LEFT | wx.TOP) self.panel.SetSizer(self.vbox) #self.vbox.Fit(self) def create_status_bar(self): self.statusbar = self.CreateStatusBar() def init_plot(self): self.dpi = 100 self.fig = Figure((3.0, 3.0), dpi=self.dpi) self.axes = self.fig.add_subplot(111) self.axes.set_axis_bgcolor('white') self.axes.set_title('Usart data', size=12) pylab.setp(self.axes.get_xticklabels(), fontsize=8) pylab.setp(self.axes.get_yticklabels(), fontsize=8) # plot the data as a line series, and save the reference # to the plotted line series # self.plot_data = self.axes.plot( self.data, linewidth=1, color="blue", )[0] def draw_plot(self): # redraws the plot xmax = len(self.data) if len(self.data) > DATA_LENGTH else DATA_LENGTH xmin = xmax - DATA_LENGTH ymin = 0 ymax = 4096 self.axes.set_xbound(lower=xmin, upper=xmax) self.axes.set_ybound(lower=ymin, upper=ymax) # enable grid #self.axes.grid(True, color='gray') # Using setp here is convenient, because get_xticklabels # returns a list over which one needs to explicitly # iterate, and setp already handles this. # pylab.setp(self.axes.get_xticklabels(), visible=True) self.plot_data.set_xdata(np.arange(len(self.data))) self.plot_data.set_ydata(np.array(self.data)) self.canvas.draw() def on_pause_button(self, event): self.paused = not self.paused def on_update_pause_button(self, event): label = "Resume" if self.paused else "Pause" self.pause_button.SetLabel(label) def on_save_plot(self, event): file_choices = "PNG (*.png)|*.png" dlg = wx.FileDialog( self, message="Save plot as...", defaultDir=os.getcwd(), defaultFile="plot.png", wildcard=file_choices, style=wx.SAVE) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() self.canvas.print_figure(path, dpi=self.dpi) self.flash_status_message("Saved to %s" % path) def on_redraw_timer(self, event): if not self.paused: newData = getData() self.data.append(newData) self.draw_plot() def on_exit(self, event): self.Destroy() def flash_status_message(self, msg, flash_len_ms=1500): self.statusbar.SetStatusText(msg) self.timeroff = wx.Timer(self) self.Bind( wx.EVT_TIMER, self.on_flash_status_off, self.timeroff) self.timeroff.Start(flash_len_ms, oneShot=True) def on_flash_status_off(self, event): self.statusbar.SetStatusText('') if __name__ == '__main__': app = wx.PySimpleApp() app.frame = GraphFrame() app.frame.Show() app.MainLoop() A: Solved it by realizing that Plot() returned a list of lines. A: Here's a matplotlib example. It was originally written to use a module that would get analog data from an arduino running firmata, but you should be able to get the relevant bits from it: http://github.com/jsnyder/jbsnyder_tools/blob/master/plotanalog.py I believe it may depend on a ring buffer implementation that's in that repo as well: http://github.com/jsnyder/jbsnyder_tools
Multiple data series in real time plot
I'm kind of new to Python and trying to create a plotting app for values read via RS232 from a sensor. I've managed (after some reading and copying examples online) to get a plot working that updates on a timer which is great. My only trouble is that I can't manage to get multiple data series into the same plot. Does anyone have a solution to this? This is the code that I've worked out this far: import os import pprint import random import sys import wx # The recommended way to use wx with mpl is with the WXAgg backend import matplotlib matplotlib.use('WXAgg') from matplotlib.figure import Figure from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigCanvas, NavigationToolbar2WxAgg as NavigationToolbar import numpy as np import pylab DATA_LENGTH = 100 REDRAW_TIMER_MS = 20 def getData(): return int(random.uniform(1000, 1020)) class GraphFrame(wx.Frame): # the main frame of the application def __init__(self): wx.Frame.__init__(self, None, -1, "Usart plotter", size=(800,600)) self.Centre() self.data = [] self.paused = False self.create_menu() self.create_status_bar() self.create_main_panel() self.redraw_timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.on_redraw_timer, self.redraw_timer) self.redraw_timer.Start(REDRAW_TIMER_MS) def create_menu(self): self.menubar = wx.MenuBar() menu_file = wx.Menu() m_expt = menu_file.Append(-1, "&Save plot\tCtrl-S", "Save plot to file") self.Bind(wx.EVT_MENU, self.on_save_plot, m_expt) menu_file.AppendSeparator() m_exit = menu_file.Append(-1, "E&xit\tCtrl-X", "Exit") self.Bind(wx.EVT_MENU, self.on_exit, m_exit) self.menubar.Append(menu_file, "&File") self.SetMenuBar(self.menubar) def create_main_panel(self): self.panel = wx.Panel(self) self.init_plot() self.canvas = FigCanvas(self.panel, -1, self.fig) # pause button self.pause_button = wx.Button(self.panel, -1, "Pause") self.Bind(wx.EVT_BUTTON, self.on_pause_button, self.pause_button) self.Bind(wx.EVT_UPDATE_UI, self.on_update_pause_button, self.pause_button) self.hbox1 = wx.BoxSizer(wx.HORIZONTAL) self.hbox1.Add(self.pause_button, border=5, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL) self.vbox = wx.BoxSizer(wx.VERTICAL) self.vbox.Add(self.canvas, 1, flag=wx.LEFT | wx.TOP | wx.GROW) self.vbox.Add(self.hbox1, 0, flag=wx.ALIGN_LEFT | wx.TOP) self.panel.SetSizer(self.vbox) #self.vbox.Fit(self) def create_status_bar(self): self.statusbar = self.CreateStatusBar() def init_plot(self): self.dpi = 100 self.fig = Figure((3.0, 3.0), dpi=self.dpi) self.axes = self.fig.add_subplot(111) self.axes.set_axis_bgcolor('white') self.axes.set_title('Usart data', size=12) pylab.setp(self.axes.get_xticklabels(), fontsize=8) pylab.setp(self.axes.get_yticklabels(), fontsize=8) # plot the data as a line series, and save the reference # to the plotted line series # self.plot_data = self.axes.plot( self.data, linewidth=1, color="blue", )[0] def draw_plot(self): # redraws the plot xmax = len(self.data) if len(self.data) > DATA_LENGTH else DATA_LENGTH xmin = xmax - DATA_LENGTH ymin = 0 ymax = 4096 self.axes.set_xbound(lower=xmin, upper=xmax) self.axes.set_ybound(lower=ymin, upper=ymax) # enable grid #self.axes.grid(True, color='gray') # Using setp here is convenient, because get_xticklabels # returns a list over which one needs to explicitly # iterate, and setp already handles this. # pylab.setp(self.axes.get_xticklabels(), visible=True) self.plot_data.set_xdata(np.arange(len(self.data))) self.plot_data.set_ydata(np.array(self.data)) self.canvas.draw() def on_pause_button(self, event): self.paused = not self.paused def on_update_pause_button(self, event): label = "Resume" if self.paused else "Pause" self.pause_button.SetLabel(label) def on_save_plot(self, event): file_choices = "PNG (*.png)|*.png" dlg = wx.FileDialog( self, message="Save plot as...", defaultDir=os.getcwd(), defaultFile="plot.png", wildcard=file_choices, style=wx.SAVE) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() self.canvas.print_figure(path, dpi=self.dpi) self.flash_status_message("Saved to %s" % path) def on_redraw_timer(self, event): if not self.paused: newData = getData() self.data.append(newData) self.draw_plot() def on_exit(self, event): self.Destroy() def flash_status_message(self, msg, flash_len_ms=1500): self.statusbar.SetStatusText(msg) self.timeroff = wx.Timer(self) self.Bind( wx.EVT_TIMER, self.on_flash_status_off, self.timeroff) self.timeroff.Start(flash_len_ms, oneShot=True) def on_flash_status_off(self, event): self.statusbar.SetStatusText('') if __name__ == '__main__': app = wx.PySimpleApp() app.frame = GraphFrame() app.frame.Show() app.MainLoop()
[ "Solved it by realizing that Plot() returned a list of lines.\n", "Here's a matplotlib example. It was originally written to use a module that would get analog data from an arduino running firmata, but you should be able to get the relevant bits from it: http://github.com/jsnyder/jbsnyder_tools/blob/master/plotanalog.py\nI believe it may depend on a ring buffer implementation that's in that repo as well: http://github.com/jsnyder/jbsnyder_tools\n" ]
[ 1, 1 ]
[]
[]
[ "matplotlib", "python", "sensors" ]
stackoverflow_0002814464_matplotlib_python_sensors.txt
Q: How do I name a variable with acronym? For example in Java for Data Transfer Object I use as: ExampleDTO exampleDTO = new ExampleDTO(); So, if I am following PEP 8 (lower_case_with_underscores), what naming convention should I use for similar in Python? A: The style most agreeing with PEP-8 would probably be... example_dto = ExampleDTO() A: You may want to look at Python Style Guide I personally use camelCase for variables and _ (underscore) separated in method names.
How do I name a variable with acronym?
For example in Java for Data Transfer Object I use as: ExampleDTO exampleDTO = new ExampleDTO(); So, if I am following PEP 8 (lower_case_with_underscores), what naming convention should I use for similar in Python?
[ "The style most agreeing with PEP-8 would probably be...\nexample_dto = ExampleDTO()\n", "You may want to look at Python Style Guide\nI personally use camelCase for variables and _ (underscore) separated in method names. \n" ]
[ 10, 0 ]
[ "Why use acronyms in the first place? I try to avoid them when possible. They obfuscate the code and tend to create code that is hard to browse for quick read. Worst case they bring bugs because of misinterpretation (RndCmp was a Random Compare not a Rounded Complex).\nWhat is DTO? Will it still be used in 2 years? Will every new guy immediately know what it means? In 5 years from now too? Can it be confused with anything else? (Deterministic and Transferable Object?)\nThe only true (and honest) reason for using acronyms is pure coder laziness. My fun in meetings is to ask about acronyms in variable names and 80% of the times nobody really knows. Even the old guys forget what it meant a couple of years back. We even have some with more than one meanings.\nWith today great IDE (??) with auto-complete of variable names, laziness is a very bad reason to keep them around. By experience you cannot prevent them, but they should always be questioned.\n" ]
[ -2 ]
[ "naming_conventions", "python" ]
stackoverflow_0002869251_naming_conventions_python.txt
Q: feedparser fails during script run, but can't reproduce in interactive python console It's failing with this when I run eclipse or when I run my script in iPython: 'ascii' codec can't decode byte 0xe2 in position 32: ordinal not in range(128) I don't know why, but when I simply execute the feedparse.parse(url) statement using the same url, there is no error thrown. This is stumping me big time. The code is as simple as: try: d = feedparser.parse(url) except Exception, e: logging.error('Error while retrieving feed.') logging.error(e) logging.error(formatExceptionInfo(None)) logging.error(formatExceptionInfo1()) Here is the stack trace: d = feedparser.parse(url) File "C:\Python26\lib\site-packages\feedparser.py", line 2623, in parse feedparser.feed(data) File "C:\Python26\lib\site-packages\feedparser.py", line 1441, in feed sgmllib.SGMLParser.feed(self, data) File "C:\Python26\lib\sgmllib.py", line 104, in feed self.goahead(0) File "C:\Python26\lib\sgmllib.py", line 143, in goahead k = self.parse_endtag(i) File "C:\Python26\lib\sgmllib.py", line 320, in parse_endtag self.finish_endtag(tag) File "C:\Python26\lib\sgmllib.py", line 360, in finish_endtag self.unknown_endtag(tag) File "C:\Python26\lib\site-packages\feedparser.py", line 476, in unknown_endtag method() File "C:\Python26\lib\site-packages\feedparser.py", line 1318, in _end_content value = self.popContent('content') File "C:\Python26\lib\site-packages\feedparser.py", line 700, in popContent value = self.pop(tag) File "C:\Python26\lib\site-packages\feedparser.py", line 641, in pop output = _resolveRelativeURIs(output, self.baseuri, self.encoding) File "C:\Python26\lib\site-packages\feedparser.py", line 1594, in _resolveRelativeURIs p.feed(htmlSource) File "C:\Python26\lib\site-packages\feedparser.py", line 1441, in feed sgmllib.SGMLParser.feed(self, data) File "C:\Python26\lib\sgmllib.py", line 104, in feed self.goahead(0) File "C:\Python26\lib\sgmllib.py", line 138, in goahead k = self.parse_starttag(i) File "C:\Python26\lib\sgmllib.py", line 296, in parse_starttag self.finish_starttag(tag, attrs) File "C:\Python26\lib\sgmllib.py", line 338, in finish_starttag self.unknown_starttag(tag, attrs) File "C:\Python26\lib\site-packages\feedparser.py", line 1588, in unknown_starttag attrs = [(key, ((tag, key) in self.relative_uris) and self.resolveURI(value) or value) for key, value in attrs] File "C:\Python26\lib\site-packages\feedparser.py", line 1584, in resolveURI return _urljoin(self.baseuri, uri) File "C:\Python26\lib\site-packages\feedparser.py", line 286, in _urljoin return urlparse.urljoin(base, uri) File "C:\Python26\lib\urlparse.py", line 215, in urljoin params, query, fragment)) File "C:\Python26\lib\urlparse.py", line 184, in urlunparse return urlunsplit((scheme, netloc, url, query, fragment)) File "C:\Python26\lib\urlparse.py", line 192, in urlunsplit url = scheme + ':' + url File "C:\Python26\lib\encodings\cp1252.py", line 15, in decode return codecs.charmap_decode(input,errors,decoding_table) PARTIALLY SOLVED: This is reproducable when the URL being passed to feedparser.parse() is unicode. It won't repro when it's an ascii URL. And for the record, you need a feed that has some high character unicode characters. I am not sure why this is. A: Looks like the url that is giving you problem contains text with some encoding (such as latin-1, where 0xe2 would be "lowercase a with a circle on top" aka &acirc;) without a proper content-type header (it should have a charset= parameter in Content-Type: but doesn't). If that is the case feedparser cannot guess the encoding, tries the default (ascii), and fails. this part of feedparser's docs explains the issues in more detail. Unfortunately there are no "magic bullets" to solve this general issue (due to bozos that break the XML rules). You could try catching this exception, and in the handler read the url's contents separately (use urllib2) and try decoding them with various possible encodings -- then when you finally get a usable unicode object this way, feed that to feedparser.parse (whose first arg can be a url, a file stream, or a unicode string with the data). A: With reference to the OP's comment: Try any url literal, such as u'myfeed.blah/xml' It should reproduce. >>> from pprint import pprint as pp >>> import feedparser >>> d = feedparser.parse(u'myfeed.blah/xml') >>> pp(d) {'bozo': 1, 'bozo_exception': SAXParseException('not well-formed (invalid token)',), 'encoding': 'utf-8', 'entries': [], 'feed': {}, 'namespaces': {}, 'version': ''} >>> d = feedparser.parse(u'http://myfeed.blah/xml') >>> pp(d) {'bozo': 1, 'bozo_exception': URLError(gaierror(11001, 'getaddrinfo failed'),), 'encoding': 'utf-8', 'entries': [], 'feed': {}, 'version': None} >>> d = feedparser.parse("http://feedparser.org/docs/examples/atom10.xml") >>> d['bozo'] 0 >>> d['feed']['title'] u'Sample Feed' >>> d = feedparser.parse(u"http://feedparser.org/docs/examples/atom10.xml") >>> d['bozo'] 0 >>> d['feed']['title'] u'Sample Feed' >>> Please stop thrashing about; provide a URL that actually causes the problem.
feedparser fails during script run, but can't reproduce in interactive python console
It's failing with this when I run eclipse or when I run my script in iPython: 'ascii' codec can't decode byte 0xe2 in position 32: ordinal not in range(128) I don't know why, but when I simply execute the feedparse.parse(url) statement using the same url, there is no error thrown. This is stumping me big time. The code is as simple as: try: d = feedparser.parse(url) except Exception, e: logging.error('Error while retrieving feed.') logging.error(e) logging.error(formatExceptionInfo(None)) logging.error(formatExceptionInfo1()) Here is the stack trace: d = feedparser.parse(url) File "C:\Python26\lib\site-packages\feedparser.py", line 2623, in parse feedparser.feed(data) File "C:\Python26\lib\site-packages\feedparser.py", line 1441, in feed sgmllib.SGMLParser.feed(self, data) File "C:\Python26\lib\sgmllib.py", line 104, in feed self.goahead(0) File "C:\Python26\lib\sgmllib.py", line 143, in goahead k = self.parse_endtag(i) File "C:\Python26\lib\sgmllib.py", line 320, in parse_endtag self.finish_endtag(tag) File "C:\Python26\lib\sgmllib.py", line 360, in finish_endtag self.unknown_endtag(tag) File "C:\Python26\lib\site-packages\feedparser.py", line 476, in unknown_endtag method() File "C:\Python26\lib\site-packages\feedparser.py", line 1318, in _end_content value = self.popContent('content') File "C:\Python26\lib\site-packages\feedparser.py", line 700, in popContent value = self.pop(tag) File "C:\Python26\lib\site-packages\feedparser.py", line 641, in pop output = _resolveRelativeURIs(output, self.baseuri, self.encoding) File "C:\Python26\lib\site-packages\feedparser.py", line 1594, in _resolveRelativeURIs p.feed(htmlSource) File "C:\Python26\lib\site-packages\feedparser.py", line 1441, in feed sgmllib.SGMLParser.feed(self, data) File "C:\Python26\lib\sgmllib.py", line 104, in feed self.goahead(0) File "C:\Python26\lib\sgmllib.py", line 138, in goahead k = self.parse_starttag(i) File "C:\Python26\lib\sgmllib.py", line 296, in parse_starttag self.finish_starttag(tag, attrs) File "C:\Python26\lib\sgmllib.py", line 338, in finish_starttag self.unknown_starttag(tag, attrs) File "C:\Python26\lib\site-packages\feedparser.py", line 1588, in unknown_starttag attrs = [(key, ((tag, key) in self.relative_uris) and self.resolveURI(value) or value) for key, value in attrs] File "C:\Python26\lib\site-packages\feedparser.py", line 1584, in resolveURI return _urljoin(self.baseuri, uri) File "C:\Python26\lib\site-packages\feedparser.py", line 286, in _urljoin return urlparse.urljoin(base, uri) File "C:\Python26\lib\urlparse.py", line 215, in urljoin params, query, fragment)) File "C:\Python26\lib\urlparse.py", line 184, in urlunparse return urlunsplit((scheme, netloc, url, query, fragment)) File "C:\Python26\lib\urlparse.py", line 192, in urlunsplit url = scheme + ':' + url File "C:\Python26\lib\encodings\cp1252.py", line 15, in decode return codecs.charmap_decode(input,errors,decoding_table) PARTIALLY SOLVED: This is reproducable when the URL being passed to feedparser.parse() is unicode. It won't repro when it's an ascii URL. And for the record, you need a feed that has some high character unicode characters. I am not sure why this is.
[ "Looks like the url that is giving you problem contains text with some encoding (such as latin-1, where 0xe2 would be \"lowercase a with a circle on top\" aka &acirc;) without a proper content-type header (it should have a charset= parameter in Content-Type: but doesn't).\nIf that is the case feedparser cannot guess the encoding, tries the default (ascii), and fails.\nthis part of feedparser's docs explains the issues in more detail.\nUnfortunately there are no \"magic bullets\" to solve this general issue (due to bozos that break the XML rules). You could try catching this exception, and in the handler read the url's contents separately (use urllib2) and try decoding them with various possible encodings -- then when you finally get a usable unicode object this way, feed that to feedparser.parse (whose first arg can be a url, a file stream, or a unicode string with the data).\n", "With reference to the OP's comment: Try any url literal, such as u'myfeed.blah/xml' It should reproduce.\n>>> from pprint import pprint as pp\n>>> import feedparser\n\n>>> d = feedparser.parse(u'myfeed.blah/xml')\n>>> pp(d)\n{'bozo': 1,\n 'bozo_exception': SAXParseException('not well-formed (invalid token)',),\n 'encoding': 'utf-8',\n 'entries': [],\n 'feed': {},\n 'namespaces': {},\n 'version': ''}\n\n>>> d = feedparser.parse(u'http://myfeed.blah/xml')\n>>> pp(d)\n{'bozo': 1,\n 'bozo_exception': URLError(gaierror(11001, 'getaddrinfo failed'),),\n 'encoding': 'utf-8',\n 'entries': [],\n 'feed': {},\n 'version': None}\n\n>>> d = feedparser.parse(\"http://feedparser.org/docs/examples/atom10.xml\")\n>>> d['bozo']\n0\n>>> d['feed']['title']\nu'Sample Feed'\n\n>>> d = feedparser.parse(u\"http://feedparser.org/docs/examples/atom10.xml\")\n>>> d['bozo']\n0\n>>> d['feed']['title']\nu'Sample Feed'\n>>>\n\nPlease stop thrashing about; provide a URL that actually causes the problem.\n" ]
[ 1, 1 ]
[]
[]
[ "ascii", "character_encoding", "feedparser", "python", "unicode" ]
stackoverflow_0002857450_ascii_character_encoding_feedparser_python_unicode.txt
Q: xml filtering with python I have a following xml document: <node0> <node1> <node2 a1="x1"> ... </node2> <node2 a1="x2"> ... </node2> <node2 a1="x1"> ... </node2> </node1> </node0> I want to filter out node2 when a1="x2". The user provides the xpath and attribute values that need to tested and filtered out. I looked at some solutions in python like BeautifulSoup but they are too complicated and dont preserve the case of text. I want to keep the document same as before with some stuff filtered out. Can you recommend a simple and succinct solution? This should not be too complicated from the looks of it. The actual xml document is not as simple as above but idea is the same. A: This uses xml.etree.ElementTree which is in the standard library: import xml.etree.ElementTree as xee data='''\ <node1> <node2 a1="x1"> ... </node2> <node2 a1="x2"> ... </node2> <node2 a1="x1"> ... </node2> </node1> ''' doc=xee.fromstring(data) for tag in doc.findall('node2'): if tag.attrib['a1']=='x2': doc.remove(tag) print(xee.tostring(doc)) # <node1> # <node2 a1="x1"> ... </node2> # <node2 a1="x1"> ... </node2> # </node1> This uses lxml, which is not in the standard library, but has a more powerful syntax: import lxml.etree data='''\ <node1> <node2 a1="x1"> ... </node2> <node2 a1="x2"> ... </node2> <node2 a1="x1"> ... </node2> </node1> ''' doc = lxml.etree.XML(data) e=doc.find('node2/[@a1="x2"]') doc.remove(e) print(lxml.etree.tostring(doc)) # <node1> # <node2 a1="x1"> ... </node2> # <node2 a1="x1"> ... </node2> # </node1> Edit: If node2 is buried more deeply in the xml, then you can iterate through all the tags, check each parent tag to see if the node2 element is one of its children, and the remove it if so: Using only xml.etree.ElementTree: doc=xee.fromstring(data) for parent in doc.getiterator(): for child in parent.findall('node2'): if child.attrib['a1']=='x2': parent.remove(child) Using lxml: doc = lxml.etree.XML(data) for parent in doc.iter('*'): child=parent.find('node2/[@a1="x2"]') if child is not None: parent.remove(child)
xml filtering with python
I have a following xml document: <node0> <node1> <node2 a1="x1"> ... </node2> <node2 a1="x2"> ... </node2> <node2 a1="x1"> ... </node2> </node1> </node0> I want to filter out node2 when a1="x2". The user provides the xpath and attribute values that need to tested and filtered out. I looked at some solutions in python like BeautifulSoup but they are too complicated and dont preserve the case of text. I want to keep the document same as before with some stuff filtered out. Can you recommend a simple and succinct solution? This should not be too complicated from the looks of it. The actual xml document is not as simple as above but idea is the same.
[ "This uses xml.etree.ElementTree which is in the standard library:\nimport xml.etree.ElementTree as xee\ndata='''\\\n<node1>\n <node2 a1=\"x1\"> ... </node2>\n <node2 a1=\"x2\"> ... </node2>\n <node2 a1=\"x1\"> ... </node2>\n</node1>\n'''\ndoc=xee.fromstring(data)\n\nfor tag in doc.findall('node2'):\n if tag.attrib['a1']=='x2':\n doc.remove(tag)\nprint(xee.tostring(doc))\n# <node1>\n# <node2 a1=\"x1\"> ... </node2>\n# <node2 a1=\"x1\"> ... </node2>\n# </node1>\n\nThis uses lxml, which is not in the standard library, but has a more powerful syntax: \nimport lxml.etree\ndata='''\\\n<node1>\n <node2 a1=\"x1\"> ... </node2>\n <node2 a1=\"x2\"> ... </node2>\n <node2 a1=\"x1\"> ... </node2>\n</node1>\n'''\ndoc = lxml.etree.XML(data)\ne=doc.find('node2/[@a1=\"x2\"]')\ndoc.remove(e)\nprint(lxml.etree.tostring(doc))\n\n# <node1>\n# <node2 a1=\"x1\"> ... </node2>\n# <node2 a1=\"x1\"> ... </node2>\n# </node1>\n\nEdit: If node2 is buried more deeply in the xml, then you can iterate through all the tags, check each parent tag to see if the node2 element is one of its children, and the remove it if so:\nUsing only xml.etree.ElementTree:\ndoc=xee.fromstring(data)\nfor parent in doc.getiterator():\n for child in parent.findall('node2'):\n if child.attrib['a1']=='x2':\n parent.remove(child)\n\nUsing lxml:\ndoc = lxml.etree.XML(data)\nfor parent in doc.iter('*'):\n child=parent.find('node2/[@a1=\"x2\"]')\n if child is not None:\n parent.remove(child)\n\n" ]
[ 7 ]
[]
[]
[ "elementtree", "python", "xml", "xpath" ]
stackoverflow_0002869564_elementtree_python_xml_xpath.txt
Q: How do I send this email in Python, opening files and stuff? msg = EmailMessage(subject, body, from_email, [to_email]) msg.content_subtype = "html" msg.send() This is how I send an email in Django. But what if I want to open a text file and take into account all its line breaks and tabs. I want to take the body of the text file (with line breaks \n) and email it as text of the "body". A: If it's a text file, just send it as text. If you send it as "HTML", the whitespace won't be significant. A: In Django itself, it uses render_to_string("", {}) from django.template.loader. The advantage of it is that you can use contexts.
How do I send this email in Python, opening files and stuff?
msg = EmailMessage(subject, body, from_email, [to_email]) msg.content_subtype = "html" msg.send() This is how I send an email in Django. But what if I want to open a text file and take into account all its line breaks and tabs. I want to take the body of the text file (with line breaks \n) and email it as text of the "body".
[ "If it's a text file, just send it as text. If you send it as \"HTML\", the whitespace won't be significant.\n", "In Django itself, it uses render_to_string(\"\", {}) from django.template.loader. The advantage of it is that you can use contexts.\n" ]
[ 1, 0 ]
[]
[]
[ "django", "email", "file", "html", "python" ]
stackoverflow_0002869694_django_email_file_html_python.txt
Q: How to use regular expressions to pull a substring? (screen scraping) Hey guys, i'm really trying to understand regular expressions while scraping a site, i've been using it in my code enough to pull the following, but am stuck here. I need to quickly grab this: http://www.example.com/online/store/TitleDetail?detail&sku=123456789 from this: ('<a href="javascript:if(handleDoubleClick(this.id)){window.location=\'http://www.example.com/online/store/TitleDetail?detail&sku=123456789\';}" id="getTitleDetails_123456789">\r\n\t\t\t \tcheck store inventory\r\n\t\t\t </a>', 1) This is where I got confused. any ideas? Edit: the sku number changes per product so therein lies the trouble for me A: http://www\.example\.com/online/store/TitleDetail\?detail&sku=\d+ use the \d group with a "Greedy" +, to qualify any integer value in the sku field A: You don't need regular expressions for that, just use string methods: result = html[0].split("window.location='")[1].split("'")[0] A: pattern = re.compile(r"window.location=\\'([^\\]*)") haystack = r"""<a href="javascript:if(handleDoubleClick(this.id)){window.location=\'http://www.example.com/online/store/TitleDetail?detail&sku=123456789\';}" id="getTitleDetails_123456789">\r\n\t\t\t\tcheck store inventory\r\n\t\t\t</a>""" url = re.search(pattern, haystack).group(1) A: if there are always 9 digits http://www.example.com/online/store/TitleDetail?detail&sku=[0-9]{9} if there are an arbitrary number of digits: http://www.example.com/online/store/TitleDetail?detail&sku=[0-9]* more general: http*?sku=[0-9]* (the ? in *? means it will find shorter matches first, so it is less likely to find a match that spans multiple URLs.) edit: [0-9]. not [1-9] A: http://txt2re.com/ might help you
How to use regular expressions to pull a substring? (screen scraping)
Hey guys, i'm really trying to understand regular expressions while scraping a site, i've been using it in my code enough to pull the following, but am stuck here. I need to quickly grab this: http://www.example.com/online/store/TitleDetail?detail&sku=123456789 from this: ('<a href="javascript:if(handleDoubleClick(this.id)){window.location=\'http://www.example.com/online/store/TitleDetail?detail&sku=123456789\';}" id="getTitleDetails_123456789">\r\n\t\t\t \tcheck store inventory\r\n\t\t\t </a>', 1) This is where I got confused. any ideas? Edit: the sku number changes per product so therein lies the trouble for me
[ "http://www\\.example\\.com/online/store/TitleDetail\\?detail&sku=\\d+\n\nuse the \\d group with a \"Greedy\" +, to qualify any integer value in the sku field\n", "You don't need regular expressions for that, just use string methods:\nresult = html[0].split(\"window.location='\")[1].split(\"'\")[0]\n\n", "pattern = re.compile(r\"window.location=\\\\'([^\\\\]*)\")\nhaystack = r\"\"\"<a href=\"javascript:if(handleDoubleClick(this.id)){window.location=\\'http://www.example.com/online/store/TitleDetail?detail&sku=123456789\\';}\" id=\"getTitleDetails_123456789\">\\r\\n\\t\\t\\t\\tcheck store inventory\\r\\n\\t\\t\\t</a>\"\"\"\nurl = re.search(pattern, haystack).group(1)\n\n", "if there are always 9 digits\nhttp://www.example.com/online/store/TitleDetail?detail&sku=[0-9]{9}\n\nif there are an arbitrary number of digits: \nhttp://www.example.com/online/store/TitleDetail?detail&sku=[0-9]*\n\nmore general:\nhttp*?sku=[0-9]*\n\n(the ? in *? means it will find shorter matches first, so it is less likely to find a match that spans multiple URLs.)\nedit: [0-9]. not [1-9]\n", "http://txt2re.com/ might help you\n" ]
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "python", "regex", "screen_scraping" ]
stackoverflow_0002870444_python_regex_screen_scraping.txt
Q: Why learn Perl, Python, Ruby if the company is using C++, C# or Java as the application language? I wonder why would a C++, C#, Java developer want to learn a dynamic language? Assuming the company won't switch its main development language from C++/C#/Java to a dynamic one what use is there for a dynamic language? What helper tasks can be done by the dynamic languages faster or better after only a few days of learning than with the static language that you have been using for several years? Update After seeing the first few responses it is clear that there are two issues. My main interest would be something that is justifiable to the employer as an expense. That is, I am looking for justifications for the employer to finance the learning of a dynamic language. Aside from the obvious that the employee will have broader view, the employers are usually looking for some "real" benefit. A: A lot of times some quick task comes up that isn't part of the main software you are developing. Sometimes the task is one off ie compare this file to the database and let me know the differences. It is a lot easier to do text parsing in Perl/Ruby/Python than it is in Java or C# (partially because it is a lot easier to use regular expressions). It will probably take a lot less time to parse the text file using Perl/Ruby/Python (or maybe even vbscript cringe and then load it into the database than it would to create a Java/C# program to do it or to do it by hand. Also, due to the ease at which most of the dynamic languages parse text, they are great for code generation. Sure your final project must be in C#/Java/Transact SQL but instead of cutting and pasting 100 times, finding errors, and cutting and pasting another 100 times it is often (but not always) easier just to use a code generator. A recent example at work is we needed to get data from one accounting system into our accounting system. The system has an import format, but the old system had a completely different format (fixed width although some things had to be matched). The task is not to create a program to migrate the data over and over again. It is to shove the data into our system and then maintain it there going forward. So even though we are a C# and SQL Server shop, I used Python to convert the data into the format that could be imported by our application. Ultimately it doesn't matter that I used python, it matters that the data is in the system. My boss was pretty impressed. Where I often see the dynamic languages used for is testing. It is much easier to create a Python/Perl/Ruby program to link to a web service and throw some data against it than it is to create the equivalent Java program. You can also use python to hit against command line programs, generate a ton of garbage (but still valid) test data, etc.. quite easily. The other thing that dynamic languages are big on is code generation. Creating the C#/C++/Java code. Some examples follow: The first code generation task I often see is people using dynamic languages to maintain constants in the system. Instead of hand coding a bunch of enums, a dynamic language can be used to fairly easily parse a text file and create the Java/C# code with the enums. SQL is a whole other ball game but often you get better performance by cut and pasting 100 times instead of trying to do a function (due to caching of execution plans or putting complicated logic in a function causing you to go row by row instead of in a set). In fact it is quite useful to use the table definition to create certain stored procedures automatically. It is always better to get buy in for a code generator. But even if you don't, is it more fun to spend time cutting/pasting or is it more fun to create a Perl/Python/Ruby script once and then have that generate the code? If it takes you hours to hand code something but less time to create a code generator, then even if you use it once you have saved time and hence money. If it takes you longer to create a code generator than it takes to hand code once but you know you will have to update the code more than once, it may still make sense. If it takes you 2 hours to hand code, 4 hours to do the generator but you know you'll have to hand code equivalent work another 5 or 6 times than it is obviously better to create the generator. Also some things are easier with dynamic languages than Java/C#/C/C++. In particular regular expressions come to mind. If you start using regular expressions in Perl and realize their value, you may suddenly start making use of the Java regular expression library if you haven't before. If you have then there may be something else. I will leave you with one last example of a task that would have been great for a dynamic language. My work mate had to take a directory full of files and burn them to various cd's for various customers. There were a few customers but a lot of files and you had to look in them to see what they were. He did this task by hand....A Java/C# program would have saved time, but for one time and with all the development overhead it isn't worth it. However slapping something together in Perl/Python/Ruby probably would have been worth it. He spent several hours doing it. It would have taken less than one to create the Python script to inspect each file, match which customer it goes to, and then move the file to the appropriate place.....Again, not part of the standard job. But the task came up as a one off. Is it better to do it yourself, spend the larger amount of time to make Java/C# do the task, or spend a much smaller amount of time doing it in Python/Perl/Ruby. If you are using C or C++ the point is even more dramatic due to the extra concerns of programming in C or C++ (pointers, no array bounds checking, etc.). A: Let me turn your question on its head by asking what use it is to an American English speaker to learn another language? The languages we speak (and those we program in) inform the way we think. This can happen on a fundamental level, such as c++ versus javascript versus lisp, or on an implementation level, in which a ruby construct provides a eureka moment for a solution in your "real job." Speaking of your real job, if the market goes south and your employer decides to "right size" you, how do you think you'll stack up against a guy who is flexible because he's written software in tens of languages, instead of your limited exposure? All things being equal, I think the answer is clear. Finally, you program for a living because you love programming... right? A: I don't think anyone has mentioned this yet. Learning a new language can be fun! Surely that's a good enough reason to try something new. A: I primarily program in Java and C# but use dynamic languages (ruby/perl) to support smoother deployment, kicking off OS tasks, automated reporting, some log parsing, etc. After a short time learning and experimenting with ruby or perl you should be able to write some regex manipulating scripts that can alter data formats or grab information from logs. An example of a small ruby/perl script that could be written quickly would be a script to parse a very large log file and report out only a few events of interest in either a human readable format or a csv format. Also, having experience with a variety of different programming languages should help you think of new ways to tackle problems in more structured languages like Java, C++, and C#. A: One big reason to learn Perl or Ruby is to help you automate any complicated tasks that you have to do over and over. Or if you have to analyse contents of log files and you need more mungeing than available using grep, sed, etc. Also using other languages, e.g. Ruby, that don't have much "setup cost" will let you quickly prototype ideas before implementing them in C++, Java, etc. HTH cheers, Rob A: Do you expect to work for this company forever? If you're ever out on the job market, pehaps some prospective employers will be aware of the Python paradox. A: A good hockey player plays where the puck is. A great hockey player plays where the puck is going to be. - Wayne Gretzky Our industry is always changing. No language can be mainstream forever. To me Java, C++, .Net is where the puck is right now. And python, ruby, perl is where the puck is going to be. Decide for yourself if you wanna be good or great! A: Paul Graham posted an article several years ago about why Python programmers made better Java programmers. (http://www.paulgraham.com/pypar.html) Basically, regardless of whether the new language is relevant to the company's current methodology, learning a new language means learning new ideas. Someone who is willing to learn a language that isn't considered "business class" means that he is interested in programming, beyond just earning a paycheck. To quote Paul's site: And people don't learn Python because it will get them a job; they learn it because they genuinely like to program and aren't satisfied with the languages they already know. Which makes them exactly the kind of programmers companies should want to hire. Hence what, for lack of a better name, I'll call the Python paradox: if a company chooses to write its software in a comparatively esoteric language, they'll be able to hire better programmers, because they'll attract only those who cared enough to learn it. And for programmers the paradox is even more pronounced: the language to learn, if you want to get a good job, is a language that people don't learn merely to get a job. If an employer was willing to pay for the cost of learning a new language, chances are the people who volunteered to learn (assuming it wasn't a mandatory class) would be the same people to are already on the "fast track". A: When I first learned Python, I worked for a Java shop. Occasionally I'd have to do serious text-processing tasks which were much easier to do with quick Python scripts than Java programs. For example, if I had to parse a complex CSV file and figure out which of its rows corresponded to rows in our Oracle database, this was much easier to do with Python than Java. More than that, I found that learning Python made me a much better Java programmer; having learned many of the same concepts in another language I feel that I understand those concepts much better. And as for what makes Python easier than Java, you might check out this question: Java -> Python? A: Edit: I wrote this before reading the update to the original question. See my other answer for a better answer to the updated question. I will leave this as is as a warning against being the fastest gun in the west =) Over a decade ago, when I was learning the ways of the Computer, the Old Wise Men With Beards explained how C and C++ are the tools of the industry. No one used Pascal and only the foolhardy would risk their companies with assembler. And of course, no one would even mention the awful slow ugly thing called Java. It will not be a tool for serious business. So. Um. Replace the languages in the above story and perhaps you can predict the future. Perhaps you can't. Point is, Java will not be the Last Programming Language ever and also you will most likely switch employers as well. The future is charging at you 24 hours per day. Be prepared. Learning new languages is good for you. Also, in some cases it can give you bragging rights for a long time. My first university course was in Scheme. So when people talk to me about the new language du jour, my response is something like "First-class functions? That's so last century." And of course, you get more stuff done with a high-level language. A: Learning a new language is a long-term process. In a couple of days you'll learn the basics, yes. But! As you probably know, the real practical applicability of any language is tied to the standard library and other available components. Learning how to use the efficiently requires a lot of hands-on experience. Perhaps the only immediate short-term benefit is that developers learn to distinguish the nails that need a Python/Perl/Ruby -hammer. And, if they are any good, they can then study some more (online, perhaps!) and become real experts. The long-term benefits are easier to imagine: The employee becomes a better developer. Better developer => better quality. We are living in a knowledge economy these days. It's wiser to invest in those brains that already work for you. It is easier to adapt when the next big language emerges. It is very likely that the NBL will have many of the features present in today's scripting languages: first-class functions, closures, streams/generators, etc. New market possibilities and ability to respond more quickly. Even if you are not writing Python, other people are. Your clients? Another vendor in the project? Perhaps a critical component was written in some other language? It will cost money and time, if you do not have people who can understand the code and interface with it. Recruitment. If your company has a reputation of teaching new and interesting stuff to people, it will be easier to recruit the top people. Everyone is doing Java/C#/C++. It is not a very effective way to differentiate yourself in the job market. A: Towards answering the updated question, its a chicken/egg problem. The best way to justify an expense is to show how it reduces a cost somewhere else, so you may need to spend some extra/personal time to learn something first to build some kind of functional prototype. Show your boss a demo like "hey, i did this thing, and it saves me this much time [or better yet, this much $$], imagine if everyone could use this how much money we would save" and then after they agree, explain how it is some other technology and that it is worth the expense to get more training, and training for others on how to do it better. A: I have often found that learning another language, especially a dynamically typed language, can teach you things about other languages and make you an overall better programmer. Learning ruby, for example, will teach you Object Oriented programming in ways Java wont, and vice versa. All in all, I believe that it is better to be a well rounded programmer than stuck in a single language. It makes you more valuable to the companies/clients you work for. A: check out the answers to this thead: https://stackoverflow.com/questions/76364/what-is-the-single-most-effective-thing-you-did-to-improve-your-programming-ski#84112 Learning new languages is about keeping an open mind and learning new ways of doing things. A: Im not sure if this is what you are looking for, but we write our main application with Java at the small company I work for, but have used python to write smaller scripts quickly. Backup software, temporary scripts to manipulate data and push out results. It just seems easier sometimes to sit down with python and write a quick script than mess with classes and stuff in java. Temp scripts that aren't going to stick around don't need a lot of design time wasted on them. And I am lazy, but it is good to just learn as much as you can of course and see what features exist in other languages. Knowing more never hurts you in future career changes :) A: It's all about broadening your horizons as a developer. If you limit yourself to only strong-typed languages, you may not end up the best programmer you could. As for tasks, Python/Lua/Ruby/Perl are great for small simple tasks, like finding some files and renaming them. They also work great when paired with a framework (e.g. Rails, Django, Lua for Windows) for developing simple apps quickly. Hell, 37Signals is based on creating simple yet very useful apps in Ruby on Rails. A: They're useful for the "Quick Hack" that is for plugging a gap in your main language for a quick (and potentially dirty) fix faster than it would take to develop the same in your main language. An example: a simple script in perl to go through a large text file and replace all instances of an email address with another is trivial with an amount of time taken in the 10 minute range. Hacking a console app together to do the same in your main language would take multiples of that. You also have the benefit that exposing yourself to additional languages broadens your abilities and learning to attack problems from a different languages perspective can be as valuable as the language itself. Finally, scripting languages are very useful in the realm of extension. Take LUA as an example. You can bolt a lua interpreter into your app with very little overhead and you now have a way to create rich scripting functionality that can be exposed to end users or altered and distributed quickly without requiring a rebuild of the entire app. This is used to great effect in many games most notably World of Warcraft. A: Personally I work on a Java app, but I couldn't get by without perl for some supporting scripts. I've got scripts to quickly flip what db I'm pointing at, scripts to run build scripts, scripts to scrape data & compare stuff. Sure I could do all that with java, or maybe shell scripts (I've got some of those too), but who wants to compile a class (making sure the classpath is set right etc) when you just need something quick and dirty. Knowing a scripting language can remove 90% of those boring/repetitive manual tasks. A: Learning something with a flexible OOP system, like Lisp or Perl (see Moose), will allow you to better expand and understand your thoughts on software engineering. Ideally, every language has some unique facet (whether it be CLOS or some other technique) that enhances, extends and grows your abilities as a programmer. A: If all you have is a hammer, every problem begins to look like a nail. There are times when having a screwdriver or pair of pliers makes a complicated problem trivial. Nobody asks contractors, carpenters, etc, "Why learn to use a screwdriver if i already have a hammer?". Really good contractors/carpenters have tons of tools and know how to use them well. All programmers should be doing the same thing, learning to use new tools and use them well. But before we use any power tools, lets take a moment to talk about shop safety. Be sure to read, understand, and follow all the safety rules that come with your power tools. Doing so will greatly reduce the risk of personal injury. And remember this: there is no more important rule than to wear these: safety glasses -- Norm A: I think the main benefits of dynamic languages can be boiled down to Rapid development Glue The short design-code-test cycle time makes dynamic languages ideal for prototyping, tools, and quick & dirty one-off scripts. IMHO, the latter two can make a huge impact on a programmer's productivity. It amazes me how many people trudge through things manually instead of whipping up a tool to do it for them. I think it's because they don't have something like Perl in their toolbox. The ability to interface with just about anything (other programs or languages, databases, etc.) makes it easy to reuse existing work and automate tasks that would otherwise need to be done manually. A: Given the increasing focus to running dynamic languages (da-vinci vm etc.) on the JVM and the increasing number of dynamic languages that do run on it (JRuby, Grrovy, Jython) I think the usecases are just increasing. Some of the scenarios I found really benifited are Prototyping- use RoR or Grails to build quick prototypes with advantage of being able to runn it on the standard app server and (maybe) reuse existing services etc. Testing- right unit tests much much faster in dynamic languages Performance/automation test scripting- some of these tools are starting to allow the use standard dynamic language of choice to write the test scripts instead of proprietary script languages. Side benefit might be to the able to reuse some unit test code you've already written. A: Don't tell your employer that you want to learn Ruby. Tell him you want to learn about the state-of-the-art in web framework technologies. it just happens that the hottest ones are Django and Ruby on Rails. A: I have found the more that I play with Ruby, the better I understand C#. 1) As you switch between these languages that each of them has their own constructs and philosophies behind the problems that they try to solve. This will help you when finding the right tool for the job or the domain of a problem. 2) The role of the compiler (or interpreter for some languages) becomes more prominent. Why is Ruby's type system differ from the .Net/C# system? What problems do each of these solve? You'll find yourself understanding at a lower level the constructs of the compiler and its influence on the language 3) Switching between Ruby and C# really helped me to understand Design Patterns better. I really suggest implementing common design patterns in a language like C# and then in a language like Ruby. It often helped me see through some of the compiler ceremony to the philosophy of a particular pattern. 4) A different community. C#, Java, Ruby, Python, etc all have different communities that can help engage your abilities. It is a great way to take your craft to the next level. 5) Last, but not least, because new languages are fun :) A: Philosophical issues aside, I know that I have gotten value from writing quick-and-dirty Ruby scripts to solve brute-force problems that Java was just too big for. Last year I had three separate directory structures that were all more-or-less the same, but with lots of differences among the files (the client hadn't heard of version control and I'll leave the rest to your imagination). It would have taken a great deal of overhead to write an analyzer in Java, but in Ruby I had one working in about 40 minutes. A: Often, dynamc languages (especially python and lua) are embedded in programs to add a more plugin-like functionality and because they are high-level languages that make it easy to add certain behavior, where a low/mid-level language is not needed. Lua specificially lacks all the low-level system calls because it was designed for easeof-use to add functionality within the program, not as a general programming language. A: You should also consider learning a functional programming language like Scala. It has many of the advantages of Ruby, including a concise syntax, and powerful features like closures. But it compiles to Java class files and and integrate seamlessly into a Java stack, which may make it much easier for your employer to swallow. Scala isn't dynamically typed, but its "implicit conversion" feature gives many, perhaps even all of the benefits of dynamic typing, while retaining many of the advantages of static typing. A: Dynamic languages are fantastic for prototyping ideas. Often for performance reasons they won't work for permanent solutions or products. But, with languages like Python, which allow you to embed standard C/C++/Java inside them or visa versa, you can speed up the really critical bits but leave it glued together with the flexibility of a dynamic language. ...and so you get the best of both worlds. If you need to justify this in terms of why more people should learn these languages, just point out much faster you can develop the same software and how much more robust the solution is (because debugging/fixing problems in dynamic languages is in my experience, considerably easier!). A: Knowing grep and ruby made it possible to narrow down a problem, and verify the fix for, an issue involving tons of java exceptions on some production servers. Because I threw the solution together in ruby, it was done (designed, implemented, tested, run, bug-fixed, re-run, enhanced, results analyzed) in an afternoon instead of a couple of days. I could have solved the same problem using an all-java solution or a C# solution, but it most likely would have taken me longer. Having dynamic language expertise also sometimes leads you to simpler solutions in less dynamic languages. In ruby, perl or python, you just intuitively reach for associative arrays (hashes, dictionaries, whatever word you want to use) for the smallest things, where you might be tempted to create a complex class hierarchy in a statically typed language when the problem doesn't necessarily demand it. Plus you can plug in most scripting languages into most runtimes. So it doesn't have to be either/or. A: The "real benefit" that an employer could see is a better programmer who can implement solutions faster; however, you will not be able to provide any hard numbers to justify the expense and an employer will most likely have you work on what makes money now as opposed to having you work on things that make the future better. The only time you can get training on the employer's dime, is when they perceive a need for it and it's cheaper than hiring a new person who already has that skill-set. A: Testing. It's often quicker and easier to test your C#/Java application by using a dynamic language. You can do exploratory testing at the interactive prompt and quickly create automated test scripts. A: Others have already explained why learning more languages makes you a better programmer. As for convincing your boss it's worth it, this is probably just your company's culture. Some places make career and skill progress a policy (move up or out), some places value it but leave it up to the employee's initiative, and some places are very focused on the bottom line. If you have to explain why learning a language is a good thing to your boss, my advice would be to stay at work only as long as necessary, then go home and study new things on your own. A: For after work work, for freelance jobs...:) and final to be programming literate as possible as...;) A: Dynamic languages are a different way to think and sometimes the practices you learn from a dynamic or functional language can transfer to the more statically typed languages but if you never take the time to learn different languages, you'll never get the benefit of having a knew way to think when you are coding. A: Don't bother your employer, spend ~$40 on a book, download some software, and devote some time each day to read/do exercises. In no time you'll be trained :)
Why learn Perl, Python, Ruby if the company is using C++, C# or Java as the application language?
I wonder why would a C++, C#, Java developer want to learn a dynamic language? Assuming the company won't switch its main development language from C++/C#/Java to a dynamic one what use is there for a dynamic language? What helper tasks can be done by the dynamic languages faster or better after only a few days of learning than with the static language that you have been using for several years? Update After seeing the first few responses it is clear that there are two issues. My main interest would be something that is justifiable to the employer as an expense. That is, I am looking for justifications for the employer to finance the learning of a dynamic language. Aside from the obvious that the employee will have broader view, the employers are usually looking for some "real" benefit.
[ "A lot of times some quick task comes up that isn't part of the main software you are developing. Sometimes the task is one off ie compare this file to the database and let me know the differences. It is a lot easier to do text parsing in Perl/Ruby/Python than it is in Java or C# (partially because it is a lot easier to use regular expressions). It will probably take a lot less time to parse the text file using Perl/Ruby/Python (or maybe even vbscript cringe and then load it into the database than it would to create a Java/C# program to do it or to do it by hand.\nAlso, due to the ease at which most of the dynamic languages parse text, they are great for code generation. Sure your final project must be in C#/Java/Transact SQL but instead of cutting and pasting 100 times, finding errors, and cutting and pasting another 100 times it is often (but not always) easier just to use a code generator.\nA recent example at work is we needed to get data from one accounting system into our accounting system. The system has an import format, but the old system had a completely different format (fixed width although some things had to be matched). The task is not to create a program to migrate the data over and over again. It is to shove the data into our system and then maintain it there going forward. So even though we are a C# and SQL Server shop, I used Python to convert the data into the format that could be imported by our application. Ultimately it doesn't matter that I used python, it matters that the data is in the system. My boss was pretty impressed.\nWhere I often see the dynamic languages used for is testing. It is much easier to create a Python/Perl/Ruby program to link to a web service and throw some data against it than it is to create the equivalent Java program. You can also use python to hit against command line programs, generate a ton of garbage (but still valid) test data, etc.. quite easily.\nThe other thing that dynamic languages are big on is code generation. Creating the C#/C++/Java code. Some examples follow:\nThe first code generation task I often see is people using dynamic languages to maintain constants in the system. Instead of hand coding a bunch of enums, a dynamic language can be used to fairly easily parse a text file and create the Java/C# code with the enums.\nSQL is a whole other ball game but often you get better performance by cut and pasting 100 times instead of trying to do a function (due to caching of execution plans or putting complicated logic in a function causing you to go row by row instead of in a set). In fact it is quite useful to use the table definition to create certain stored procedures automatically.\nIt is always better to get buy in for a code generator. But even if you don't, is it more fun to spend time cutting/pasting or is it more fun to create a Perl/Python/Ruby script once and then have that generate the code? If it takes you hours to hand code something but less time to create a code generator, then even if you use it once you have saved time and hence money. If it takes you longer to create a code generator than it takes to hand code once but you know you will have to update the code more than once, it may still make sense. If it takes you 2 hours to hand code, 4 hours to do the generator but you know you'll have to hand code equivalent work another 5 or 6 times than it is obviously better to create the generator.\nAlso some things are easier with dynamic languages than Java/C#/C/C++. In particular regular expressions come to mind. If you start using regular expressions in Perl and realize their value, you may suddenly start making use of the Java regular expression library if you haven't before. If you have then there may be something else.\nI will leave you with one last example of a task that would have been great for a dynamic language. My work mate had to take a directory full of files and burn them to various cd's for various customers. There were a few customers but a lot of files and you had to look in them to see what they were. He did this task by hand....A Java/C# program would have saved time, but for one time and with all the development overhead it isn't worth it. However slapping something together in Perl/Python/Ruby probably would have been worth it. He spent several hours doing it. It would have taken less than one to create the Python script to inspect each file, match which customer it goes to, and then move the file to the appropriate place.....Again, not part of the standard job. But the task came up as a one off. Is it better to do it yourself, spend the larger amount of time to make Java/C# do the task, or spend a much smaller amount of time doing it in Python/Perl/Ruby. If you are using C or C++ the point is even more dramatic due to the extra concerns of programming in C or C++ (pointers, no array bounds checking, etc.).\n", "Let me turn your question on its head by asking what use it is to an American English speaker to learn another language?\nThe languages we speak (and those we program in) inform the way we think. This can happen on a fundamental level, such as c++ versus javascript versus lisp, or on an implementation level, in which a ruby construct provides a eureka moment for a solution in your \"real job.\"\nSpeaking of your real job, if the market goes south and your employer decides to \"right size\" you, how do you think you'll stack up against a guy who is flexible because he's written software in tens of languages, instead of your limited exposure? All things being equal, I think the answer is clear.\nFinally, you program for a living because you love programming... right?\n", "I don't think anyone has mentioned this yet. Learning a new language can be fun! Surely that's a good enough reason to try something new. \n", "I primarily program in Java and C# but use dynamic languages (ruby/perl) to support smoother deployment, kicking off OS tasks, automated reporting, some log parsing, etc.\nAfter a short time learning and experimenting with ruby or perl you should be able to write some regex manipulating scripts that can alter data formats or grab information from logs. An example of a small ruby/perl script that could be written quickly would be a script to parse a very large log file and report out only a few events of interest in either a human readable format or a csv format. \nAlso, having experience with a variety of different programming languages should help you think of new ways to tackle problems in more structured languages like Java, C++, and C#.\n", "One big reason to learn Perl or Ruby is to help you automate any complicated tasks that you have to do over and over.\nOr if you have to analyse contents of log files and you need more mungeing than available using grep, sed, etc.\nAlso using other languages, e.g. Ruby, that don't have much \"setup cost\" will let you quickly prototype ideas before implementing them in C++, Java, etc.\nHTH\ncheers,\nRob\n", "Do you expect to work for this company forever? If you're ever out on the job market, pehaps some prospective employers will be aware of the Python paradox.\n", "A good hockey player plays where the puck is. A great hockey player plays where the puck is going to be.\n- Wayne Gretzky\nOur industry is always changing. No language can be mainstream forever. To me Java, C++, .Net is where the puck is right now. And python, ruby, perl is where the puck is going to be. Decide for yourself if you wanna be good or great!\n", "Paul Graham posted an article several years ago about why Python programmers made better Java programmers. (http://www.paulgraham.com/pypar.html)\nBasically, regardless of whether the new language is relevant to the company's current methodology, learning a new language means learning new ideas. Someone who is willing to learn a language that isn't considered \"business class\" means that he is interested in programming, beyond just earning a paycheck.\nTo quote Paul's site:\n\nAnd people don't learn Python because\n it will get them a job; they learn it\n because they genuinely like to program\n and aren't satisfied with the\n languages they already know.\nWhich makes them exactly the kind of\n programmers companies should want to\n hire. Hence what, for lack of a better\n name, I'll call the Python paradox: if\n a company chooses to write its\n software in a comparatively esoteric\n language, they'll be able to hire\n better programmers, because they'll\n attract only those who cared enough to\n learn it. And for programmers the\n paradox is even more pronounced: the\n language to learn, if you want to get\n a good job, is a language that people\n don't learn merely to get a job.\n\nIf an employer was willing to pay for the cost of learning a new language, chances are the people who volunteered to learn (assuming it wasn't a mandatory class) would be the same people to are already on the \"fast track\".\n", "When I first learned Python, I worked for a Java shop. Occasionally I'd have to do serious text-processing tasks which were much easier to do with quick Python scripts than Java programs. For example, if I had to parse a complex CSV file and figure out which of its rows corresponded to rows in our Oracle database, this was much easier to do with Python than Java.\nMore than that, I found that learning Python made me a much better Java programmer; having learned many of the same concepts in another language I feel that I understand those concepts much better. And as for what makes Python easier than Java, you might check out this question: Java -> Python?\n", "Edit: I wrote this before reading the update to the original question. See my other answer for a better answer to the updated question. I will leave this as is as a warning against being the fastest gun in the west =)\nOver a decade ago, when I was learning the ways of the Computer, the Old Wise Men With Beards explained how C and C++ are the tools of the industry. No one used Pascal and only the foolhardy would risk their companies with assembler.\nAnd of course, no one would even mention the awful slow ugly thing called Java. It will not be a tool for serious business.\nSo. Um. Replace the languages in the above story and perhaps you can predict the future. Perhaps you can't. Point is, Java will not be the Last Programming Language ever and also you will most likely switch employers as well. The future is charging at you 24 hours per day. Be prepared.\nLearning new languages is good for you. Also, in some cases it can give you bragging rights for a long time. My first university course was in Scheme. So when people talk to me about the new language du jour, my response is something like \"First-class functions? That's so last century.\"\nAnd of course, you get more stuff done with a high-level language.\n", "Learning a new language is a long-term process. In a couple of days you'll learn the basics, yes. But! As you probably know, the real practical applicability of any language is tied to the standard library and other available components. Learning how to use the efficiently requires a lot of hands-on experience. \nPerhaps the only immediate short-term benefit is that developers learn to distinguish the nails that need a Python/Perl/Ruby -hammer. And, if they are any good, they can then study some more (online, perhaps!) and become real experts.\nThe long-term benefits are easier to imagine:\n\nThe employee becomes a better developer. Better developer => better quality. We are living in a knowledge economy these days. It's wiser to invest in those brains that already work for you.\nIt is easier to adapt when the next big language emerges. It is very likely that the NBL will have many of the features present in today's scripting languages: first-class functions, closures, streams/generators, etc. \nNew market possibilities and ability to respond more quickly. Even if you are not writing Python, other people are. Your clients? Another vendor in the project? Perhaps a critical component was written in some other language? It will cost money and time, if you do not have people who can understand the code and interface with it.\nRecruitment. If your company has a reputation of teaching new and interesting stuff to people, it will be easier to recruit the top people. Everyone is doing Java/C#/C++. It is not a very effective way to differentiate yourself in the job market.\n\n", "Towards answering the updated question, its a chicken/egg problem. The best way to justify an expense is to show how it reduces a cost somewhere else, so you may need to spend some extra/personal time to learn something first to build some kind of functional prototype.\nShow your boss a demo like \"hey, i did this thing, and it saves me this much time [or better yet, this much $$], imagine if everyone could use this how much money we would save\"\nand then after they agree, explain how it is some other technology and that it is worth the expense to get more training, and training for others on how to do it better.\n", "I have often found that learning another language, especially a dynamically typed language, can teach you things about other languages and make you an overall better programmer. Learning ruby, for example, will teach you Object Oriented programming in ways Java wont, and vice versa. All in all, I believe that it is better to be a well rounded programmer than stuck in a single language. It makes you more valuable to the companies/clients you work for.\n", "check out the answers to this thead: \nhttps://stackoverflow.com/questions/76364/what-is-the-single-most-effective-thing-you-did-to-improve-your-programming-ski#84112\nLearning new languages is about keeping an open mind and learning new ways of doing things.\n", "Im not sure if this is what you are looking for, but we write our main application with Java at the small company I work for, but have used python to write smaller scripts quickly. Backup software, temporary scripts to manipulate data and push out results. It just seems easier sometimes to sit down with python and write a quick script than mess with classes and stuff in java. \nTemp scripts that aren't going to stick around don't need a lot of design time wasted on them.\nAnd I am lazy, but it is good to just learn as much as you can of course and see what features exist in other languages. Knowing more never hurts you in future career changes :)\n", "It's all about broadening your horizons as a developer. If you limit yourself to only strong-typed languages, you may not end up the best programmer you could.\nAs for tasks, Python/Lua/Ruby/Perl are great for small simple tasks, like finding some files and renaming them. They also work great when paired with a framework (e.g. Rails, Django, Lua for Windows) for developing simple apps quickly. Hell, 37Signals is based on creating simple yet very useful apps in Ruby on Rails. \n", "They're useful for the \"Quick Hack\" that is for plugging a gap in your main language for a quick (and potentially dirty) fix faster than it would take to develop the same in your main language. An example: a simple script in perl to go through a large text file and replace all instances of an email address with another is trivial with an amount of time taken in the 10 minute range. Hacking a console app together to do the same in your main language would take multiples of that.\nYou also have the benefit that exposing yourself to additional languages broadens your abilities and learning to attack problems from a different languages perspective can be as valuable as the language itself.\nFinally, scripting languages are very useful in the realm of extension. Take LUA as an example. You can bolt a lua interpreter into your app with very little overhead and you now have a way to create rich scripting functionality that can be exposed to end users or altered and distributed quickly without requiring a rebuild of the entire app. This is used to great effect in many games most notably World of Warcraft.\n", "Personally I work on a Java app, but I couldn't get by without perl for some supporting scripts. \nI've got scripts to quickly flip what db I'm pointing at, scripts to run build scripts, scripts to scrape data & compare stuff. \nSure I could do all that with java, or maybe shell scripts (I've got some of those too), but who wants to compile a class (making sure the classpath is set right etc) when you just need something quick and dirty. Knowing a scripting language can remove 90% of those boring/repetitive manual tasks.\n", "Learning something with a flexible OOP system, like Lisp or Perl (see Moose), will allow you to better expand and understand your thoughts on software engineering. Ideally, every language has some unique facet (whether it be CLOS or some other technique) that enhances, extends and grows your abilities as a programmer.\n", "If all you have is a hammer, every problem begins to look like a nail.\nThere are times when having a screwdriver or pair of pliers makes a complicated problem trivial.\nNobody asks contractors, carpenters, etc, \"Why learn to use a screwdriver if i already have a hammer?\". Really good contractors/carpenters have tons of tools and know how to use them well. All programmers should be doing the same thing, learning to use new tools and use them well.\n\nBut before we use any power tools, lets\n take a moment to talk about shop safety. Be sure\n to read, understand, and follow all the\n safety rules that come with your power\n tools. Doing so will greatly reduce\n the risk of personal injury. And remember\n this: there is no more important rule\n than to wear these: safety glasses\n -- Norm\n\n", "I think the main benefits of dynamic languages can be boiled down to\n\nRapid development\nGlue\n\nThe short design-code-test cycle time makes dynamic languages ideal for prototyping, tools, and quick & dirty one-off scripts. IMHO, the latter two can make a huge impact on a programmer's productivity. It amazes me how many people trudge through things manually instead of whipping up a tool to do it for them. I think it's because they don't have something like Perl in their toolbox.\nThe ability to interface with just about anything (other programs or languages, databases, etc.) makes it easy to reuse existing work and automate tasks that would otherwise need to be done manually.\n", "Given the increasing focus to running dynamic languages (da-vinci vm etc.) on the JVM and the increasing number of dynamic languages that do run on it (JRuby, Grrovy, Jython) I think the usecases are just increasing. Some of the scenarios I found really benifited are\n\nPrototyping- use RoR or Grails to build quick prototypes with advantage of being able to runn it on the standard app server and (maybe) reuse existing services etc.\nTesting- right unit tests much much faster in dynamic languages\nPerformance/automation test scripting- some of these tools are starting to allow the use standard dynamic language of choice to write the test scripts instead of proprietary script languages. Side benefit might be to the able to reuse some unit test code you've already written.\n\n", "Don't tell your employer that you want to learn Ruby. Tell him you want to learn about the state-of-the-art in web framework technologies. it just happens that the hottest ones are Django and Ruby on Rails.\n", "I have found the more that I play with Ruby, the better I understand C#. \n1) As you switch between these languages that each of them has their own constructs and philosophies behind the problems that they try to solve. This will help you when finding the right tool for the job or the domain of a problem.\n2) The role of the compiler (or interpreter for some languages) becomes more prominent. Why is Ruby's type system differ from the .Net/C# system? What problems do each of these solve? You'll find yourself understanding at a lower level the constructs of the compiler and its influence on the language\n3) Switching between Ruby and C# really helped me to understand Design Patterns better. I really suggest implementing common design patterns in a language like C# and then in a language like Ruby. It often helped me see through some of the compiler ceremony to the philosophy of a particular pattern.\n4) A different community. C#, Java, Ruby, Python, etc all have different communities that can help engage your abilities. It is a great way to take your craft to the next level.\n5) Last, but not least, because new languages are fun :)\n", "Philosophical issues aside, I know that I have gotten value from writing quick-and-dirty Ruby scripts to solve brute-force problems that Java was just too big for. Last year I had three separate directory structures that were all more-or-less the same, but with lots of differences among the files (the client hadn't heard of version control and I'll leave the rest to your imagination). \nIt would have taken a great deal of overhead to write an analyzer in Java, but in Ruby I had one working in about 40 minutes.\n", "Often, dynamc languages (especially python and lua) are embedded in programs to add a more plugin-like functionality and because they are high-level languages that make it easy to add certain behavior, where a low/mid-level language is not needed.\nLua specificially lacks all the low-level system calls because it was designed for easeof-use to add functionality within the program, not as a general programming language.\n", "You should also consider learning a functional programming language like Scala. It has many of the advantages of Ruby, including a concise syntax, and powerful features like closures. But it compiles to Java class files and and integrate seamlessly into a Java stack, which may make it much easier for your employer to swallow.\nScala isn't dynamically typed, but its \"implicit conversion\" feature gives many, perhaps even all of the benefits of dynamic typing, while retaining many of the advantages of static typing.\n", "Dynamic languages are fantastic for prototyping ideas. Often for performance reasons they won't work for permanent solutions or products. But, with languages like Python, which allow you to embed standard C/C++/Java inside them or visa versa, you can speed up the really critical bits but leave it glued together with the flexibility of a dynamic language.\n...and so you get the best of both worlds. If you need to justify this in terms of why more people should learn these languages, just point out much faster you can develop the same software and how much more robust the solution is (because debugging/fixing problems in dynamic languages is in my experience, considerably easier!).\n", "Knowing grep and ruby made it possible to narrow down a problem, and verify the fix for, an issue involving tons of java exceptions on some production servers. Because I threw the solution together in ruby, it was done (designed, implemented, tested, run, bug-fixed, re-run, enhanced, results analyzed) in an afternoon instead of a couple of days. I could have solved the same problem using an all-java solution or a C# solution, but it most likely would have taken me longer.\nHaving dynamic language expertise also sometimes leads you to simpler solutions in less dynamic languages. In ruby, perl or python, you just intuitively reach for associative arrays (hashes, dictionaries, whatever word you want to use) for the smallest things, where you might be tempted to create a complex class hierarchy in a statically typed language when the problem doesn't necessarily demand it.\nPlus you can plug in most scripting languages into most runtimes. So it doesn't have to be either/or.\n", "The \"real benefit\" that an employer could see is a better programmer who can implement solutions faster; however, you will not be able to provide any hard numbers to justify the expense and an employer will most likely have you work on what makes money now as opposed to having you work on things that make the future better. \nThe only time you can get training on the employer's dime, is when they perceive a need for it and it's cheaper than hiring a new person who already has that skill-set.\n", "Testing.\nIt's often quicker and easier to test your C#/Java application by using a dynamic language. You can do exploratory testing at the interactive prompt and quickly create automated test scripts.\n", "Others have already explained why learning more languages makes you a better programmer.\nAs for convincing your boss it's worth it, this is probably just your company's culture. Some places make career and skill progress a policy (move up or out), some places value it but leave it up to the employee's initiative, and some places are very focused on the bottom line.\nIf you have to explain why learning a language is a good thing to your boss, my advice would be to stay at work only as long as necessary, then go home and study new things on your own.\n", "For after work work, for freelance jobs...:) and final to be programming literate as possible as...;) \n", "Dynamic languages are a different way to think and sometimes the practices you learn from a dynamic or functional language can transfer to the more statically typed languages but if you never take the time to learn different languages, you'll never get the benefit of having a knew way to think when you are coding.\n", "Don't bother your employer, spend ~$40 on a book, download some software, and devote some time each day to read/do exercises. In no time you'll be trained :)\n" ]
[ 81, 21, 14, 9, 7, 5, 5, 5, 4, 3, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "c#", "java", "perl", "python", "ruby" ]
stackoverflow_0000084340_c#_java_perl_python_ruby.txt
Q: Twisted Matrix and telnet server implementation I have a project which is essentially a game server where users connect and send text commands via telnet. The code is in C and really old and unmodular and has several bugs and missing features. The main function alone is half the code. I came to the conclusion that rewriting it in Python, with Twisted, could actually result in faster completement, besides other benefits. So, here is the questions: What packages and modules I should use? I see a "telnet" module inside "protocols" package. I also see "cronch" package with "ssh" and another "telnet" module. I'm a complete novice regarding Python. A: Greg's suggestion to try to become familiar with Python before trying to take on Twisted is perhaps a reasonable one. Limiting the possible sources of your confusion may help you avoid some very frustrating cases. On the other hand, I know a lot of people who take on a Twisted-based project as a first Python learning experience, and succeed. So it's possible. And you'll have to do something first. There's no guarantee that what you pick instead of Twisted will be easier. :) As far as the specifics of telnet go, you want to use twisted.conch.telnet, not twisted.protocols.telnet. The former is newer, better tested, more featureful, and has several examples (although unfortunately not a lot of documentation beyond that). The main telnet example shows you the most useful event handlers you can define if you use twisted.conch.telnet. Unfortunately it doesn't really explain what they do, nor does it give a demonstration of how you might negotiation options. If you're already familiar with the telnet protocol itself (primarily the option negotiation part of it), this should make sense to you. If you're thinking of "telnet" as just a way to pass human readable/writeable bytes between two computers, then you probably haven't run across option negotiation before and it might not make much sense. You can either ignore it, or check out the telnet RFC to learn more (it's a little dense, though). For performing option negotiations yourself, you can at least take a look at the API documentation for the self.transport object you see in the above linked example (this isn't a regular TCP transport as you'll find used throughout much of Twisted, but a special telnet-derived transport which sits on top of TCP, so it has a few extra features). If you just want to pass bytes around, though, then you can focus on the dataReceived method and on self.transport.write. The former will be called when you receive bytes from your peer; the latter you can call to send bytes to your peer. A: It sounds like you've got two separate tasks here: Port the code from C to Python. Rewrite the whole program to use Twisted. Since you're new to Python, I would be inclined to do the first one first, before trying to make the program structure work in Twisted. If the program is old, there isn't likely to be any performance problems running it on modern hardware. Converting the C code to Python first will give you the familiarity with Python you need to start on the port to Twisted.
Twisted Matrix and telnet server implementation
I have a project which is essentially a game server where users connect and send text commands via telnet. The code is in C and really old and unmodular and has several bugs and missing features. The main function alone is half the code. I came to the conclusion that rewriting it in Python, with Twisted, could actually result in faster completement, besides other benefits. So, here is the questions: What packages and modules I should use? I see a "telnet" module inside "protocols" package. I also see "cronch" package with "ssh" and another "telnet" module. I'm a complete novice regarding Python.
[ "Greg's suggestion to try to become familiar with Python before trying to take on Twisted is perhaps a reasonable one. Limiting the possible sources of your confusion may help you avoid some very frustrating cases.\nOn the other hand, I know a lot of people who take on a Twisted-based project as a first Python learning experience, and succeed. So it's possible. And you'll have to do something first. There's no guarantee that what you pick instead of Twisted will be easier. :)\nAs far as the specifics of telnet go, you want to use twisted.conch.telnet, not twisted.protocols.telnet. The former is newer, better tested, more featureful, and has several examples (although unfortunately not a lot of documentation beyond that).\nThe main telnet example shows you the most useful event handlers you can define if you use twisted.conch.telnet. Unfortunately it doesn't really explain what they do, nor does it give a demonstration of how you might negotiation options. If you're already familiar with the telnet protocol itself (primarily the option negotiation part of it), this should make sense to you. If you're thinking of \"telnet\" as just a way to pass human readable/writeable bytes between two computers, then you probably haven't run across option negotiation before and it might not make much sense. You can either ignore it, or check out the telnet RFC to learn more (it's a little dense, though).\nFor performing option negotiations yourself, you can at least take a look at the API documentation for the self.transport object you see in the above linked example (this isn't a regular TCP transport as you'll find used throughout much of Twisted, but a special telnet-derived transport which sits on top of TCP, so it has a few extra features).\nIf you just want to pass bytes around, though, then you can focus on the dataReceived method and on self.transport.write. The former will be called when you receive bytes from your peer; the latter you can call to send bytes to your peer.\n", "It sounds like you've got two separate tasks here:\n\nPort the code from C to Python.\nRewrite the whole program to use Twisted.\n\nSince you're new to Python, I would be inclined to do the first one first, before trying to make the program structure work in Twisted. If the program is old, there isn't likely to be any performance problems running it on modern hardware.\nConverting the C code to Python first will give you the familiarity with Python you need to start on the port to Twisted.\n" ]
[ 5, 1 ]
[]
[]
[ "python", "telnet", "twisted" ]
stackoverflow_0002864663_python_telnet_twisted.txt
Q: Writing white space to CSV fields in Python? When I try to write a field that includes whitespace in it, it gets split into multiple fields on the space. What's causing this? It's driving me insane. Thanks data = open("file.csv", "wb") w = csv.writer(data) w.writerow(['word1', 'word2']) w.writerow(['word 1', 'word2']) data.close() I'll get 2 fields(word1,word2) for first example and 3(word,1,word2) for the second. A: The writing is correct, I think; the problem would be in reading. You never said what you're using to open such generated CSV. It might be splitting fields on comma or whitespace. UPDATE: Try this, see if it helps: w = csv.writer(data, quoting=csv.QUOTE_ALL) A: Not reproducible here: >>> import csv >>> data = open("file.csv", "wb") >>> w = csv.writer(data) >>> w.writerow(['word1', 'word2']) >>> w.writerow(['word 1', 'word2']) >>> data.close() >>> [1]+ Stopped python2.6 $ cat file.csv word1,word2 word 1,word2 $ What do you see when you do exactly this (or the window equivalent, control-Z to exit the interpreter where I did it to supend the intepreter and get a shell prompt)? What exact environment and version of Python? A: For me on Python 2.7, that gives: word1,word2 word 1,word2 as expected.
Writing white space to CSV fields in Python?
When I try to write a field that includes whitespace in it, it gets split into multiple fields on the space. What's causing this? It's driving me insane. Thanks data = open("file.csv", "wb") w = csv.writer(data) w.writerow(['word1', 'word2']) w.writerow(['word 1', 'word2']) data.close() I'll get 2 fields(word1,word2) for first example and 3(word,1,word2) for the second.
[ "The writing is correct, I think; the problem would be in reading. You never said what you're using to open such generated CSV. It might be splitting fields on comma or whitespace.\nUPDATE: Try this, see if it helps:\nw = csv.writer(data, quoting=csv.QUOTE_ALL)\n\n", "Not reproducible here:\n>>> import csv\n>>> data = open(\"file.csv\", \"wb\")\n>>> w = csv.writer(data)\n>>> w.writerow(['word1', 'word2'])\n>>> w.writerow(['word 1', 'word2'])\n>>> data.close()\n>>> \n[1]+ Stopped python2.6\n$ cat file.csv\nword1,word2\nword 1,word2\n$\n\nWhat do you see when you do exactly this (or the window equivalent, control-Z to exit the interpreter where I did it to supend the intepreter and get a shell prompt)? What exact environment and version of Python?\n", "For me on Python 2.7, that gives:\nword1,word2\nword 1,word2\n\nas expected.\n" ]
[ 4, 3, 1 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0002870976_csv_python.txt
Q: Python and database I am working on a personal project where I need to manipulate values in a database-like format. Up until now I have been using dictionaries, tuples, and lists to store and consult those values. I am thinking about starting to use SQL to manipulate those values, but I don't know if it's worth the effort, because I don't know anything about SQL, and I don't want to use something that won't bring me any benefits (if I can do it in a simpler way, I don't want to complicate things) If I am only storing and consulting values, what would be the benefit of using SQL? PS: the numbers of rows goes between 3 and 100 and the number of columns is around 10 (some may have 5 some may have 10 etc.) A: SQL is nice and practical for many kinds of problems, is not that hard to learn at a simple "surface" level, and can be very handy to use in Python with its embedded sqlite. But if you don't know SQL, have no intrinsic motivation to learn it right now, and are already doing all you need to do to/with your data without problems, then the immediate return on the investment of learning SQL (relatively small as that investment may be) seem like it would be pretty meager indeed for you. A: No, I think you just stick to dictionaries or tuples if you only have rows around 100 A: SQL is useful in many applications. But it is an overkill in this case. You can easily store your data in CSV, pickle or JSON format. Get this job done in 5 minutes and then learn SQL when you have time.
Python and database
I am working on a personal project where I need to manipulate values in a database-like format. Up until now I have been using dictionaries, tuples, and lists to store and consult those values. I am thinking about starting to use SQL to manipulate those values, but I don't know if it's worth the effort, because I don't know anything about SQL, and I don't want to use something that won't bring me any benefits (if I can do it in a simpler way, I don't want to complicate things) If I am only storing and consulting values, what would be the benefit of using SQL? PS: the numbers of rows goes between 3 and 100 and the number of columns is around 10 (some may have 5 some may have 10 etc.)
[ "SQL is nice and practical for many kinds of problems, is not that hard to learn at a simple \"surface\" level, and can be very handy to use in Python with its embedded sqlite. But if you don't know SQL, have no intrinsic motivation to learn it right now, and are already doing all you need to do to/with your data without problems, then the immediate return on the investment of learning SQL (relatively small as that investment may be) seem like it would be pretty meager indeed for you.\n", "No, I think you just stick to dictionaries or tuples if you only have rows around 100\n", "SQL is useful in many applications. But it is an overkill in this case. You can easily store your data in CSV, pickle or JSON format. Get this job done in 5 minutes and then learn SQL when you have time.\n" ]
[ 7, 2, 2 ]
[]
[]
[ "database", "python", "sql" ]
stackoverflow_0002870815_database_python_sql.txt
Q: Python readability hints for a Java programmer I'm a java programmer, but now entering the "realm of python" for some stuff for which Python works better. I'm quite sure a good portion of my code would look weird for a Python programmer (e.g. using parenthesis on every if). I know each language has its own conventions and set of "habits". So, from a readability standpoint what are conventions and practices which is "the way to go" in Java, but are not really the "pythonic way" to do stuff? A: There's no simple answer to that question. It takes time for your code to be "Pythonic". Don't try and recreate Java idioms in Python. It will just take time to learn Python idioms. Take a look at Code Like a Pythonista: Idiomatic Python, Style Guide for Python Code and Python for Java Programmers (archived). A: Jacob Hallén once observed that the best Python style follows Tufte's rejection of decoration (though Tufte's field is not programming languages, but visual display of information): don't waste "ink" (pixels) or "paper" (space) for mere decoration. A lot follows from this principle: no redundant parentheses, no semicolons, no silly "ascii boxes" in comments and docstrings, no wasted space to "align" things on different rows, single quotes unless you specifically need double quotes, no \ to continue lines except when mandatory, no comments that merely remind the reader of the language's rules (if the reader does not know the language you're in trouble anyway;-), and so forth. I should point out that some of these consequences of the "Tufte spirit of Python" are more controversial than others, within the Python community. But the language sure respects "Tufte's Spirit" pretty well... Moving to "more controversial" (but sanctioned by the Zen of Python -- import this at an interpreter prompt): "flat is better than nested", so "get out as soon as sensible" rather than nesting. Let me explain: if foo: return bar else: baz = fie(fum) return baz + blab this isn't terrible, but neither is it optimal: since "return" ``gets out'', you can save the nesting: if foo: return bar baz = fie(fum) return baz + blab A sharper example: for item in container: if interesting(item): dothis(item) dothat(item) theother(item) that large block being double-nested is not neat... consider the flatter style: for item in container: if not interesting(item): continue dothis(item) dothat(item) theother(item) BTW, and an aside that's not specifically of Python-exclusive style -- one of my pet peeves (in any language, but in Python Tufte's Spirit supports me;-): if not something: this() that() theother() else: blih() bluh() blah() "if not ... else" is contorted! Swap the two halves and lose the not: if something: blih() bluh() blah() else: this() that() theother() A: The best place to start is probably PEP-8, which is the official Python style guide. It covers a lot of the basics for what is considered standard. A: In addition, some previous stackoverflow questions: What are the important language features idioms of python to learn early on? What does pythonic mean? What defines “pythonian” or “pythonic”? Python: Am I missing something? Zen of python A: "Everything is a class" is a Java idiom that's specifically not a Python idiom. (Almost) everything can be a class in Python, and if that's more comfortable for you then go for it, but Python doesn't require such a thing. Python is not a purely object-oriented language, and in my (limited) experience it's good to take that to heart. A: Syntax is only the tip of an iceberg. There are a number of different language construct that Java programmers should be aware of, e.g. Python do not need to use interface Creating an interface and swappable implementations in python - Stack Overflow The other really useful idiom is everything can be convert to a boolean value with an intuitive meaning in Python. For example, to check for an empty array, you simply do if not my_array: return ...process my_array... The first condition is equivalent to Java's if ((my_array == null) || (my_array.length == 0)) { return } This is a godsend in Python. Not only is it more concise, it also avoid a Java pitfall where many people do not check for both conditions consistently. Countless NullPointerException are averted as a result.
Python readability hints for a Java programmer
I'm a java programmer, but now entering the "realm of python" for some stuff for which Python works better. I'm quite sure a good portion of my code would look weird for a Python programmer (e.g. using parenthesis on every if). I know each language has its own conventions and set of "habits". So, from a readability standpoint what are conventions and practices which is "the way to go" in Java, but are not really the "pythonic way" to do stuff?
[ "There's no simple answer to that question. It takes time for your code to be \"Pythonic\". Don't try and recreate Java idioms in Python. It will just take time to learn Python idioms.\nTake a look at Code Like a Pythonista: Idiomatic Python, Style Guide for Python Code and Python for Java Programmers (archived).\n", "Jacob Hallén once observed that the best Python style follows Tufte's rejection of decoration (though Tufte's field is not programming languages, but visual display of information): don't waste \"ink\" (pixels) or \"paper\" (space) for mere decoration.\nA lot follows from this principle: no redundant parentheses, no semicolons, no silly \"ascii boxes\" in comments and docstrings, no wasted space to \"align\" things on different rows, single quotes unless you specifically need double quotes, no \\ to continue lines except when mandatory, no comments that merely remind the reader of the language's rules (if the reader does not know the language you're in trouble anyway;-), and so forth.\nI should point out that some of these consequences of the \"Tufte spirit of Python\" are more controversial than others, within the Python community. But the language sure respects \"Tufte's Spirit\" pretty well...\nMoving to \"more controversial\" (but sanctioned by the Zen of Python -- import this at an interpreter prompt): \"flat is better than nested\", so \"get out as soon as sensible\" rather than nesting. Let me explain:\nif foo:\n return bar\nelse:\n baz = fie(fum)\n return baz + blab\n\nthis isn't terrible, but neither is it optimal: since \"return\" ``gets out'', you can save the nesting:\nif foo:\n return bar\nbaz = fie(fum)\nreturn baz + blab\n\nA sharper example:\nfor item in container:\n if interesting(item):\n dothis(item)\n dothat(item)\n theother(item)\n\nthat large block being double-nested is not neat... consider the flatter style:\nfor item in container:\n if not interesting(item):\n continue\n dothis(item)\n dothat(item)\n theother(item)\n\nBTW, and an aside that's not specifically of Python-exclusive style -- one of my pet peeves (in any language, but in Python Tufte's Spirit supports me;-):\nif not something:\n this()\n that()\n theother()\nelse:\n blih()\n bluh()\n blah()\n\n\"if not ... else\" is contorted! Swap the two halves and lose the not:\nif something:\n blih()\n bluh()\n blah()\nelse:\n this()\n that()\n theother()\n\n", "The best place to start is probably PEP-8, which is the official Python style guide. It covers a lot of the basics for what is considered standard.\n", "In addition, some previous stackoverflow questions:\n\nWhat are the important language features idioms of python to learn early on?\nWhat does pythonic mean?\nWhat defines “pythonian” or “pythonic”?\nPython: Am I missing something?\nZen of python\n\n", "\"Everything is a class\" is a Java idiom that's specifically not a Python idiom. (Almost) everything can be a class in Python, and if that's more comfortable for you then go for it, but Python doesn't require such a thing. Python is not a purely object-oriented language, and in my (limited) experience it's good to take that to heart.\n", "Syntax is only the tip of an iceberg. There are a number of different language construct that Java programmers should be aware of, e.g. Python do not need to use interface\nCreating an interface and swappable implementations in python - Stack Overflow\nThe other really useful idiom is everything can be convert to a boolean value with an intuitive meaning in Python. For example, to check for an empty array, you simply do\nif not my_array:\n return\n...process my_array...\n\nThe first condition is equivalent to Java's\nif ((my_array == null) || (my_array.length == 0)) {\n return\n}\n\nThis is a godsend in Python. Not only is it more concise, it also avoid a Java pitfall where many people do not check for both conditions consistently. Countless NullPointerException are averted as a result.\n" ]
[ 8, 5, 3, 1, 0, 0 ]
[]
[]
[ "conventions", "java", "python", "readability" ]
stackoverflow_0002870292_conventions_java_python_readability.txt
Q: add gtk.widget in a gnome Applet I have a question : I write a little gnome applet, and when we click on a button i want to add a gtk.widget under the "gnome-panel" like the calendar of the clock-applet. But I don't know how to do this. It's my code : listButton = gtk.Button(_("lastest")) self.listTwitt = gtk.TreeView() mainLayout = gtk.VBox() mainLayout.pack_start(listButton) mainLayout.pack_start(self.listTwitt) self.applet.add(mainLayout) With this code, when i click on the button, the list shows up in the gnome panel : it's because I add it in the mainLayout. So how do I add it under the "gnome-panel". Thanks A: You have to create a gtk.Window, position it under the applet, and add it in there.
add gtk.widget in a gnome Applet
I have a question : I write a little gnome applet, and when we click on a button i want to add a gtk.widget under the "gnome-panel" like the calendar of the clock-applet. But I don't know how to do this. It's my code : listButton = gtk.Button(_("lastest")) self.listTwitt = gtk.TreeView() mainLayout = gtk.VBox() mainLayout.pack_start(listButton) mainLayout.pack_start(self.listTwitt) self.applet.add(mainLayout) With this code, when i click on the button, the list shows up in the gnome panel : it's because I add it in the mainLayout. So how do I add it under the "gnome-panel". Thanks
[ "You have to create a gtk.Window, position it under the applet, and add it in there.\n" ]
[ 0 ]
[]
[]
[ "applet", "gnome", "gtk", "python" ]
stackoverflow_0002868912_applet_gnome_gtk_python.txt
Q: Can I move beaker.SessionMiddleware to handle method somehow? It's a bit ugly that many lines of code fall into "__main__". Can someone give me a tip of how to move SessionMiddleware into handle method? I should notice that I use session in CoreXmlParser. Thanks in advance ! def handle(environ, start_response): req = webob.Request(environ) c = CoreXmlParser(req) resp = webob.Response(body=c(), charset = 'utf-8', status='200 OK', \ request=req, content_type='text/xml') resp(environ, start_response) return resp.app_iter if __name__ == '__main__': #parse config file for session options app = SessionMiddleware(handle, some_session_opts_here) from flup.server.fcgi import WSGIServer WSGIServer(app).run() A: I'm not sure I understand why you're trying to move just one line. If you want to reduce the amount of stuff in "__main__", why not just move all that "#parse config file" stuff into a separate function? def handle(environ, start_response): # same as before def create_app(config_file): #parse config file for session options return SessionMiddleWare(handle, some_session_opts_here) if __name__ == '__main__': app = create_app(config_file) from flup.server.fcgi import WSGIServer WSGIServer(app).run()
Can I move beaker.SessionMiddleware to handle method somehow?
It's a bit ugly that many lines of code fall into "__main__". Can someone give me a tip of how to move SessionMiddleware into handle method? I should notice that I use session in CoreXmlParser. Thanks in advance ! def handle(environ, start_response): req = webob.Request(environ) c = CoreXmlParser(req) resp = webob.Response(body=c(), charset = 'utf-8', status='200 OK', \ request=req, content_type='text/xml') resp(environ, start_response) return resp.app_iter if __name__ == '__main__': #parse config file for session options app = SessionMiddleware(handle, some_session_opts_here) from flup.server.fcgi import WSGIServer WSGIServer(app).run()
[ "I'm not sure I understand why you're trying to move just one line. If you want to reduce the amount of stuff in \"__main__\", why not just move all that \"#parse config file\" stuff into a separate function?\ndef handle(environ, start_response):\n # same as before\n\ndef create_app(config_file):\n #parse config file for session options\n return SessionMiddleWare(handle, some_session_opts_here)\n\nif __name__ == '__main__':\n app = create_app(config_file)\n from flup.server.fcgi import WSGIServer\n WSGIServer(app).run()\n\n" ]
[ 0 ]
[]
[]
[ "beaker", "fastcgi", "python" ]
stackoverflow_0002871424_beaker_fastcgi_python.txt
Q: How to send a EML file as email using python script to list of emails one at a time? I want to write a simple python script that send a EML file exported from Outlook though given smtp server as email to a given list of emails. I know how to send a simple email but sending a EML file as email is not something i could do and could not find it on Google. Can anyone help me with that. The EML file is actually in HTML format with embedded images. Any alternate suggestion is also welcome. A: Building on the email module example, try using a MIME attachment with HTML content. If the EML format is just HTML, this should work. The example shows how to construct a message with (html) attachments: # Create the body of the message (a plain-text and an HTML version). text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org" html = """\ <html> <head></head> <body> <p>Hi!<br> How are you?<br> Here is the <a href="http://www.python.org">link</a> you wanted. </p> </body> </html> """ # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. msg.attach(part1) msg.attach(part2) #...
How to send a EML file as email using python script to list of emails one at a time?
I want to write a simple python script that send a EML file exported from Outlook though given smtp server as email to a given list of emails. I know how to send a simple email but sending a EML file as email is not something i could do and could not find it on Google. Can anyone help me with that. The EML file is actually in HTML format with embedded images. Any alternate suggestion is also welcome.
[ "Building on the email module example, try using a MIME attachment with HTML content.\nIf the EML format is just HTML, this should work.\nThe example shows how to construct a message with (html) attachments:\n# Create the body of the message (a plain-text and an HTML version).\ntext = \"Hi!\\nHow are you?\\nHere is the link you wanted:\\nhttp://www.python.org\"\nhtml = \"\"\"\\\n<html>\n <head></head>\n <body>\n <p>Hi!<br>\n How are you?<br>\n Here is the <a href=\"http://www.python.org\">link</a> you wanted.\n </p>\n </body>\n</html>\n\"\"\"\n\n# Record the MIME types of both parts - text/plain and text/html.\npart1 = MIMEText(text, 'plain')\npart2 = MIMEText(html, 'html')\n\n# Attach parts into message container.\n# According to RFC 2046, the last part of a multipart message, in this case\n# the HTML message, is best and preferred.\nmsg.attach(part1)\nmsg.attach(part2)\n#...\n\n" ]
[ 3 ]
[]
[]
[ "email", "linux", "python" ]
stackoverflow_0002871440_email_linux_python.txt
Q: Snow Leopard Python 2.6 problems getting PIL to work I installed libjpeg and PIL, but when I try to save a JPG image, I always get this error: ImportError: The _imaging C module is not installed Any help much appreciated! I tried to import _imaging w/ Python interpreter to see what's wrong and got this: >>> import _imaging Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PIL/_imaging.so, 2): Symbol not found: _jpeg_resync_to_restart Referenced from: /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PIL/_imaging.so Expected in: dynamic lookup A: I just hit this as well on SL, and the problem is likely your libjpeg was built without a matching architecture. Assuming you're using MacPorts, run file /opt/local/lib/libjpeg.dylib. The right way is to build everything with MacPorts as +universal, see Universal Binaries in MacPorts as it relates to PIL dependencies. A: A lot of these errors happen when compiling from source when you've previously installed python tools from fink or ports. For example the _jpeg_resync_to_restart error can happen when you've got leftover libjpeg files in /opt/local/lib. Try this: cd /opt/local/lib sudo rm *jpeg* Then recompile libjpeg (starting with make clean), then recompile PIL (starting with rm -Rf build). After that, import _imaging should work. Did for me anyway. A: Edit: Thanks for the added error message. This is apparently a problem with the jpeglib on Snow Leopard. Have you tried this? http://jetfar.com/libjpeg-and-python-imaging-pil-on-snow-leopard/ A: I kept having this problem as well. It turned out to be related to a change I made to my .bash_profile (forcing the usage of ggc-4.0) when trying to fix a MySQLdb installation problem. http://www.brambraakman.com/blog/comments/installing_pil_in_snow_leopard_jpeg_resync_to_restart_error/
Snow Leopard Python 2.6 problems getting PIL to work
I installed libjpeg and PIL, but when I try to save a JPG image, I always get this error: ImportError: The _imaging C module is not installed Any help much appreciated! I tried to import _imaging w/ Python interpreter to see what's wrong and got this: >>> import _imaging Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PIL/_imaging.so, 2): Symbol not found: _jpeg_resync_to_restart Referenced from: /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PIL/_imaging.so Expected in: dynamic lookup
[ "I just hit this as well on SL, and the problem is likely your libjpeg was built without a matching architecture. Assuming you're using MacPorts, run file /opt/local/lib/libjpeg.dylib. The right way is to build everything with MacPorts as +universal, see \nUniversal Binaries in MacPorts as it relates to PIL dependencies.\n", "A lot of these errors happen when compiling from source when you've previously installed python tools from fink or ports. For example the _jpeg_resync_to_restart error can happen when you've got leftover libjpeg files in /opt/local/lib. Try this:\ncd /opt/local/lib\nsudo rm *jpeg*\n\nThen recompile libjpeg (starting with make clean), then recompile PIL (starting with rm -Rf build).\nAfter that, import _imaging should work. Did for me anyway.\n", "Edit: Thanks for the added error message. This is apparently a problem with the jpeglib on Snow Leopard. Have you tried this?\nhttp://jetfar.com/libjpeg-and-python-imaging-pil-on-snow-leopard/\n", "I kept having this problem as well. It turned out to be related to a change I made to my .bash_profile (forcing the usage of ggc-4.0) when trying to fix a MySQLdb installation problem.\nhttp://www.brambraakman.com/blog/comments/installing_pil_in_snow_leopard_jpeg_resync_to_restart_error/\n" ]
[ 4, 4, 2, 1 ]
[]
[]
[ "image_manipulation", "osx_snow_leopard", "pylons", "python", "python_imaging_library" ]
stackoverflow_0001518573_image_manipulation_osx_snow_leopard_pylons_python_python_imaging_library.txt
Q: python simple json problem with a unicode string url "link": "http:\/\/www.mydomain.com"? i have a dictionary when i pass it over simplejson.dumps(dict) the json output has put some sort of encoding on a string url? "link": "http:\/\/www.mydomain.com" How can i stop this? Im using app engine simplejson. A: I don't see a problem with this. This encoding for the forward slash is perfectly valid. If the other side can't decode this then it's their JSON library that is broken.
python simple json problem with a unicode string url "link": "http:\/\/www.mydomain.com"?
i have a dictionary when i pass it over simplejson.dumps(dict) the json output has put some sort of encoding on a string url? "link": "http:\/\/www.mydomain.com" How can i stop this? Im using app engine simplejson.
[ "I don't see a problem with this. This encoding for the forward slash is perfectly valid. If the other side can't decode this then it's their JSON library that is broken.\n" ]
[ 2 ]
[]
[]
[ "python", "simplejson" ]
stackoverflow_0002871912_python_simplejson.txt
Q: Combining entries, filtering of Python dictionaries I have two large lists that are filled with dictionaries. I need to combine the entries if a value from dict2==dict1 and place the newly combined matches somewhere else. I'm having trouble explaining it. List one contains: {'keyword':value, 'keyword2':value2} List two: {'keyword2':value2, 'keyword3':value3} I want a new list with dictionaries including keyword1, keyword2, and keyword3 if both lists share the same 'keyword2' value. What's the best way to do this? When I try, I only come up with tons of nested for loops. Thanks A: If you don't care about "conflicts", i.e. that the same key is mapped to different values in two dicts, you can use the update method of dicts: >>> d1 = {'keyword': 1, 'keyword2': 2} >>> d2 = {'keyword2': 2, 'keyword3': 3} >>> d = {} >>> d.update(d1) >>> d {'keyword2': 2, 'keyword': 1} >>> d.update(d2) >>> d {'keyword3': 7, 'keyword2': 2, 'keyword': 1} Assuming your dicts are stored in a large list named dict_list: total = {} for d in dict_list: total.update(d) A: Loop over one dictionary, comparing individual elements to the other dictionary. Like this, where dict1 and dict2 are the originals, and dict3 is the result: dict3 = dict1 for k in dict2: if k in dict1: # The key is in both dictionaries; we've already added dict1's version if dict1[k] != dict2[k]: pass # The dictionaries have different values; handle this as you like else # The key is only in dict2; add it to dict3 dict3[k] = dict2[k] You weren't clear on what behavior you wanted if the two dictionaries have different values for some key; replace the "pass" with whatever you want to do. (As written, it will keep the value from dict1. If you don't want to include either value, replace the pass with del dict3[k].)
Combining entries, filtering of Python dictionaries
I have two large lists that are filled with dictionaries. I need to combine the entries if a value from dict2==dict1 and place the newly combined matches somewhere else. I'm having trouble explaining it. List one contains: {'keyword':value, 'keyword2':value2} List two: {'keyword2':value2, 'keyword3':value3} I want a new list with dictionaries including keyword1, keyword2, and keyword3 if both lists share the same 'keyword2' value. What's the best way to do this? When I try, I only come up with tons of nested for loops. Thanks
[ "If you don't care about \"conflicts\", i.e. that the same key is mapped to different values in two dicts, you can use the update method of dicts:\n>>> d1 = {'keyword': 1, 'keyword2': 2}\n>>> d2 = {'keyword2': 2, 'keyword3': 3}\n>>> d = {}\n>>> d.update(d1)\n>>> d\n{'keyword2': 2, 'keyword': 1}\n>>> d.update(d2)\n>>> d\n{'keyword3': 7, 'keyword2': 2, 'keyword': 1}\n\nAssuming your dicts are stored in a large list named dict_list:\ntotal = {}\nfor d in dict_list:\n total.update(d)\n\n", "Loop over one dictionary, comparing individual elements to the other dictionary. Like this, where dict1 and dict2 are the originals, and dict3 is the result:\ndict3 = dict1\nfor k in dict2:\n if k in dict1:\n # The key is in both dictionaries; we've already added dict1's version\n if dict1[k] != dict2[k]:\n pass # The dictionaries have different values; handle this as you like\n else\n # The key is only in dict2; add it to dict3\n dict3[k] = dict2[k]\n\nYou weren't clear on what behavior you wanted if the two dictionaries have different values for some key; replace the \"pass\" with whatever you want to do. (As written, it will keep the value from dict1. If you don't want to include either value, replace the pass with del dict3[k].)\n" ]
[ 2, 0 ]
[]
[]
[ "dictionary", "list", "python", "sorting" ]
stackoverflow_0002871836_dictionary_list_python_sorting.txt
Q: How to retrieve value from etc/sysconfig in Python I have a config file FOO in /etc/sysconfig/. This Linux file is very similar to INI-File, but without a section declaration. In order to retrieve a value from this file, I used to write a shell script like: source /etc/sysconfig/FOO echo $MY_VALUE Now I want to do the same thing in python. I tried to use ConfigParser, but ConfigParser does not accept such an INI-File similar format, unless it has a section declaration. Is there any way to retrieve value from such a file? A: I suppose you could do exactly what you're doing with your shell script using the subprocess module and reading it's output. Use it with the shell option set to True. A: If you want to use ConfigParser, you could do something like: #! /usr/bin/env python2.6 from StringIO import StringIO import ConfigParser def read_configfile_without_sectiondeclaration(filename): buffer = StringIO() buffer.write("[main]\n") buffer.write(open(filename).read()) buffer.seek(0) config = ConfigParser.ConfigParser() config.readfp(buffer) return config if __name__ == "__main__": import sys config = read_configfile_without_sectiondeclaration(sys.argv[1]) print config.items("main") The code creates an in-memory filelike object containing a [main] section header and the contents of the specified file. ConfigParser then reads that filelike object.
How to retrieve value from etc/sysconfig in Python
I have a config file FOO in /etc/sysconfig/. This Linux file is very similar to INI-File, but without a section declaration. In order to retrieve a value from this file, I used to write a shell script like: source /etc/sysconfig/FOO echo $MY_VALUE Now I want to do the same thing in python. I tried to use ConfigParser, but ConfigParser does not accept such an INI-File similar format, unless it has a section declaration. Is there any way to retrieve value from such a file?
[ "I suppose you could do exactly what you're doing with your shell script using the subprocess module and reading it's output. Use it with the shell option set to True.\n", "If you want to use ConfigParser, you could do something like:\n#! /usr/bin/env python2.6\n\nfrom StringIO import StringIO\nimport ConfigParser\n\ndef read_configfile_without_sectiondeclaration(filename):\n buffer = StringIO()\n buffer.write(\"[main]\\n\")\n buffer.write(open(filename).read())\n buffer.seek(0)\n config = ConfigParser.ConfigParser()\n config.readfp(buffer)\n return config\n\nif __name__ == \"__main__\":\n import sys\n config = read_configfile_without_sectiondeclaration(sys.argv[1])\n print config.items(\"main\")\n\nThe code creates an in-memory filelike object containing a [main] section header and the contents of the specified file. ConfigParser then reads that filelike object.\n" ]
[ 1, 1 ]
[]
[]
[ "bash", "environment_variables", "ini", "linux", "python" ]
stackoverflow_0002871930_bash_environment_variables_ini_linux_python.txt
Q: spam and dirty words comment post filtering/prevention/blocking in python (django) My basic question is how to prevent spam and dirty words in a comment post system under python (django). I have a collection of phrases (approximately 3000 phrases) to be blocked. What I want to do is like this: If I found a comment which has a dirty-word when user clicks the post button, then the web should popup a warning message and asked people to re-enter/correct the comments and submit it again. This is just preventing people to submit rude/spam comments. Question (1), are there any existing open source python (or django) package/module/plugin which can handle this job? I knew there was one called Akismet. But from what I understood, it will not solve my problem. Akismet is just a web service and filter the words dictionary defined by Akismet. But I have my own collection of words. Please correct me if I am wrong. Question (2), If there is no such open source package I can use, how to create my own one? The only thing I can think of it's to use regular expression and join all the word phrases with 'or' in a regular expression. but I have 3000 phrases, I think it won't work in term of performance and filter every comment post. any suggestions where should I start from? Thank you very much for your help and time. A: You may want to check out the PROFANITIES_LIST setting, looks like you can use it with validators. Although, with that many (3000 really? you must be fun at parties) phrases you want to rethink things. You shouldn't filter SPAM. You should throw it away. Just my opinion. If the comment has SPAM in it, why keep it at all? Is there any value added from such a comment?
spam and dirty words comment post filtering/prevention/blocking in python (django)
My basic question is how to prevent spam and dirty words in a comment post system under python (django). I have a collection of phrases (approximately 3000 phrases) to be blocked. What I want to do is like this: If I found a comment which has a dirty-word when user clicks the post button, then the web should popup a warning message and asked people to re-enter/correct the comments and submit it again. This is just preventing people to submit rude/spam comments. Question (1), are there any existing open source python (or django) package/module/plugin which can handle this job? I knew there was one called Akismet. But from what I understood, it will not solve my problem. Akismet is just a web service and filter the words dictionary defined by Akismet. But I have my own collection of words. Please correct me if I am wrong. Question (2), If there is no such open source package I can use, how to create my own one? The only thing I can think of it's to use regular expression and join all the word phrases with 'or' in a regular expression. but I have 3000 phrases, I think it won't work in term of performance and filter every comment post. any suggestions where should I start from? Thank you very much for your help and time.
[ "You may want to check out the PROFANITIES_LIST setting, looks like you can use it with validators.\nAlthough, with that many (3000 really? you must be fun at parties) phrases you want to rethink things. You shouldn't filter SPAM. You should throw it away. Just my opinion. If the comment has SPAM in it, why keep it at all? Is there any value added from such a comment?\n" ]
[ 4 ]
[]
[]
[ "django", "filtering", "python", "spam_prevention" ]
stackoverflow_0002871978_django_filtering_python_spam_prevention.txt
Q: Efficient way in Python to remove an element from a comma-separated string I'm looking for the most efficient way to add an element to a comma-separated string while maintaining alphabetical order for the words: For example: string = 'Apples, Bananas, Grapes, Oranges' subtraction = 'Bananas' result = 'Apples, Grapes, Oranges' Also, a way to do this but while maintaining IDs: string = '1:Apples, 4:Bananas, 6:Grapes, 23:Oranges' subtraction = '4:Bananas' result = '1:Apples, 6:Grapes, 23:Oranges' Sample code is greatly appreciated. Thank you so much. A: Split on ', ', remove the element, and join. A: Matthew's comment above is the right approach but if you're sure that the , (comma followed by a space) occur only as separators, then something like this would work def remove(str, element): items = str.split(", ") items.remove(element) return ", ".join(items) I wouldn't recommend that you use strings as lists though. They're designed for a different purpose and following Matthew's advice is the right thing to do. A: Ideally, something like: input_str = '1:Apples, 4:Bananas, 6:Grapes, 23:Oranges' removal_str = '4:Bananas' sep = ", " print sep.join(input_str.split(sep).remove(removal_str)) would work. But python doesn't return the new list from remove(), so you can't do that all on one line, and need temporary variables etc. A similar solution that does work is: input_str = '1:Apples, 4:Bananas, 6:Grapes, 23:Oranges' removal_str = '4:Bananas' sep = ", " print sep.join([ i for i in input_str.split(sep) if i != removal_str ]) However, to be as correct as possible, assuming you've no GUARANTEE that all items are valid, you'd need to verify that each item matches ALL of the specifications given to you, namely that they're of the format number:identifier. The simplest way to do that is to use the re module to search for a specific regular expression format, return all results, and skip results that don't match what you want. Using deliberately compact code, you get a reasonably short solution that does good validation: def str_to_dictlist(inp_str): import re regexp = r"(?P<id>[0-9]+):(?P<name>[a-zA-Z0-9_]+)" return [ x.groups() for x in re.finditer(regexp, inp_str) ] input_str = '1:Apples, 4:Bananas, 6:Grapes, 23:Oranges' subtraction_str = "4:Bananas" sep = ", " input_items = str_to_dictlist(input_str) removal_items = str_to_dictlist(subtraction_str) final_items = [ "%s:%s" % (x,y) for x,y in input_items if (x,y) not in removal_items ] print sep.join(final_items) This also has the advantage of handling multiple removals at the same time. Since the input format and removal formats are so similar, and the input format has multiple items, it makes sense that the removal format might need to support them too -- or at least, that it's useful to have that support. Note that doing it this way (using re to search) would make it difficult to detect items that DON'T validate though; it would just scan for anything that does. As a hack, you could count commas in the input and report a warning that something might have failed to parse: if items_found < (num_commas + 1): print warning_str This would warn about commas without spaces as well. To parse more complex input strings properly, you need to break it down into individual tokens, track input lines and columns as you parse, print errors for anything unexpected, and maybe even handle stuff like backtracking and graph-building for more complex inputs like source code. For that sort of stuff, look into the pyparsing module (which is a third-party download; it doesn't come with python). A: >>> import re >>> re.sub("Bananas, |, Bananas$", "", "Apples, Bananas, Grapes, Oranges") 'Apples, Grapes, Oranges' or import re strng = '1:Apples, 4:Bananas, 6:Grapes, 23:Oranges' subtraction = '4:Bananas' result = re.sub(subtraction + ", |, " + subtraction, "", strng) print result This works on your examples, but would need to be modified if the subtraction strings might contain regular expression metacharacters like [].*?{}\. This is, as one commenter noted, a low-level string operation. It might just work, but an approach that takes the structure of your data into account should be more reliable. Whether splitting on a comma/space is enough, or whether you need the robustness of the csv module depends on the possible input strings you're expecting.
Efficient way in Python to remove an element from a comma-separated string
I'm looking for the most efficient way to add an element to a comma-separated string while maintaining alphabetical order for the words: For example: string = 'Apples, Bananas, Grapes, Oranges' subtraction = 'Bananas' result = 'Apples, Grapes, Oranges' Also, a way to do this but while maintaining IDs: string = '1:Apples, 4:Bananas, 6:Grapes, 23:Oranges' subtraction = '4:Bananas' result = '1:Apples, 6:Grapes, 23:Oranges' Sample code is greatly appreciated. Thank you so much.
[ "Split on ', ', remove the element, and join.\n", "Matthew's comment above is the right approach but if you're sure that the , (comma followed by a space) occur only as separators, then something like this would work\ndef remove(str, element):\n items = str.split(\", \")\n items.remove(element)\n return \", \".join(items)\n\nI wouldn't recommend that you use strings as lists though. They're designed for a different purpose and following Matthew's advice is the right thing to do. \n", "Ideally, something like:\ninput_str = '1:Apples, 4:Bananas, 6:Grapes, 23:Oranges'\nremoval_str = '4:Bananas'\nsep = \", \"\n\nprint sep.join(input_str.split(sep).remove(removal_str))\n\nwould work. But python doesn't return the new list from remove(), so you can't do that all on one line, and need temporary variables etc. A similar solution that does work is:\ninput_str = '1:Apples, 4:Bananas, 6:Grapes, 23:Oranges'\nremoval_str = '4:Bananas'\nsep = \", \"\n\nprint sep.join([ i for i in input_str.split(sep) if i != removal_str ])\n\nHowever, to be as correct as possible, assuming you've no GUARANTEE that all items are valid, you'd need to verify that each item matches ALL of the specifications given to you, namely that they're of the format number:identifier. The simplest way to do that is to use the re module to search for a specific regular expression format, return all results, and skip results that don't match what you want. Using deliberately compact code, you get a reasonably short solution that does good validation:\ndef str_to_dictlist(inp_str):\n import re\n regexp = r\"(?P<id>[0-9]+):(?P<name>[a-zA-Z0-9_]+)\"\n return [ x.groups() for x in re.finditer(regexp, inp_str) ]\n\ninput_str = '1:Apples, 4:Bananas, 6:Grapes, 23:Oranges'\nsubtraction_str = \"4:Bananas\"\nsep = \", \"\n\ninput_items = str_to_dictlist(input_str)\nremoval_items = str_to_dictlist(subtraction_str)\nfinal_items = [ \"%s:%s\" % (x,y) for x,y in input_items if (x,y) not in removal_items ]\n\nprint sep.join(final_items)\n\nThis also has the advantage of handling multiple removals at the same time. Since the input format and removal formats are so similar, and the input format has multiple items, it makes sense that the removal format might need to support them too -- or at least, that it's useful to have that support.\nNote that doing it this way (using re to search) would make it difficult to detect items that DON'T validate though; it would just scan for anything that does. As a hack, you could count commas in the input and report a warning that something might have failed to parse:\nif items_found < (num_commas + 1):\n print warning_str\n\nThis would warn about commas without spaces as well.\nTo parse more complex input strings properly, you need to break it down into individual tokens, track input lines and columns as you parse, print errors for anything unexpected, and maybe even handle stuff like backtracking and graph-building for more complex inputs like source code. For that sort of stuff, look into the pyparsing module (which is a third-party download; it doesn't come with python).\n", ">>> import re\n>>> re.sub(\"Bananas, |, Bananas$\", \"\", \"Apples, Bananas, Grapes, Oranges\")\n'Apples, Grapes, Oranges'\n\nor\nimport re\nstrng = '1:Apples, 4:Bananas, 6:Grapes, 23:Oranges'\nsubtraction = '4:Bananas'\nresult = re.sub(subtraction + \", |, \" + subtraction, \"\", strng)\nprint result\n\nThis works on your examples, but would need to be modified if the subtraction strings might contain regular expression metacharacters like [].*?{}\\.\nThis is, as one commenter noted, a low-level string operation. It might just work, but an approach that takes the structure of your data into account should be more reliable. Whether splitting on a comma/space is enough, or whether you need the robustness of the csv module depends on the possible input strings you're expecting.\n" ]
[ 5, 1, 1, 0 ]
[]
[]
[ "pylons", "python", "string" ]
stackoverflow_0002871915_pylons_python_string.txt
Q: Google app engin, python: Google, Facebook, Twitter, OpenID account Do anyone know if there are alternatives of Django-SocialAuth which support Google, Facebook, Twitter and OpenID account. I prefer webapp version instead of Django. Or if you have done once would you mind sharing it? Thanks in million. A: try checking out http://code.google.com/p/gaema/ from the gaema introduction, gaema is a library that provides various authentication systems for Google App Engine. It is basically the tornado.auth module extracted to work on App Engine and independently of any framework. It supports login using: OpenId OAuth Google Accounts Facebook FriendFeed Twitter You can use one, all or a mix of these auth methods. This is done with minimal overhead: gaema is small and doesn't have any dependencies, thanks to the awesome work done by the Tornado crew. gaema only authenticates an user, and doesn't provide persistence such as sessions or secure cookies to keep the user logged in. Because each framework do these things in a different way, it is up to the framework to implement these mechanisms. You can get gaema from http://pypi.python.org/pypi/gaema.
Google app engin, python: Google, Facebook, Twitter, OpenID account
Do anyone know if there are alternatives of Django-SocialAuth which support Google, Facebook, Twitter and OpenID account. I prefer webapp version instead of Django. Or if you have done once would you mind sharing it? Thanks in million.
[ "try checking out http://code.google.com/p/gaema/\nfrom the gaema introduction, \n\ngaema is a library that provides\n various authentication systems for\n Google App Engine. It is basically the\n tornado.auth module extracted to work\n on App Engine and independently of any\n framework.\nIt supports login using:\n\nOpenId \nOAuth \nGoogle Accounts \nFacebook\nFriendFeed Twitter\n\nYou can use one, all or a mix of these\n auth methods. This is done with\n minimal overhead: gaema is small and\n doesn't have any dependencies, thanks\n to the awesome work done by the\n Tornado crew.\ngaema only authenticates an user, and\n doesn't provide persistence such as\n sessions or secure cookies to keep the\n user logged in. Because each framework\n do these things in a different way, it\n is up to the framework to implement\n these mechanisms.\nYou can get gaema from\n http://pypi.python.org/pypi/gaema.\n\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002871689_google_app_engine_python.txt
Q: Why are python extensions shared libraries? Is it possible to make a static-linked library? I'm an extension noob. What I want to do is create an extension that doesn't require other libraries to be installed. Is this impossible because the extension has to link against a specific version of libpython at runtime? A: You can't make a statically linked extension module because Python needs to load it dynamically at runtime and because (as you reasoned) the module needs to dynamically link against libpython. You could compile your own custom version of Python with your extension statically linked into the interpreter. That's usually more trouble than it's worth. Why do you want to make a statically linked extension? If we have more information about your goals, we might be able to help you achieve them in a different way. Welcome to StackOverflow. :-) A: I think you're mixing things. You don't want the extension to be statically linked in the interpreter (which is possible but cumbersome since it involves rebuilding a custom interpreter), you want your extension not to be linked against pythonxx.dll, or to be linked statically to it. This is not possible; your extension and the python interpreter would have each their own copies of global variables for instance, which is Bad. There is another approach, which is to determine what Python versions are available at runtime and using dynamically the Python/C API by loading the Python DLL through LoadLibrary (Windows) or dlopen (Linux/etc), then deciding at runtime on the methods signatures depending on the version, etc. Very cumbersome. For an example of this kind of manipulation in Delphi, see PythonForDelphi: http://www.atug.com/andypatterns/pythonDelphiTalk.htm I'm not aware of any other project who would do that.
Why are python extensions shared libraries? Is it possible to make a static-linked library?
I'm an extension noob. What I want to do is create an extension that doesn't require other libraries to be installed. Is this impossible because the extension has to link against a specific version of libpython at runtime?
[ "You can't make a statically linked extension module because Python needs to load it dynamically at runtime and because (as you reasoned) the module needs to dynamically link against libpython.\nYou could compile your own custom version of Python with your extension statically linked into the interpreter. That's usually more trouble than it's worth.\nWhy do you want to make a statically linked extension? If we have more information about your goals, we might be able to help you achieve them in a different way.\nWelcome to StackOverflow. :-)\n", "I think you're mixing things. You don't want the extension to be statically linked in the interpreter (which is possible but cumbersome since it involves rebuilding a custom interpreter), you want your extension not to be linked against pythonxx.dll, or to be linked statically to it. This is not possible; your extension and the python interpreter would have each their own copies of global variables for instance, which is Bad.\nThere is another approach, which is to determine what Python versions are available at runtime and using dynamically the Python/C API by loading the Python DLL through LoadLibrary (Windows) or dlopen (Linux/etc), then deciding at runtime on the methods signatures depending on the version, etc. Very cumbersome. For an example of this kind of manipulation in Delphi, see PythonForDelphi:\nhttp://www.atug.com/andypatterns/pythonDelphiTalk.htm\nI'm not aware of any other project who would do that.\n" ]
[ 6, 3 ]
[]
[]
[ "c", "python" ]
stackoverflow_0002865679_c_python.txt
Q: Where can I find documentation on assembler? I wrote a very short program that parses a "program" using python and converts it to assembler, allowing me to compile my little proramming language to an executable. You can read my blog for more information here http://spiceycurry.blogspot.com/2010/05/simple-compilable-programming-language.html my question is... Where can I find more kernel commands so that I can further expand on my script in the above blog? A: I'd rather recomment using LLVM: It allows you not to bother with low-level details like register allocations (you provide only SSA form) It does optimizations for you. It can be faster then the hand-written and well-optimized compiler as the LLVM pipeline in GHC is showing (at the beginning - before much optimalization it had equal or better performance than mature native code generator). It is cross-platform - you don't tight yourself to for example x86 I'n not quite sure what you mean by 'kernel' commands. If you mean opcodes: There are Intel manuals There is Wikipedia page containing all of the documented memnonics (however not the opcodes and not always description) There is NASM manual However the ARM or PowerPC have totally different opcodes. If you mean the operating systen syscalls (system calls) then: You can just use C library. It is in every operating system and is cross platform. You can use directly syscalls. However they are harder to use, may be slower (libc may use additional buffering) and are not cross platform (Linux syscalls on x86 - may be not up-to-date).
Where can I find documentation on assembler?
I wrote a very short program that parses a "program" using python and converts it to assembler, allowing me to compile my little proramming language to an executable. You can read my blog for more information here http://spiceycurry.blogspot.com/2010/05/simple-compilable-programming-language.html my question is... Where can I find more kernel commands so that I can further expand on my script in the above blog?
[ "I'd rather recomment using LLVM:\n\nIt allows you not to bother with low-level details like register allocations (you provide only SSA form)\nIt does optimizations for you. It can be faster then the hand-written and well-optimized compiler as the LLVM pipeline in GHC is showing (at the beginning - before much optimalization it had equal or better performance than mature native code generator).\nIt is cross-platform - you don't tight yourself to for example x86\n\nI'n not quite sure what you mean by 'kernel' commands. If you mean opcodes:\n\nThere are Intel manuals\nThere is Wikipedia page containing all of the documented memnonics (however not the opcodes and not always description)\nThere is NASM manual\n\nHowever the ARM or PowerPC have totally different opcodes.\nIf you mean the operating systen syscalls (system calls) then:\n\nYou can just use C library. It is in every operating system and is cross platform.\nYou can use directly syscalls. However they are harder to use, may be slower (libc may use additional buffering) and are not cross platform (Linux syscalls on x86 - may be not up-to-date).\n\n" ]
[ 1 ]
[]
[]
[ "assembly", "compiler_construction", "gnu_assembler", "ld", "python" ]
stackoverflow_0002873431_assembly_compiler_construction_gnu_assembler_ld_python.txt
Q: How to execute machine language from memory? I wrote a program to compile a simple text program to a compiled executable... Is it possible that I can load an executable to memory an some how point a pc counter to the memory space at will? Here is what I made that I would like to store the programs to memory for execution on demand... Kind of wanting to make a little web language like php but compile it... Just for learning. http://spiceycurry.blogspot.com/2010/05/simple-compilable-programming-language.html A: Is it a executable file in memory(like ELF or something like that)? or just executable code in memory? If it is executable code in memory you could jmp there if the containing memory is executable and the execution will continue from there. If it is an executable file you need to actually read and interpret the format fields to load, link etc.. because an executable file contains static memory that needs to be initialized, dynamic libs that need to be linked, and an entry point that needs to be read from the file header. A: Build it into a shared library which are designed for dynamic loading. I sure there are a lot of headers that you need and a bunch of C style calling conventions you need to obey. I recommend you write the extension in C, try binding that, and when that works, grab all the linkage assembler from the C compiler code generation phase. A: In theory you can just load the code into memory at a certain address and issue a JMP to its entry point. If you are working in python, you will probably need to do that in an extension module written in C. Beware that this will be rather useless unless you settle on ways to get data into/out of your little code, and specify what functions (and how) of the parent program the code is allowed to access. This means defining an ABI and calling conventions. Also, I can't even begin to express how insecure this system will be unless you take rigorous precautions. The risks are increased manifold if you expose it to the public web.
How to execute machine language from memory?
I wrote a program to compile a simple text program to a compiled executable... Is it possible that I can load an executable to memory an some how point a pc counter to the memory space at will? Here is what I made that I would like to store the programs to memory for execution on demand... Kind of wanting to make a little web language like php but compile it... Just for learning. http://spiceycurry.blogspot.com/2010/05/simple-compilable-programming-language.html
[ "Is it a executable file in memory(like ELF or something like that)? or just executable code in memory?\nIf it is executable code in memory you could jmp there if the containing memory is executable and the execution will continue from there.\nIf it is an executable file you need to actually read and interpret the format fields to load, link etc.. because an executable file contains static memory that needs to be initialized, dynamic libs that need to be linked, and an entry point that needs to be read from the file header.\n", "Build it into a shared library which are designed for dynamic loading. I sure there are a lot of headers that you need and a bunch of C style calling conventions you need to obey.\nI recommend you write the extension in C, try binding that, and when that works, grab all the linkage assembler from the C compiler code generation phase.\n", "In theory you can just load the code into memory at a certain address and issue a JMP to its entry point. If you are working in python, you will probably need to do that in an extension module written in C.\nBeware that this will be rather useless unless you settle on ways to get data into/out of your little code, and specify what functions (and how) of the parent program the code is allowed to access. This means defining an ABI and calling conventions.\nAlso, I can't even begin to express how insecure this system will be unless you take rigorous precautions. The risks are increased manifold if you expose it to the public web.\n" ]
[ 1, 1, 0 ]
[]
[]
[ "assembly", "compiler_construction", "python" ]
stackoverflow_0002873571_assembly_compiler_construction_python.txt
Q: "UserWarning: Unbuilt egg for setuptools" - What does this actually mean? When I install things into a virtualenv using pip I often see the message "UserWarning: Unbuilt egg for setuptools". I always safely ignore it and go about my business and it doesn't seem to cause me any problems. But I've suddenly been smacked in the face with curiosity, and wondered if someone could explain what it means, exactly? Also, does the new virtualenv option to use distribute instead fit into all this somewhere? Should I be using that instead, or just ignoring it until distutils2 comes out? (apologies if that's totally unrelated - maybe it should be a new question?) Thanks! A: The answer and workaround in this Ubuntu bug report fixed this issue for me, where I was reading the same error while using interactive trac-admin command. Marius Gedminas, said: Workaround: sudo rmdir /usr/lib/python2.6/dist-packages/setuptools.egg-info sudo apt-get install --reinstall python-setuptools This replaces the empty directory /usr/lib/python2.6/dist-packages/setuptools.egg-info with a symlink to /usr/share/pyshared/setuptools.egg-info which is a file, not a directory.
"UserWarning: Unbuilt egg for setuptools" - What does this actually mean?
When I install things into a virtualenv using pip I often see the message "UserWarning: Unbuilt egg for setuptools". I always safely ignore it and go about my business and it doesn't seem to cause me any problems. But I've suddenly been smacked in the face with curiosity, and wondered if someone could explain what it means, exactly? Also, does the new virtualenv option to use distribute instead fit into all this somewhere? Should I be using that instead, or just ignoring it until distutils2 comes out? (apologies if that's totally unrelated - maybe it should be a new question?) Thanks!
[ "The answer and workaround in this Ubuntu bug report fixed this issue for me, where I was reading the same error while using interactive trac-admin command.\nMarius Gedminas, said:\n\nWorkaround:\nsudo rmdir /usr/lib/python2.6/dist-packages/setuptools.egg-info\nsudo apt-get install --reinstall python-setuptools\nThis replaces the empty directory\n /usr/lib/python2.6/dist-packages/setuptools.egg-info with a symlink to /usr/share/pyshared/setuptools.egg-info which is a file, not a directory.\n\n" ]
[ 14 ]
[]
[]
[ "distribute", "pip", "python", "setuptools" ]
stackoverflow_0002643835_distribute_pip_python_setuptools.txt
Q: problem in extracting the data from text file i am new to python , and I want to extract the data from this format FBpp0143497 5 151 5 157 PF00339.22 Arrestin_N Domain 1 135 149 83.4 1.1e-23 1 CL0135 FBpp0143497 183 323 183 324 PF02752.15 Arrestin_C Domain 1 137 138 58.5 6e-16 1 CL0135 FBpp0131987 60 280 51 280 PF00089.19 Trypsin Domain 14 219 219 127.7 3.7e-37 1 CL0124 to this format FBpp0143497 5 151 Arrestin_N 1.1e-23 FBpp0143497 183 323 Arrestin_C 6e-16 I have written code in hope that it works but it does not work , please help! file = open('/ddfs/user/data/k/ktrip_01/hmm.txt','r') rec = file.read() for line in rec : field = line.split("\t") print field print field[:] print '>',field[0] print field[1], field[2], field[6], field[12] the hmmtext file is FBpp0143497 5 151 5 157 PF00339.22 Arrestin_N Domain 1 135 149 83.4 1.1e-23 1 CL0135 FBpp0143497 183 323 183 324 PF02752.15 Arrestin_C Domain 1 137 138 58.5 6e-16 1 CL0135 FBpp0131987 60 280 51 280 PF00089.19 Trypsin Domain 14 219 219 127.7 3.7e-37 1 CL0124 A: to iterate over a file line-by-line, you should do: with open(fname) as file: for line in file: fields = line.split('\t') print(fields) # select fields you want to print A: Use the csv module to parse your tab-separated fields: import csv filename='/ddfs/user/data/k/ktrip_01/hmm.txt' template='''\ > {field[0]} {field[1]} {field[2]} {field[6]} {field[12]}''' with open(filename,"r") as f: csvobj=csv.reader(f,delimiter='\t') for field in csvobj: if field: print(template.format(field=field)) yields: > FBpp0143497 5 151 Arrestin_N 1.1e-23 1CL0135 > FBpp0143497 183 323 Arrestin_C 6e-1 > FBpp0131987 60 280 Trypsin 127.7 A: This line: rec = file.read() reads your whole file into rec, line breaks and all. You probably want to do this: rec = file.readlines() This is just one way to read lines from a file in Python. It's not always the best way, because this will load all the lines of the file into memory. If your input file contains, say, three million lines, it might be better to read and process each line one at a time.
problem in extracting the data from text file
i am new to python , and I want to extract the data from this format FBpp0143497 5 151 5 157 PF00339.22 Arrestin_N Domain 1 135 149 83.4 1.1e-23 1 CL0135 FBpp0143497 183 323 183 324 PF02752.15 Arrestin_C Domain 1 137 138 58.5 6e-16 1 CL0135 FBpp0131987 60 280 51 280 PF00089.19 Trypsin Domain 14 219 219 127.7 3.7e-37 1 CL0124 to this format FBpp0143497 5 151 Arrestin_N 1.1e-23 FBpp0143497 183 323 Arrestin_C 6e-16 I have written code in hope that it works but it does not work , please help! file = open('/ddfs/user/data/k/ktrip_01/hmm.txt','r') rec = file.read() for line in rec : field = line.split("\t") print field print field[:] print '>',field[0] print field[1], field[2], field[6], field[12] the hmmtext file is FBpp0143497 5 151 5 157 PF00339.22 Arrestin_N Domain 1 135 149 83.4 1.1e-23 1 CL0135 FBpp0143497 183 323 183 324 PF02752.15 Arrestin_C Domain 1 137 138 58.5 6e-16 1 CL0135 FBpp0131987 60 280 51 280 PF00089.19 Trypsin Domain 14 219 219 127.7 3.7e-37 1 CL0124
[ "to iterate over a file line-by-line, you should do:\nwith open(fname) as file:\n for line in file:\n fields = line.split('\\t')\n print(fields) # select fields you want to print\n\n", "Use the csv module to parse your tab-separated fields:\nimport csv\nfilename='/ddfs/user/data/k/ktrip_01/hmm.txt'\n\ntemplate='''\\\n> {field[0]}\n{field[1]} {field[2]} {field[6]} {field[12]}'''\n\nwith open(filename,\"r\") as f:\n csvobj=csv.reader(f,delimiter='\\t')\n for field in csvobj:\n if field:\n print(template.format(field=field))\n\nyields: \n> FBpp0143497\n5 151 Arrestin_N 1.1e-23 1CL0135\n> FBpp0143497\n183 323 Arrestin_C 6e-1\n> FBpp0131987\n60 280 Trypsin 127.7\n\n", "This line:\nrec = file.read() \n\nreads your whole file into rec, line breaks and all. You probably want to do this:\nrec = file.readlines() \n\nThis is just one way to read lines from a file in Python. It's not always the best way, because this will load all the lines of the file into memory. If your input file contains, say, three million lines, it might be better to read and process each line one at a time.\n" ]
[ 3, 1, 0 ]
[]
[]
[ "python", "string", "text_processing" ]
stackoverflow_0002873929_python_string_text_processing.txt