prefix
stringclasses 1
value | input_text
stringlengths 19
27.3k
⌀ | target_text
stringlengths 2
24.8k
⌀ |
---|---|---|
QA
|
comparison of python and perl solutions to wide finder challenge would be very grateful if you could compare the winning rourke perl solution to lundh python solution as do not know perl good enough to understand what is going on there more specifically would like to know what gave perl version advantage algorithmic superiority quality of extensions other factors wide finder results
|
perl is heavily optimized for text processing there are so many factors that it is hard to say what is the exact difference text is represented completely differently internally utf versus utf utf and the regular expression engines are completely different too python regular expression engine is custom one and not as much used as the perl one there are very few developers working on it think it is largely unmaintained in contrast to the perl one which is basically the core of the language after all perl is the text processing language
|
QA
|
comparison of python and perl solutions to wide finder challenge would be very grateful if you could compare the winning rourke perl solution to lundh python solution as do not know perl good enough to understand what is going on there more specifically would like to know what gave perl version advantage algorithmic superiority quality of extensions other factors wide finder results
|
the better regex implementation of perl is one part of the story that cannot explain however why the perl implementation scales better the difference become bigger with more processors for some reason the python implementation has an issue there
|
QA
|
passing around urls between applications in the same project am trying to mock up an api and am using separate apps within django to represent different web services would like app to take in link that corresponds to app and parse the json response is there way to dynamically construct the url to app so that can test the code in development and not change to much before going into production the problem is that cannot use localhost as part of link am currently using urllib but eventually would like to do something less hacky and better fitting with the web services rest paradigm
|
by separate apps within django do you mean separate applications with common settings that is to say two applications within the same django site or project if so the url tag will generate proper absolute url to any of the apps listed in the settings file if there are separate django servers with separate settings you have the standard internet problem of uri design your uri can be consistent with only the hostname changing http localhost some path development http some path someone is laptop who is running server for testing http qa mysite com some path qa http www mysite com some path production you never need to provide the host information so all of your links are href some path this generally works out the best you have can someone is random laptop being test server you can get the ip address using ifconfig
|
QA
|
what is the intended use of the default section in config files used by configparser have used configparser for quite while for simple configs one thing that is bugged me for long time is the default section am not really sure what is an appropriate use have read the documentation but would really like to see some clever examples of its use and how it affects other sections in the file something that really illustrates the kind of things that are possible
|
found an explanation here by googling for windows ini default section summary whatever you put in the default section gets propagated to every other section using the example from the linked website let us say have config file called test ini host lh server vh hosts plonesite lh root plonesite host lh server vh hosts plonesite lh root plonesite can read this using configparser cp configparser configparser cp read test ini test ini cp get host lh server but notice that lh server is the same in both sections and indeed realise that it will be the same for most hosts might add so can do this as test ini default lh server host vh root plonesite lh root plonesite host vh root plonesite lh root plonesite despite the sections not having lh server keys can still access them cp read test ini test ini cp get host lh server read the linked page for further example of using variable substitution in the default section to simplify the ini file even more
|
QA
|
how do read an excel file into python using xlrd can it read newer office formats my issue is below but would be interested comments from anyone with experience with xlrd just found xlrd and it looks like the perfect solution but am having little problem getting started am attempting to extract data programatically from an excel file pulled from dow jones with current components of the dow jones industrial average link http www djindexes com mdsidx event showaverages when open the file unmodified get nasty biff error binary format not recognized however you can see in this screenshot that excel for mac thinks it is in excel format screenshot http skitch com alok ssa componentreport dji xls properties if instead open it in excel manually and save as excel format explicitly then open in python usig xlrd everything is wonderful remember office thinks the file is already in excel format all files are xls here is pastebin of an ipython session replicating the issue http pastie textmate org private jbawdtrvlrruh mzueqdq any thoughts on how to trick xlrd into recognizing the file so can extract data how to use python to automate the explicit save as format to one that xlrd will accept plan
|
more info on pyexcelerator to read file do this import pyexcelerator book pyexcelerator parse xls filename where filename is string that is the filename to read not file like object this will give you data structure representing the workbook list of pairs where the first element of the pair is the worksheet name and the second element is the worksheet data the worksheet data is dictionary where the keys are row col pairs starting with and the values are the cell contents generally int float or string so for instance in the simple case of all the data being on the first worksheet data book print cell of worksheet is book repr data if the cell is empty you will get keyerror if you are dealing with dates they may forget come through as integers or floats if this is the case you will need to convert basically the rule is datetime datetime datetime timedelta days but that might be off by or because excel treats as leap year for compatibility with lotus and because cannot remember if is or so do some trial and error to check datetimes are stored as floats think days and fractions of day think there is partial support for forumulas but would not guarantee anything
|
QA
|
what is the easiest most concise way to make selected attributes in an instance be readonly in python want to make selected instance attributes of class be readonly to code outside of the class want there to be no way outside code can alter the attribute except indirectly by invoking methods on the instance want the syntax to be concise what is the best way give my current best answer below
|
there is no real way to do this there are ways to make it more difficult but there is no concept of completely hidden inaccessible class attributes if the person using your class cannot be trusted to follow the api docs then that is their own problem protecting people from doing stupid stuff just means that they will do far more elaborate complicated and damaging stupid stuff to try to do whatever they should not have been doing in the first place
|
QA
|
what is the easiest most concise way to make selected attributes in an instance be readonly in python want to make selected instance attributes of class be readonly to code outside of the class want there to be no way outside code can alter the attribute except indirectly by invoking methods on the instance want the syntax to be concise what is the best way give my current best answer below
|
class object def init self self fullaccess self readonly almost invisible to outside code define publicly visible read only version of readonly readonly property lambda self self readonly def inc readonly self self readonly prove regular attribute is rw print fullaccess fullaccess fullaccess print fullaccess fullaccess prove readonly is read only attribute print readonly readonly try readonly except attributeerror print cannot change readonly print readonly readonly change readonly indirectly inc readonly print readonly readonly this outputs python py fullaccess fullaccess readonly cannot change readonly readonly readonly my fingers itch to be able to say readonly self readonly use decorator on an attribute it would be so clean
|
QA
|
what is the easiest most concise way to make selected attributes in an instance be readonly in python want to make selected instance attributes of class be readonly to code outside of the class want there to be no way outside code can alter the attribute except indirectly by invoking methods on the instance want the syntax to be concise what is the best way give my current best answer below
|
you should use the property decorator class object def init self self property def xval self return self xval xval traceback most recent call last file stdin line in module attributeerror cannot set attribute
|
QA
|
adding new element to text substring say have the following string am the most foo ck ever am trying to write makespecial foo function where the foo substring would be wrapped in new span element resulting in am the most span class special foo span ck ever beautifulsoup seemed like the way to go but have not been able to make it work could also pass this to the browser and do it with javascript but that does not seem like great idea some advice for this would be really useful especially in python
|
how about this python apr msc bit intel on win type help copyright credits or license for more information def makespecial mystring special substr return mystring replace special substr span class special span special substr makespecial am the most foo ck ever foo am the most span class special foo span ck ever
|
QA
|
adding new element to text substring say have the following string am the most foo ck ever am trying to write makespecial foo function where the foo substring would be wrapped in new span element resulting in am the most span class special foo span ck ever beautifulsoup seemed like the way to go but have not been able to make it work could also pass this to the browser and do it with javascript but that does not seem like great idea some advice for this would be really useful especially in python
|
as far as can tell you are doing simple string replace you are replacing foo with bar foo bar so from string you could just use replace old new count return copy of the string with all occurrences of substring old replaced by new if the optional argument count is given only the first count occurrences are replaced so for you it would be mystr replace foo span foo span
|
QA
|
what is the easiest most concise way to make selected attributes in an instance be readonly in python want to make selected instance attributes of class be readonly to code outside of the class want there to be no way outside code can alter the attribute except indirectly by invoking methods on the instance want the syntax to be concise what is the best way give my current best answer below
|
you could use metaclass that auto wraps methods or class attributes that follow naming convention into properties shamelessly taken from unifying types and classes in python class autoprop type def init cls name bases dict super autoprop cls init name bases dict props for name in dict keys if name startswith get or name startswith set props name for name in props keys fget getattr cls get name none fset getattr cls set name none setattr cls name property fget fset this allows you to use class metaclass autosuprop def readonly self return
|
QA
|
cx oracle how do iterate over result set there are several ways to iterate over result set what are the tradeoff of each
|
my preferred way is the cursor iterator but setting first the arraysize property of the cursor curs execute select from people curs arraysize for row in curs print row in this example cx oracle will fetch rows from oracle rows at time reducing the number of network round trips that need to be performed
|
QA
|
adding new element to text substring say have the following string am the most foo ck ever am trying to write makespecial foo function where the foo substring would be wrapped in new span element resulting in am the most span class special foo span ck ever beautifulsoup seemed like the way to go but have not been able to make it work could also pass this to the browser and do it with javascript but that does not seem like great idea some advice for this would be really useful especially in python
|
if you wanted to do it with javascript jquery take look at this question http stackoverflow com questions highlight word with jquery
|
QA
|
python reading oracle path on my desktop have written small pylons app that connects to oracle am now trying to deploy it to my server which is running win my desktop is bit xp the oracle installation on the server is also bit was getting errors about loading the oci dll so installed the bit client into oracle if add this to the path environment variable it works great but also want to run the pylons app as service using this recipe and do not want to put this bit library on the path for all other applications tried using sys path append oracle bin but that does not seem to work
|
you need to append the oracle bin directory to the path variable of your environment before you execute python exe in linux need to set up the ld library path variable for similar reasons to locate the oracle libraries before calling python use wrapper she will scripts that set the variable and then call python in your case maybe you can call in the service startup cmd or vbs script that sets the path variable and then calls python exe with your py script hope this helps
|
QA
|
extracting text from ms word files in python for working with ms word files in python there is python win extensions which can be used in windows how do do the same in linux is there any library
|
take look at how the doc format works and create word document using php in linux the former is especially useful abiword is my recommended tool there are limitations though however if the document has complicated tables text boxes embedded spreadsheets and so forth then it might not work as expected developing good ms word filters is very difficult process so please bear with us as we work on getting word documents to open correctly if you have word document which fails to load please open bug and include the document so we can improve the importer
|
QA
|
extracting text from ms word files in python for working with ms word files in python there is python win extensions which can be used in windows how do do the same in linux is there any library
|
am not sure if you are going to have much luck without using com the doc format is ridiculously complex and is often called memory dump of word at the time of saving at swati that is in html which is fine and dandy but most word documents are not so nice
|
QA
|
extracting text from ms word files in python for working with ms word files in python there is python win extensions which can be used in windows how do do the same in linux is there any library
|
openoffice org can be scripted with python see here since ooo can load most ms word files flawlessly would say that is your best bet
|
QA
|
extracting text from ms word files in python for working with ms word files in python there is python win extensions which can be used in windows how do do the same in linux is there any library
|
you could make subprocess call to antiword antiword is linux commandline utility for dumping text out of word doc works pretty well for simple documents obviously it loses formatting it is available through apt and probably as rpm or you could compile it yourself
|
QA
|
how do modify text file in python am using python and would like to insert string into text file without deleting or copying the file how can do that
|
depends on what you want to do to append you can open it with with open foo txt as write new line if you want to preprend something you have to read from the file first with open foo txt as old read read everything in the file seek rewind write new line old write the new line before
|
QA
|
what is the easiest most concise way to make selected attributes in an instance be readonly in python want to make selected instance attributes of class be readonly to code outside of the class want there to be no way outside code can alter the attribute except indirectly by invoking methods on the instance want the syntax to be concise what is the best way give my current best answer below
|
here is how class whatever object def init self self foobar self blahblah foobar property lambda self self foobar blahblah property lambda self self blahblah assuming foobar and blahblah are the attributes you want to be read only prepending two underscores to an attribute name effectively hides it from outside the class so the internal versions will not be accessible from the outside this only works for new style classes inheriting from object since it depends on property on the other hand this is pretty silly thing to do keeping variables private seems to be an obsession that comes from and java your users should use the public interface to your class because it is well designed not because you force them to edit looks like kevin already posted similar version
|
QA
|
how do modify text file in python am using python and would like to insert string into text file without deleting or copying the file how can do that
|
unfortunately there is no way to insert into the middle of file without re writing it as previous posters have indicated you can append to file or overwrite part of it using seek but if you want to add stuff at the beginning or the middle you will have to rewrite it this is an operating system thing not python thing it is the same in all languages what usually do is read from the file make the modifications and write it out to new file called myfile txt tmp or something like that this is better than reading the whole file into memory because the file may be too large for that once the temporary file is completed rename it the same as the original file this is good safe way to do it because if the file write crashes or aborts for any reason you still have your untouched original file
|
QA
|
how do copy file in python how do copy file in python could not find anything under os
|
copying file is relatively straightforward operation as shown by the examples below but you should instead use the shutil stdlib module for that def copyfileobj example source dest buffer size copy file from source to dest source and dest must be file like objects any object with read or write method like for example stringio while copy buffer source read buffer size if not copy buffer break dest write copy buffer if you want to copy by filename you could do something like this def copyfile example source dest beware this example does not handle any edge cases with open source rb as src open dest wb as dst copyfileobj example src dst
|
QA
|
convert mysql timestamp to epoch time in python convert mysql timestamp to epoch time in python is there an easy way to do this
|
use something like the following to get seconds since the epoch utc from mysql date local time calendar timegm time gmtime time mktime time strptime more info in this question http stackoverflow com questions how do convert local time to utc in python
|
QA
|
python library for rendering html and javascript is there any python module for rendering html page with javascript and get back dom object want to parse page which generates almost all of its content using javascript
|
only way know to accomplish this would be to drive real browser for example using selenium rc
|
QA
|
python library for rendering html and javascript is there any python module for rendering html page with javascript and get back dom object want to parse page which generates almost all of its content using javascript
|
the big complication here is emulating the full browser environment outside of browser you can use stand alone javascript interpreters like rhino and spidermonkey to run javascript code but they do not provide complete browser like environment to full render web page if needed to solve problem like this would first look at how the javascript is rendering the page it is quite possible it is fetching data via ajax and using that to render the page could then use python libraries like simplejson and httplib to directly fetch the data and use that negating the need to access the dom object however that is only one possible situation do not know the exact problem you are solving other options include the selenium one mentioned by ukasz some kind of webkit embedded craziness some kind of ie win scripting craziness or finally pyxpcom based solution with added craziness all these have the drawback of requiring pretty much fully running web browser for python to play with which might not be an option depending on your environment
|
QA
|
python library for rendering html and javascript is there any python module for rendering html page with javascript and get back dom object want to parse page which generates almost all of its content using javascript
|
qtwebkit is contained in pyqt but do not know if you can use it without showing widget after cursory look over the documentation it seems to me you can only get html not dom tree
|
QA
|
how do develop and create self contained pygtk application bundle for macos with native looking widgets have read that it is possible to build gtk on macos know that it is possible to create bundle of gtk application on macos also know that it is possible to create widgets that look sort of native however searching around am not really clear on how to create bundle that includes the native theme stuff and uses python rather than its own main point there are also rumors that it is possible to build pygtk but it sounds like there might still be some wrinkles in that process however there is no step by step guide that explains how one can set up an environment where an application might be run from python source then built and deployed in an app bundle how can go about doing that
|
while it is not guide solely targetted at python gtk os this post is good detailed description of someone else attempt to do most of what you describe obviously the app specific stuff is going to vary
|
QA
|
python library for rendering html and javascript is there any python module for rendering html page with javascript and get back dom object want to parse page which generates almost all of its content using javascript
|
you can probably use python webkit for it requires running glib and gtk but that is probably less problematic than wrapping the parts of webkit without glib do not know if it does everything you need but guess you should give it try
|
QA
|
how do develop and create self contained pygtk application bundle for macos with native looking widgets have read that it is possible to build gtk on macos know that it is possible to create bundle of gtk application on macos also know that it is possible to create widgets that look sort of native however searching around am not really clear on how to create bundle that includes the native theme stuff and uses python rather than its own main point there are also rumors that it is possible to build pygtk but it sounds like there might still be some wrinkles in that process however there is no step by step guide that explains how one can set up an environment where an application might be run from python source then built and deployed in an app bundle how can go about doing that
|
native looking widgets is quite complicated there is beginning of quartz engine for theming found here http git gnome org browse gtk tree gdk quartz for self contained applications check out the newly released bundle on http live gnome org gtk osx
|
QA
|
how do create new signal in pygtk have created python object but want to send signals on it made it inherit from gobject gobject but there does not seem to be any way to create new signal on my object
|
if you use kiwi available here you can just do from kiwi utils import gsignal class myobject gobject gobject gsignal signal name
|
QA
|
how do modify text file in python am using python and would like to insert string into text file without deleting or copying the file how can do that
|
rewriting file in place is often done by saving the old copy with modified name unix folks add to mark the old one windows folks do all kinds of things add bak or old or rename the file entirely or put the on the front of the name import shutil shutil move afile afile destination open afile source open afile for line in source destination write line if some condition destination write some additional line source close destination close instead of shutil you can use the following import os os rename afile afile
|
QA
|
example facebook application using turbogears pyfacebook have turbogears application would like to run through facebook and am looking for an example turbogears project using pyfacebook or minifb py pyfacebook is django centric and can probably figure it out but this is after all the lazy web
|
why is pyfacebook django centric looks like it works perfectly fine with all kinds of wsgi apps or python applications in general no need to use django
|
QA
|
cannot find lpq when trying to install psycopg intro am trying to migrate our trac sqlite to postgresql backend to do that need psycopg after clicking past the embarrassing rant on www initd org downloaded the latest version and tried running setup py install this did not work telling me needed mingw so downloaded and installed mingw problem now get the following error when running setup py build ext compiler mingw install running build ext building psycopg psycopg extension writing build temp win release psycopg psycopg def mingw bin gcc exe mno cygwin shared build temp win release psycopg psycopgmodule build temp win release psycopg pqpath build temp win release psycopg typecast build temp win release psycopg microprotoco ls build temp win release psycopg microprotocols proto build temp win release psycopg connection type build temp win release psycopg con nection int build temp win release psycopg cursor type build temp win release psycopg cursor int build temp win release psycopg lobject type build temp win release psycopg lobject int build temp win elease psycopg adapter qstring build temp win release psycopg adapter pb oolean build temp win release psycopg adapter binary build temp win release psycopg adapter asis build temp win release psycopg adapter list build temp win release psycopg adapter datetime build temp win release psycopg psycopg def lc python libs lc python pcbuild lc rogra postgr lib lpython lmsvcr lpq lmsvcr lws ladvapi build lib win psycopg psycopg pyd mingw bin lib gcc mingw mingw bin ld exe cannot fin lpq collect ld returned exit status error command gcc failed with exit status what have tried noticed the forward slashes in the option so manually entered my postgresql lib directory in the library dirs option in the setup cfg to no avail the call then had option with backslashes but the error message stayed the same
|
have you tried the binary build of psycopg for windows if that works with your python then it mitigates the need to build by hand have seen random people ask this question on various lists and it seems one recommendation is to build postgresql by hand to work around this problem
|
QA
|
cannot find lpq when trying to install psycopg intro am trying to migrate our trac sqlite to postgresql backend to do that need psycopg after clicking past the embarrassing rant on www initd org downloaded the latest version and tried running setup py install this did not work telling me needed mingw so downloaded and installed mingw problem now get the following error when running setup py build ext compiler mingw install running build ext building psycopg psycopg extension writing build temp win release psycopg psycopg def mingw bin gcc exe mno cygwin shared build temp win release psycopg psycopgmodule build temp win release psycopg pqpath build temp win release psycopg typecast build temp win release psycopg microprotoco ls build temp win release psycopg microprotocols proto build temp win release psycopg connection type build temp win release psycopg con nection int build temp win release psycopg cursor type build temp win release psycopg cursor int build temp win release psycopg lobject type build temp win release psycopg lobject int build temp win elease psycopg adapter qstring build temp win release psycopg adapter pb oolean build temp win release psycopg adapter binary build temp win release psycopg adapter asis build temp win release psycopg adapter list build temp win release psycopg adapter datetime build temp win release psycopg psycopg def lc python libs lc python pcbuild lc rogra postgr lib lpython lmsvcr lpq lmsvcr lws ladvapi build lib win psycopg psycopg pyd mingw bin lib gcc mingw mingw bin ld exe cannot fin lpq collect ld returned exit status error command gcc failed with exit status what have tried noticed the forward slashes in the option so manually entered my postgresql lib directory in the library dirs option in the setup cfg to no avail the call then had option with backslashes but the error message stayed the same
|
compiling extensions on windows can be tricky there are precompiled libraries available however http www stickpeople com projects python win psycopg
|
QA
|
adding code to init py am taking look at how the model system in django works and noticed something that do not understand know that you create an empty init py file to specify that the current directory is package and that you can set some variable in init py so that import works properly but django adds bunch of from import statements and defines bunch of classes in init py why does not this just make things look messy is there reason that requires this code in init py
|
using the init py file allows you to make the internal package structure invisible from the outside if the internal structure changes because you split one fat module into two you only have to adjust the init py file but not the code that depends on the package you can also make parts of your package invisible if they are not ready for general usage note that you can use the del command so typical init py may look like this from somemodule import some function some function someobject del somemodule now if you decide to split somemodule the new init py might be from somemodule import some function some function from somemodule import someobject del somemodule del somemodule from the outside the package still looks exactly as before
|
QA
|
iterate list with indexes in python could swear have seen the function or method that takes list like this and makes it into iterable list of tuples like so to use it instead of for in range len name of list name of list something but cannot remember the name and googling iterate list gets nothing
|
for val in enumerate print val
|
QA
|
iterate list with indexes in python could swear have seen the function or method that takes list like this and makes it into iterable list of tuples like so to use it instead of for in range len name of list name of list something but cannot remember the name and googling iterate list gets nothing
|
yep that would be the enumerate function or more to the point you need to do list enumerate
|
QA
|
how can move an object drawn in device context python have drawn an image in the device context using python and want to move it somothly animate either vertically or horizontally what algorithm should use where can get info for this kind of tasks in python
|
once an object is drawn in device context it stays there if you want to move it you need to redraw it you can keep background that is fixed and only redraw the movable elements each time they move basically that is how it is done to move an object smoothly over line you have to do something like this do not have program ready so can only give you an idea choose the start and end position point and choose in how much time the object should change position from to say seconds use timer set to certain interval say seconds calculate the delta and that the object should change for each timer interval in this case dx and dy in the timer callback increment the current object position with dx and dy and redraw the image that would be the algorithm suggest that you also take look to pygame maybe you can use that and it also has some tutorials
|
QA
|
checking for code changes in all imported python modules almost every python web framework has simple server that runs wsgi application and automatically reloads the imported modules every time the source gets changed know can look at the code and see how it is done but that may take some time and am asking just out of curiosity does anyone have any idea how this is implemented
|
as the author of one of the reloader mechanisms the one in werkzeug can tell you that it does not work what all the reloaders do is forking one time and restarting the child process if monitor thread notices that one module changed on the file system inline reload ing does not work because references to the reloaded module are not updated
|
QA
|
checking for code changes in all imported python modules almost every python web framework has simple server that runs wsgi application and automatically reloads the imported modules every time the source gets changed know can look at the code and see how it is done but that may take some time and am asking just out of curiosity does anyone have any idea how this is implemented
|
reload does not work reloading is usually implemented by forking implementing real reload is extremely difficult and even the most serious attempt twisted python rebuild is not perfect
|
QA
|
find out number of capture groups in python regular expressions is there way to determine how many capture groups there are in given regular expression would like to be able to do the follwing def groups regexp returns the first result of re findall or an empty default groups groups abc import re re search regexp if return groups return num of groups regexp this allows me to do stuff like first last phone groups john doe however do not know how to implement num of groups currently just work around it edit following the advice from rslite replaced re findall with re search sre parse seems like the most robust and comprehensive solution but requires tree traversal and appears to be bit heavy mizardx regular expression seems to cover all bases so am going to go with that
|
first of all if you only need the first result of re findall it is better to just use re search that returns match or none for the groups number you could count the number of open parenthesis except those that are escaped by you could use another regex for that def num of groups regexp rg re compile return len rg findall regexp note that this does not work if the regex contains non capturing groups and also if is escaped by using it as so this is not very reliable but depending on the regexes that you use it might help
|
QA
|
find out number of capture groups in python regular expressions is there way to determine how many capture groups there are in given regular expression would like to be able to do the follwing def groups regexp returns the first result of re findall or an empty default groups groups abc import re re search regexp if return groups return num of groups regexp this allows me to do stuff like first last phone groups john doe however do not know how to implement num of groups currently just work around it edit following the advice from rslite replaced re findall with re search sre parse seems like the most robust and comprehensive solution but requires tree traversal and appears to be bit heavy mizardx regular expression seems to cover all bases so am going to go with that
|
the lastindex property of the match object should be what you are looking for see the re module docs
|
QA
|
find out number of capture groups in python regular expressions is there way to determine how many capture groups there are in given regular expression would like to be able to do the follwing def groups regexp returns the first result of re findall or an empty default groups groups abc import re re search regexp if return groups return num of groups regexp this allows me to do stuff like first last phone groups john doe however do not know how to implement num of groups currently just work around it edit following the advice from rslite replaced re findall with re search sre parse seems like the most robust and comprehensive solution but requires tree traversal and appears to be bit heavy mizardx regular expression seems to cover all bases so am going to go with that
|
something from inside sre parse might help at first glance maybe something along the lines of import sre parse sre parse parse subpattern in category category digit in category category digit subpattern in category category digit count the items of type subpattern import sre parse def count patterns regex count patterns foo count patterns foo count patterns foo parsed sre parse parse regex return len token for token in parsed if token subpattern note that we are only counting root level patterns here so the last example only returns to change this tokens would need to searched recursively
|
QA
|
find out number of capture groups in python regular expressions is there way to determine how many capture groups there are in given regular expression would like to be able to do the follwing def groups regexp returns the first result of re findall or an empty default groups groups abc import re re search regexp if return groups return num of groups regexp this allows me to do stuff like first last phone groups john doe however do not know how to implement num of groups currently just work around it edit following the advice from rslite replaced re findall with re search sre parse seems like the most robust and comprehensive solution but requires tree traversal and appears to be bit heavy mizardx regular expression seems to cover all bases so am going to go with that
|
might be wrong but do not think there is way to find the number of groups that would have been returned had the regex matched the only way can think of to make this work the way you want it to is to pass the number of matches your particular regex expects as an argument to clarify though when findall succeeds you only want the first match to be returned but when it fails you want list of empty strings because the comment seems to show all matches being returned as list
|
QA
|
how can move an object drawn in device context python have drawn an image in the device context using python and want to move it somothly animate either vertically or horizontally what algorithm should use where can get info for this kind of tasks in python
|
to smoothly move object between starting coordinate and destination coordinate you need to first ask yourself how long the object should take to get to its destination let us say you want the object to get there in time units which maybe seconds hours whatever once you have determined this it is then trivial to workout the displacement per unit time dx dy now you simply need to add dx dy to the object position initially every unit time and stop when the object gets within some threshold distance of the destination this is to account for the fact errors in divisions will accumulate so if you did an equality check like it is unlikely it will ever be true note the above method gives you constant velocity straight line movement you may wish to instead use some sort slightly more complex formula to give the object the appearance of accelerating maintaining cruise speed then decelerating the following formulae may then be useful you this is merely euler method and should suffice for animation purposes
|
QA
|
iterate list with indexes in python could swear have seen the function or method that takes list like this and makes it into iterable list of tuples like so to use it instead of for in range len name of list name of list something but cannot remember the name and googling iterate list gets nothing
|
here is another using the zip function zip range len
|
QA
|
find out number of capture groups in python regular expressions is there way to determine how many capture groups there are in given regular expression would like to be able to do the follwing def groups regexp returns the first result of re findall or an empty default groups groups abc import re re search regexp if return groups return num of groups regexp this allows me to do stuff like first last phone groups john doe however do not know how to implement num of groups currently just work around it edit following the advice from rslite replaced re findall with re search sre parse seems like the most robust and comprehensive solution but requires tree traversal and appears to be bit heavy mizardx regular expression seems to cover all bases so am going to go with that
|
using your code as basis def groups regexp returns the first result of re findall or an empty default groups groups abc import re re search regexp if return groups return len groups
|
QA
|
contributing to python am pretty inexperienced programmer can make tk apps text processing sort of understand oop but python is so awesome that would like to help the community what is the best way for beginner to contribute
|
guess one way would be to help with documentation translation updating until you are aware enough about the language also following the devs and users mail groups would give you pretty good idea of what is being done and needs to be done by the community
|
QA
|
contributing to python am pretty inexperienced programmer can make tk apps text processing sort of understand oop but python is so awesome that would like to help the community what is the best way for beginner to contribute
|
if you are not up to actually working on the python core there are still many ways to contribute that immediately come to mind is work on documentation it can always be improved take your favorite modules and check out the documentation and add where you can reporting descriptive bugs is very helpful to the development process
|
QA
|
contributing to python am pretty inexperienced programmer can make tk apps text processing sort of understand oop but python is so awesome that would like to help the community what is the best way for beginner to contribute
|
get involved with the community http www python org dev
|
QA
|
contributing to python am pretty inexperienced programmer can make tk apps text processing sort of understand oop but python is so awesome that would like to help the community what is the best way for beginner to contribute
|
add to the docs it is downright crappy help out other users on the dev and user mailing lists test python bugs in programming languages are real bad and have seen someone discover atleast bug in python frequent the python channel on irc freenode net
|
QA
|
contributing to python am pretty inexperienced programmer can make tk apps text processing sort of understand oop but python is so awesome that would like to help the community what is the best way for beginner to contribute
|
build something cool in python and share it with others small values of cool are still cool not everyone gets to write epic world changing software every problem solved well using python is way of showing how cool python is
|
QA
|
editing xml as dictionary in python am trying to generate customized xml files from template xml file in python conceptually want to read in the template xml remove some elements change some text attributes and write the new xml out to file wanted it to work something like this conf base convertxmltodict config template xml conf base dict conf base unwrap del conf base dict root name level name leaf del conf base dict root name level name leaf conf new convertdicttoxml conf base dict now want to write to file but do not see how to get to elementtree elementtree write conf new write config new xml is there some way to do this or can someone suggest doing this different way
|
am not sure if converting the info set to nested dicts first is easier using elementtree you can do this import xml etree elementtree as et doc et parse template xml lvl doc findall level name lvl remove lvl find leaf lvl remove lvl find leaf or use del lvl idx doc write config new xml elementtree was designed so that you do not have to convert your xml trees to lists and attributes first since it uses exactly that internally it also support as small subset of xpath
|
QA
|
editing xml as dictionary in python am trying to generate customized xml files from template xml file in python conceptually want to read in the template xml remove some elements change some text attributes and write the new xml out to file wanted it to work something like this conf base convertxmltodict config template xml conf base dict conf base unwrap del conf base dict root name level name leaf del conf base dict root name level name leaf conf new convertdicttoxml conf base dict now want to write to file but do not see how to get to elementtree elementtree write conf new write config new xml is there some way to do this or can someone suggest doing this different way
|
have you tried this print xml etree elementtree tostring conf new
|
QA
|
contributing to python am pretty inexperienced programmer can make tk apps text processing sort of understand oop but python is so awesome that would like to help the community what is the best way for beginner to contribute
|
start by contributing to python project that you use and enjoy this can be as simple as answering questions on the mailing list or irc channel offering to help with documentation and test writing or fixing bugs
|
QA
|
how to parse an iso formatted date in python need to parse rfc strings like into python datetime type have found strptime in the python standard library but it is not very convenient what is the best way to do this
|
what is the exact error you get is it like the following datetime datetime strptime dt valueerror time data did not match format data fmt dt if yes you can split your input string on and then add the microseconds to the datetime you got try this def gt dt str dt us dt str partition dt datetime datetime strptime dt dt us int us rstrip return dt datetime timedelta microseconds us gt datetime datetime
|
QA
|
how to parse an iso formatted date in python need to parse rfc strings like into python datetime type have found strptime in the python standard library but it is not very convenient what is the best way to do this
|
import re datetime datetime datetime map int re split
|
QA
|
how to parse an iso formatted date in python need to parse rfc strings like into python datetime type have found strptime in the python standard library but it is not very convenient what is the best way to do this
|
try the iso module it does exactly this there are several other options mentioned on the workingwithtime page on the python org wiki
|
QA
|
how to parse an iso formatted date in python need to parse rfc strings like into python datetime type have found strptime in the python standard library but it is not very convenient what is the best way to do this
|
note in python and py the character catches microseconds datetime datetime strptime dt fz see issue here
|
QA
|
how to implement decorator with non local equality greetings currently am refactoring one of my programs and found an interesting problem have transitions in an automata transitions always have start state and an end state some transitions have label which encodes certain action that must be performed upon traversal no label means no action some transitions have condition which must be fulfilled in order to traverse this condition if there is no condition the transition is basically an epsilon transition in an nfa and will be traversed without consuming an input symbol need the following operations check if the transition has label get this label add label to transition check if the transition has condition get this condition check for equality judging from the first five points this sounds like clear decorator with base transition and two decorators labeled and condition however this approach has problem two transitions are considered equal if their start state and end state are the same the labels at both transitions are equal or not existing and both conditions are the same or not existing with decorator might have two transitions labeled foo conditional bar transition baz qux and conditional bar labeled foo transition baz qux which need non local equality that is the decorators would need to collect all the data and the transition must compare this collected data on set base class transition object def init self start end self start start self end end def get label self return none def has label self return false def collect decorations self decorations return decorations def internal equality self my decorations other try return self start other start and self end other end and my decorations other collect decorations def eq self other return self internal equality self collect decorations other class labeled object def init self label base self base base self label label def has label self return true def get label self return self label def collect decorations self decorations assert label not in decorations decorations label self label return self base collect decorations decorations def getattr self attribute return self base getattr attribute is this clean approach am missing something am mostly confused because can solve this with longer class names using cooperative multiple inheritance class transition object def init self kwargs init is pythons mi madness super transition self init kwargs self start kwargs start self end kwargs end def get label self return none def get condition self return none def eq self other try return self start other start and self end other end except attributeerror return false class labeledtransition transition def init self kwargs super labeledtransition init kwargs self label kwargs label def get label self return self label def eq self super result super labeledtransition self eq other try return super result and self label other label except attributeerror return false class conditionaltransition transition def init self kwargs super conditionaltransition self init kwargs self condition kwargs condition def get condition self return self condition def eq self other super result super conditionaltransition self eq other try return super result and self condition other condition except attributeerror return false conditionaltransition about the same with get condition class labeledconditionaltransition labeledtransition conditionaltransition pass the class labledconditionaltransition behaves exactly as expected and having no code in there is appealing and do not thing mi is confusing at this size of course the third option would be to just hammer everything into single transition class with bunch of in has label has transition so am confused am missing something which implementation looks better how do you handle similar cases that is objects which look like decorator could handle them but then such non local method comes around edit added the conditionaltransition class basically this kind of behaves like the decorator minus the order created by the order of creating the decorators the transition checks for start and end being correct the labeledtransition class checks for label being correct and conditionaltransition checks for condition being correct
|
from the code that was posted the only difference between transition and labeled transition is the return of get lable and has label in which case you can compress these two single class that sets label attribute to none and return self label is not none in the has label function can you post the code for the conditionaltransition class think this would make it clearer
|
QA
|
editing xml as dictionary in python am trying to generate customized xml files from template xml file in python conceptually want to read in the template xml remove some elements change some text attributes and write the new xml out to file wanted it to work something like this conf base convertxmltodict config template xml conf base dict conf base unwrap del conf base dict root name level name leaf del conf base dict root name level name leaf conf new convertdicttoxml conf base dict now want to write to file but do not see how to get to elementtree elementtree write conf new write config new xml is there some way to do this or can someone suggest doing this different way
|
for easy manipulation of xml in python like the beautiful soup library it works something like this sample xml file root level leaf level level leaf level root python code from beautifulsoup import beautifulstonesoup tag navigablestring soup beautifulstonesoup config template xml get the parser for the xml file soup contents name you root you can use the node names as methods soup root contents name you level it is also possible to use regexes import re tags starting with level soup findall re compile level for tag in tags starting with level print tag name level level adding and inserting new nodes is pretty straightforward build and insert new level with new leaf level tag soup level level insert navigablestring leaf soup root insert level print soup prettify root level leaf level level leaf level level leaf level root
|
QA
|
what is the best way to store set data in python have list of data in the following form id description id type id description id type id description id type the data are loaded from files that belong to the same group in each group there could be multiples of the same id each coming from different files do not care about the duplicates so thought that nice way to store all of this would be to throw it into set type but there is problem sometimes for the same id the descriptions can vary slightly as follows ipi tubulin alpha chain tubulin alpha chain alpha tubulin alpha tubulin isotype alpha note that this example is taken from the uniprot protein database do not care if the descriptions vary cannot throw them away because there is chance that the protein database am using will not contain listing for certain identifier if this happens will want to be able to display the human readable description to the biologists so they know roughly what protein they are looking at am currently solving this problem by using dictionary type however do not really like this solution because it uses lot of memory have lot of these id this is only an intermediary listing of them there is some additional processing the id go through before they are placed in the database so would like to keep my data structure smaller have two questions really first will get smaller memory footprint using the set type over the dictionary type for this or should use sorted list where check every time insert into the list to see if the id exists or is there third solution that have not thought of second if the set type is the better answer how do key it to look at just the first element of the tuple instead of the whole thing thank you for reading my question tim update based on some of the comments received let me clarify little most of what do with data structure is insert into it only read it twice once to annotate it with additional information and once to do be inserted into the database however down the line there may be additional annotation that is done before insert into the database unfortunately do not know if that will happen at this time right now am looking into storing this data in structure that is not based on hash table ie dictionary would like the new structure to be fairly quick on insertion but reading it can be linear since only really do it twice am trying to move away from the hash table to save space is there better structure or is hash table about as good as it gets the information is list of swiss prot protein identifiers that get by querying uniprot
|
sets do not have keys the element is the key if you think you want keys you have mapping more or less by definition sequential list lookup can be slow even using binary search mappings use hashes and are fast are you talking about dictionary like this id description type description type id description type this sure seems minimal id are only represented once perhaps you have something like this id description description type id description type am not sure you can find anything more compact unless you resort to using the struct module
|
QA
|
what is the best way to store set data in python have list of data in the following form id description id type id description id type id description id type the data are loaded from files that belong to the same group in each group there could be multiples of the same id each coming from different files do not care about the duplicates so thought that nice way to store all of this would be to throw it into set type but there is problem sometimes for the same id the descriptions can vary slightly as follows ipi tubulin alpha chain tubulin alpha chain alpha tubulin alpha tubulin isotype alpha note that this example is taken from the uniprot protein database do not care if the descriptions vary cannot throw them away because there is chance that the protein database am using will not contain listing for certain identifier if this happens will want to be able to display the human readable description to the biologists so they know roughly what protein they are looking at am currently solving this problem by using dictionary type however do not really like this solution because it uses lot of memory have lot of these id this is only an intermediary listing of them there is some additional processing the id go through before they are placed in the database so would like to keep my data structure smaller have two questions really first will get smaller memory footprint using the set type over the dictionary type for this or should use sorted list where check every time insert into the list to see if the id exists or is there third solution that have not thought of second if the set type is the better answer how do key it to look at just the first element of the tuple instead of the whole thing thank you for reading my question tim update based on some of the comments received let me clarify little most of what do with data structure is insert into it only read it twice once to annotate it with additional information and once to do be inserted into the database however down the line there may be additional annotation that is done before insert into the database unfortunately do not know if that will happen at this time right now am looking into storing this data in structure that is not based on hash table ie dictionary would like the new structure to be fairly quick on insertion but reading it can be linear since only really do it twice am trying to move away from the hash table to save space is there better structure or is hash table about as good as it gets the information is list of swiss prot protein identifiers that get by querying uniprot
|
how about using id description id type dictionary or id id type description dictionary if id id type is the key
|
QA
|
what is the best way to upgrade from django to should try to actually upgrade my existing app or just rewrite it mostly from scratch saving what pieces templates etc can
|
upgrade for me it was very simple change str to unicode write basic admin py and done just start running your app on test it and when you encounter an error use the documentation on backwards incompatible changes to see how to fix the issue
|
QA
|
what is the best way to upgrade from django to should try to actually upgrade my existing app or just rewrite it mostly from scratch saving what pieces templates etc can
|
although this depends on what you are doing most applications should be able to just upgrade and then fix everything that breaks in my experience the main things that have had to fix after an upgrade are changes to some of the funky stuff with models such as the syntax for following foreign keys small set of template changes most notably auto escaping anything that depends on the specific structure of django internals this should not be an issue unless you are doing stuff like dynamically modifying django internals to change their behavior in way that is necessary convenient for your project to summarize unless you are doing lot of really weird and or complex stuff simple upgrade should be relatively painless and only require few changes
|
QA
|
should python import statements always be at the top of module pep states imports are always put at the top of the file just after any module comments and docstrings and before module globals and constants however if the class method function that am importing is only used in rare cases surely it is more efficient to do the import when it is needed is not this class someclass object def not often called self from datetime import datetime self datetime datetime now more efficient than this from datetime import datetime class someclass object def not often called self self datetime datetime now
|
the first variant is indeed more efficient than the second when the function is called either zero or one times with the second and subsequent invocations however the import every call approach is actually less efficient see this link for lazy loading technique that combines the best of both approaches by doing lazy import but there are reasons other than efficiency why you might prefer one over the other one approach is makes it much more clear to someone reading the code as to the dependencies that this module has they also have very different failure characteristics the first will fail at load time if there is no datetime module while the second will not fail until the method is called added note in ironpython imports can be quite bit more expensive than in cpython because the code is basically being compiled as it is being imported
|
QA
|
should python import statements always be at the top of module pep states imports are always put at the top of the file just after any module comments and docstrings and before module globals and constants however if the class method function that am importing is only used in rare cases surely it is more efficient to do the import when it is needed is not this class someclass object def not often called self from datetime import datetime self datetime datetime now more efficient than this from datetime import datetime class someclass object def not often called self self datetime datetime now
|
would not worry about the efficiency of loading the module up front too much the memory taken up by the module will not be very big assuming it is modular enough and the startup cost will be negligible in most cases you want to load the modules at the top of the source file for somebody reading your code it makes it much easier to tell what function or object came from what module one good reason to import module elsewhere in the code is if it is used in debugging statement for example do something with could debug this with from pprint import pprint pprint do something with of course the other reason to import modules elsewhere in the code is if you need to dynamically import them this is because you pretty much do not have any choice would not worry about the efficiency of loading the module up front too much the memory taken up by the module will not be very big assuming it is modular enough and the startup cost will be negligible
|
QA
|
what is the best way to store set data in python have list of data in the following form id description id type id description id type id description id type the data are loaded from files that belong to the same group in each group there could be multiples of the same id each coming from different files do not care about the duplicates so thought that nice way to store all of this would be to throw it into set type but there is problem sometimes for the same id the descriptions can vary slightly as follows ipi tubulin alpha chain tubulin alpha chain alpha tubulin alpha tubulin isotype alpha note that this example is taken from the uniprot protein database do not care if the descriptions vary cannot throw them away because there is chance that the protein database am using will not contain listing for certain identifier if this happens will want to be able to display the human readable description to the biologists so they know roughly what protein they are looking at am currently solving this problem by using dictionary type however do not really like this solution because it uses lot of memory have lot of these id this is only an intermediary listing of them there is some additional processing the id go through before they are placed in the database so would like to keep my data structure smaller have two questions really first will get smaller memory footprint using the set type over the dictionary type for this or should use sorted list where check every time insert into the list to see if the id exists or is there third solution that have not thought of second if the set type is the better answer how do key it to look at just the first element of the tuple instead of the whole thing thank you for reading my question tim update based on some of the comments received let me clarify little most of what do with data structure is insert into it only read it twice once to annotate it with additional information and once to do be inserted into the database however down the line there may be additional annotation that is done before insert into the database unfortunately do not know if that will happen at this time right now am looking into storing this data in structure that is not based on hash table ie dictionary would like the new structure to be fairly quick on insertion but reading it can be linear since only really do it twice am trying to move away from the hash table to save space is there better structure or is hash table about as good as it gets the information is list of swiss prot protein identifiers that get by querying uniprot
|
sets in python are implemented using hash tables in earlier versions they were actually implemented using sets but that has changed afaik the only thing you save by using set would then be the size of pointer for each entry the pointer to the value to use only part of tuple for the hashcode you would have to subclass tuple and override the hashcode method class proteintuple tuple def new cls return tuple new cls def hash self return hash self keep in mind that you pay for the extra function call to hash in this case because otherwise it would be method would go for constantin suggestions and take out the id from the tuple and see how much that helps
|
QA
|
should python import statements always be at the top of module pep states imports are always put at the top of the file just after any module comments and docstrings and before module globals and constants however if the class method function that am importing is only used in rare cases surely it is more efficient to do the import when it is needed is not this class someclass object def not often called self from datetime import datetime self datetime datetime now more efficient than this from datetime import datetime class someclass object def not often called self self datetime datetime now
|
most of the time this would be useful for clarity and sensible to do but it is not always the case below are couple of examples of circumstances where module imports might live elsewhere firstly you could have module with unit test of the form if name main import foo aa foo xyz initiate something for the test secondly you might have requirement to conditionally import some different module at runtime if condition import foo as plugin api else import bar as plugin api xx plugin api plugin there are probably other situations where you might place imports in other parts in the code
|
QA
|
should python import statements always be at the top of module pep states imports are always put at the top of the file just after any module comments and docstrings and before module globals and constants however if the class method function that am importing is only used in rare cases surely it is more efficient to do the import when it is needed is not this class someclass object def not often called self from datetime import datetime self datetime datetime now more efficient than this from datetime import datetime class someclass object def not often called self self datetime datetime now
|
it is tradeoff that only the programmer can decide to make case saves some memory and startup time by not importing the datetime module and doing whatever initialization it might require until needed note that doing the import only when called also means doing it every time when called so each call after the first one is still incurring the additional overhead of doing the import case save some execution time and latency by importing datetime beforehand so that not often called will return more quickly when it is called and also by not incurring the overhead of an import on every call besides efficiency it is easier to see module dependencies up front if the import statements are up front hiding them down in the code can make it more difficult to easily find what modules something depends on personally generally follow the pep except for things like unit tests and such that do not want always loaded because know they are not going to be used except for test code
|
QA
|
should python import statements always be at the top of module pep states imports are always put at the top of the file just after any module comments and docstrings and before module globals and constants however if the class method function that am importing is only used in rare cases surely it is more efficient to do the import when it is needed is not this class someclass object def not often called self from datetime import datetime self datetime datetime now more efficient than this from datetime import datetime class someclass object def not often called self self datetime datetime now
|
curt makes good point the second version is clearer and will fail at load time rather than later and unexpectedly normally do not worry about the efficiency of loading modules since it is pretty fast and mostly only happens at startup if you have to load heavyweight modules at unexpected times it probably makes more sense to load them dynamically with the import function and be sure to catch importerror exceptions and handle them in reasonable manner
|
QA
|
what is the best way to store set data in python have list of data in the following form id description id type id description id type id description id type the data are loaded from files that belong to the same group in each group there could be multiples of the same id each coming from different files do not care about the duplicates so thought that nice way to store all of this would be to throw it into set type but there is problem sometimes for the same id the descriptions can vary slightly as follows ipi tubulin alpha chain tubulin alpha chain alpha tubulin alpha tubulin isotype alpha note that this example is taken from the uniprot protein database do not care if the descriptions vary cannot throw them away because there is chance that the protein database am using will not contain listing for certain identifier if this happens will want to be able to display the human readable description to the biologists so they know roughly what protein they are looking at am currently solving this problem by using dictionary type however do not really like this solution because it uses lot of memory have lot of these id this is only an intermediary listing of them there is some additional processing the id go through before they are placed in the database so would like to keep my data structure smaller have two questions really first will get smaller memory footprint using the set type over the dictionary type for this or should use sorted list where check every time insert into the list to see if the id exists or is there third solution that have not thought of second if the set type is the better answer how do key it to look at just the first element of the tuple instead of the whole thing thank you for reading my question tim update based on some of the comments received let me clarify little most of what do with data structure is insert into it only read it twice once to annotate it with additional information and once to do be inserted into the database however down the line there may be additional annotation that is done before insert into the database unfortunately do not know if that will happen at this time right now am looking into storing this data in structure that is not based on hash table ie dictionary would like the new structure to be fairly quick on insertion but reading it can be linear since only really do it twice am trying to move away from the hash table to save space is there better structure or is hash table about as good as it gets the information is list of swiss prot protein identifiers that get by querying uniprot
|
am assuming the problem you try to solve by cutting down on the memory you use is the address space limit of your process additionally you search for data structure that allows you fast insertion and reasonable sequential read out use less structures except strings str the question you ask is how to structure your data in one process to use less memory the one canonical answer to this is as long as you still need associative lookups use as little other structures then python strings str not unicode as possible python hash dictionary stores the references to your strings fairly efficiently it is not tree implementation however think that you will not get very far with that approach since what you face are huge datasets that might eventually just exceed the process address space and the physical memory of the machine you are working with altogether alternative solution would propose different solution that does not involve changing your data structure to something that is harder to insert or interprete split your information up in multiple processes each holding whatever datastructure is convinient for that implement inter process communication with sockets such that processes might reside on other machines altogether try to divide your data such as to minimize inter process communication is glacially slow compared to cpu cycles the advantage of the approach outline is that you get to use two ore more cores on machine fully for performance you are not limited by the address space of one process or even the physical memory of one machine there are numerous packages and aproaches to distributed processing some of which are linda processing
|
QA
|
what is the best way to store set data in python have list of data in the following form id description id type id description id type id description id type the data are loaded from files that belong to the same group in each group there could be multiples of the same id each coming from different files do not care about the duplicates so thought that nice way to store all of this would be to throw it into set type but there is problem sometimes for the same id the descriptions can vary slightly as follows ipi tubulin alpha chain tubulin alpha chain alpha tubulin alpha tubulin isotype alpha note that this example is taken from the uniprot protein database do not care if the descriptions vary cannot throw them away because there is chance that the protein database am using will not contain listing for certain identifier if this happens will want to be able to display the human readable description to the biologists so they know roughly what protein they are looking at am currently solving this problem by using dictionary type however do not really like this solution because it uses lot of memory have lot of these id this is only an intermediary listing of them there is some additional processing the id go through before they are placed in the database so would like to keep my data structure smaller have two questions really first will get smaller memory footprint using the set type over the dictionary type for this or should use sorted list where check every time insert into the list to see if the id exists or is there third solution that have not thought of second if the set type is the better answer how do key it to look at just the first element of the tuple instead of the whole thing thank you for reading my question tim update based on some of the comments received let me clarify little most of what do with data structure is insert into it only read it twice once to annotate it with additional information and once to do be inserted into the database however down the line there may be additional annotation that is done before insert into the database unfortunately do not know if that will happen at this time right now am looking into storing this data in structure that is not based on hash table ie dictionary would like the new structure to be fairly quick on insertion but reading it can be linear since only really do it twice am trying to move away from the hash table to save space is there better structure or is hash table about as good as it gets the information is list of swiss prot protein identifiers that get by querying uniprot
|
it is still murky but it sounds like you have some several lists of id description type the id are unique within list and consistent between lists you want to create union single list where each id occurs once with possibly multiple descriptions for some reason you think mapping might be too big do you have any evidence of this do not over optimize without actual measurements this may be if am guessing correctly the standard merge operation from multiple sources source sort source sort result while len source or len source if len source result append source pop elif len source result append source pop elif source source result append source pop elif source source result append source pop else keys are equal result append source pop check for source to see if the description is different this assembles union of two lists by sorting and merging no mapping no hash
|
QA
|
should python import statements always be at the top of module pep states imports are always put at the top of the file just after any module comments and docstrings and before module globals and constants however if the class method function that am importing is only used in rare cases surely it is more efficient to do the import when it is needed is not this class someclass object def not often called self from datetime import datetime self datetime datetime now more efficient than this from datetime import datetime class someclass object def not often called self self datetime datetime now
|
module importing is quite fast but not instant this means that putting the imports at the top of the module is fine because it is trivial cost that is only paid once putting the imports within function will cause calls to that function to take longer so if you care about efficiency put the imports at the top only move them into function if your profiling shows that would help you did profile to see where best to improve performance right the best reasons have seen to perform lazy imports are optional library support if your code has multiple paths that use different libraries do not break if an optional library is not installed in the init py of plugin which might be imported but not actually used examples are bazaar plugins which use bzrlib lazy loading framework
|
QA
|
where do the python unit tests go if you are writing library or an app where do the unit test files go it is nice to separate the test files from the main app code but it is awkward to put them into tests subdirectory inside of the app root directory because it makes it harder to import the modules that you will be testing is there best practice here
|
we use app src code py app testing code test py app docs in each test file we insert src in sys path it is not the nicest solution but works think it would be great if someone came up something like maven in java that gives you standard conventions that just work no matter what project you work on
|
QA
|
should python import statements always be at the top of module pep states imports are always put at the top of the file just after any module comments and docstrings and before module globals and constants however if the class method function that am importing is only used in rare cases surely it is more efficient to do the import when it is needed is not this class someclass object def not often called self from datetime import datetime self datetime datetime now more efficient than this from datetime import datetime class someclass object def not often called self self datetime datetime now
|
here is an example where all the imports are at the very top this is the only time have needed to do this want to be able to terminate subprocess on both un and windows import os try kill os kill will raise attributeerror on windows from signal import sigterm def terminate process kill process pid sigterm except attributeerror importerror try from win api import terminateprocess use win api if available def terminate process terminateprocess int process handle except importerror def terminate process raise notimplementederror define dummy function on review what john millikin said
|
QA
|
should python import statements always be at the top of module pep states imports are always put at the top of the file just after any module comments and docstrings and before module globals and constants however if the class method function that am importing is only used in rare cases surely it is more efficient to do the import when it is needed is not this class someclass object def not often called self from datetime import datetime self datetime datetime now more efficient than this from datetime import datetime class someclass object def not often called self self datetime datetime now
|
this is like many other optimizations you sacrifice some readability for speed as john mentioned if you have done your profiling homework and found this to be significantly useful enough change and you need the extra speed then go for it it would probably be good to put note up with all the other imports from foo import bar from baz import qux note datetime is imported in someclass below
|
QA
|
should python import statements always be at the top of module pep states imports are always put at the top of the file just after any module comments and docstrings and before module globals and constants however if the class method function that am importing is only used in rare cases surely it is more efficient to do the import when it is needed is not this class someclass object def not often called self from datetime import datetime self datetime datetime now more efficient than this from datetime import datetime class someclass object def not often called self self datetime datetime now
|
module initialization only occurs once on the first import if the module in question is from the standard library then you will likely import it from other modules in your program as well for module as prevalent as datetime it is also likely dependency for slew of other standard libraries the import statement would cost very little then since the module intialization would have happened already all it is doing at this point is binding the existing module object to the local scope couple that information with the argument for readability and would say that it is best to have the import statement at module scope
|
QA
|
using property on classmethods have class with two class methods using the classmethod function for getting and setting what is essentially static variable tried to use the property function with these but it results in an error was able to reproduce the error with the following in the interpreter class foo object var def getvar cls return cls var getvar classmethod getvar def setvar cls value cls var value setvar classmethod setvar var property getvar setvar getvar setvar getvar var traceback most recent call last file stdin line in typeerror classmethod object is not callable var traceback most recent call last file stdin line in typeerror classmethod object is not callable is it possible to use the property function with classmethod decorated functions
|
half solution set on the class does not work still the solution is custom property class implementing both property and staticmethod class classproperty object def init self fget fset self fget fget self fset fset def get self instance owner return self fget def set self instance value self fset value class foo object bar def get bar print getting return foo bar def set bar value print setting foo bar value bar classproperty get bar set bar foo get works bar foo bar bar foo bar set does not
|
QA
|
should python import statements always be at the top of module pep states imports are always put at the top of the file just after any module comments and docstrings and before module globals and constants however if the class method function that am importing is only used in rare cases surely it is more efficient to do the import when it is needed is not this class someclass object def not often called self from datetime import datetime self datetime datetime now more efficient than this from datetime import datetime class someclass object def not often called self self datetime datetime now
|
have adopted the practice of putting all imports in the functions that use them rather than at the top of the module the benefit get is the ability to refactor more reliably when move function from one module to another know that the function will continue to work with all of its legacy of testing intact if have my imports at the top of the module when move function find that end up spending lot of time getting the new module imports complete and minimal refactoring ide might make this irrelevant there is speed penalty as mentioned elsewhere have measured this in my application and found it to be insignificant for my purposes it is also nice to be able to see all module dependencies up front without resorting to search grep however the reason care about module dependencies is generally because am installing refactoring or moving an entire system comprising multiple files not just single module in that case am going to perform global search anyway to make sure have the system level dependencies so have not found global imports to aid my understanding of system in practice usually put the import of sys inside the if name main check and then pass arguments like sys argv to main function this allows me to use main in context where sys has not been imported
|
QA
|
does django support multi value cookies would like to set cookie via django with that has several different values to it similar to net httpcookie values property looking at the documentation cannot tell if this is possible it looks like it just takes string so is there another way have tried passing it an array and dictionary name scott id but they just get converted to their string format my current solution is to just use an arbitrary separator and then parse it when reading it in which feels icky if multi values are not possible is there better way would rather not use lots of cookies because that would get annoying
|
nets multi value cookies work exactly the same way as what you are doing in django using separator they have just abstracted that away for you what you are doing is fine and proper and do not think django has anything specific to solve this problem will say that you are doing the right thing in not using multiple cookies keep the over the wire overhead down by doing what you are doing
|
QA
|
perl or python script to remove user from group am putting together samba based server as primary domain controller and ran into cute little problem that should have been solved many times over but number of searches did not yield result need to be able to remove an existing user from an existing group with command line script it appears that the usermod easily allows me to add user to supplementary group with this command usermod supgroup supgroup username without the option if the user is currently member of group which is not listed the user will be removed from the group does anyone have perl or python script that allows the specification of user and group for removal am missing an obvious existing command or well known solution forthis thanks in advance thanks to for the pointer to the unix group module which is part of unix configfile it looks like the command deluser would do what want but was not in any of my existing repositories went ahead and wrote the perl script using the unix group module here is the script for your sysadmining pleasure usr bin perl usage removegroup pl login group purpose removes user from group while retaining current primary and supplementary groups notes there is debian specific utility that can do this called deluser but did not want any cross distribution dependencies date september validate arguments correct number format etc if argv argv print nusage removegroup pl login group print exit values print the removeuser pl script exits with the following values print success print invalid number of arguments print login or group name supplied greater than characters print login and or group name contains invalid characters exit check for well formed group and login names if length argv length argv print usage removegroup pl login group print error login and group names must be less than characters exit if argv argv print usage removegroup pl login group print error login and or group name contains invalid characters exit set some variables for readability login argv group argv requires the groupfile interface from perl unix configfile use unix groupfile grp new unix groupfile etc group grp remove user group login grp commit undef grp exit
|
it looks like deluser group groupname should do it if not the groups command lists the groups that user belongs to it should be fairly straightforward to come up with some perl to capture that list into an array or map it into hash delete the unwanted group and feed that back to usermod
|
QA
|
generic exception handling in python the right way sometimes find myself in the situation where want to execute several sequential commands like such try foo except exception baz try bar except exception baz this same pattern occurs when exceptions simply need to be ignored this feels redundant and the excessive syntax causes it to be surprisingly difficult to follow when reading code in would have solved this type of problem easily with macro but unfortunately this cannot be done in straight python question how can best reduce the code footprint and increase code readability when coming across this pattern
|
if they are simple one line commands you can wrap them in lambdas for cmd in lambda foo lambda bar try cmd except standarderror baz you could wrap that whole thing up in function so it looked like this ignore errors baz lambda foo lambda bar
|
QA
|
generic exception handling in python the right way sometimes find myself in the situation where want to execute several sequential commands like such try foo except exception baz try bar except exception baz this same pattern occurs when exceptions simply need to be ignored this feels redundant and the excessive syntax causes it to be surprisingly difficult to follow when reading code in would have solved this type of problem easily with macro but unfortunately this cannot be done in straight python question how can best reduce the code footprint and increase code readability when coming across this pattern
|
the best approach have found is to define function like such def handle exception function reaction args kwargs try result function args kwargs except exception result reaction return result but that just does not feel or look right in practice handle exception foo baz handle exception bar baz
|
QA
|
generic exception handling in python the right way sometimes find myself in the situation where want to execute several sequential commands like such try foo except exception baz try bar except exception baz this same pattern occurs when exceptions simply need to be ignored this feels redundant and the excessive syntax causes it to be surprisingly difficult to follow when reading code in would have solved this type of problem easily with macro but unfortunately this cannot be done in straight python question how can best reduce the code footprint and increase code readability when coming across this pattern
|
you could use the with statement if you have python from future import with statement import contextlib contextlib contextmanager def handler try yield except exception baz your example now becomes with handler foo with handler bar
|
QA
|
what is the best way to upgrade from django to should try to actually upgrade my existing app or just rewrite it mostly from scratch saving what pieces templates etc can
|
just upgrade your app the switch from to was huge but in terms of backwards incompatible changes doubt your app even has of them was on trunk before django so the transition for me was over time but even then the only major things had to change were newforms newforms admin str to unicode and maxlength to max length most of the other changes were new features or backend rewrites or stuff that as someone who was building basic websites did not even get near
|
QA
|
perl or python script to remove user from group am putting together samba based server as primary domain controller and ran into cute little problem that should have been solved many times over but number of searches did not yield result need to be able to remove an existing user from an existing group with command line script it appears that the usermod easily allows me to add user to supplementary group with this command usermod supgroup supgroup username without the option if the user is currently member of group which is not listed the user will be removed from the group does anyone have perl or python script that allows the specification of user and group for removal am missing an obvious existing command or well known solution forthis thanks in advance thanks to for the pointer to the unix group module which is part of unix configfile it looks like the command deluser would do what want but was not in any of my existing repositories went ahead and wrote the perl script using the unix group module here is the script for your sysadmining pleasure usr bin perl usage removegroup pl login group purpose removes user from group while retaining current primary and supplementary groups notes there is debian specific utility that can do this called deluser but did not want any cross distribution dependencies date september validate arguments correct number format etc if argv argv print nusage removegroup pl login group print exit values print the removeuser pl script exits with the following values print success print invalid number of arguments print login or group name supplied greater than characters print login and or group name contains invalid characters exit check for well formed group and login names if length argv length argv print usage removegroup pl login group print error login and group names must be less than characters exit if argv argv print usage removegroup pl login group print error login and or group name contains invalid characters exit set some variables for readability login argv group argv requires the groupfile interface from perl unix configfile use unix groupfile grp new unix groupfile etc group grp remove user group login grp commit undef grp exit
|
found this for you it should do what you need as far as can tell perl does not have any built in functions for removing users from group it has several for seeing the group id of user or process
|
QA
|
how to import module given the full path how can load python module given its full path note that the file can be anywhere in the filesystem as it is configuration option
|
the advantage of adding path to sys path over using imp is that it simplifies things when importing more than one module from single package for example import sys the mock dir contains testcase py testutils py mock py sys path append foo bar mock from testcase import testcase from testutils import runtests from mock import mock sentinel patch
|
QA
|
what is the best way to store set data in python have list of data in the following form id description id type id description id type id description id type the data are loaded from files that belong to the same group in each group there could be multiples of the same id each coming from different files do not care about the duplicates so thought that nice way to store all of this would be to throw it into set type but there is problem sometimes for the same id the descriptions can vary slightly as follows ipi tubulin alpha chain tubulin alpha chain alpha tubulin alpha tubulin isotype alpha note that this example is taken from the uniprot protein database do not care if the descriptions vary cannot throw them away because there is chance that the protein database am using will not contain listing for certain identifier if this happens will want to be able to display the human readable description to the biologists so they know roughly what protein they are looking at am currently solving this problem by using dictionary type however do not really like this solution because it uses lot of memory have lot of these id this is only an intermediary listing of them there is some additional processing the id go through before they are placed in the database so would like to keep my data structure smaller have two questions really first will get smaller memory footprint using the set type over the dictionary type for this or should use sorted list where check every time insert into the list to see if the id exists or is there third solution that have not thought of second if the set type is the better answer how do key it to look at just the first element of the tuple instead of the whole thing thank you for reading my question tim update based on some of the comments received let me clarify little most of what do with data structure is insert into it only read it twice once to annotate it with additional information and once to do be inserted into the database however down the line there may be additional annotation that is done before insert into the database unfortunately do not know if that will happen at this time right now am looking into storing this data in structure that is not based on hash table ie dictionary would like the new structure to be fairly quick on insertion but reading it can be linear since only really do it twice am trying to move away from the hash table to save space is there better structure or is hash table about as good as it gets the information is list of swiss prot protein identifiers that get by querying uniprot
|
if you are doing an way merge with removing duplicates the following may be what you are looking for this generator will merge any number of sources each source must be sequence the key must be in position it yields the merged sequence one item at time def merge sources keypos for in sources sort while any len for in sources topenum enumerate keypos if len else none for in sources top for in topenum if is not none top sort key lambda src key top print src key yield sources src pop this generator removes duplicates from sequence def unique sequence keypos seqiter iter sequence curr seqiter next for next in seqiter if next keypos curr keypos might want to create sub list of matches continue yield curr curr next yield curr here is script which uses these functions to produce resulting sequence which is the union of all the sources with duplicates removed for you in unique merge source source source print you the complete set of data in each sequence must exist in memory once because we are sorting in memory however the resulting sequence does not actually exist in memory indeed it works by consuming the other sequences
|
QA
|
perl or python script to remove user from group am putting together samba based server as primary domain controller and ran into cute little problem that should have been solved many times over but number of searches did not yield result need to be able to remove an existing user from an existing group with command line script it appears that the usermod easily allows me to add user to supplementary group with this command usermod supgroup supgroup username without the option if the user is currently member of group which is not listed the user will be removed from the group does anyone have perl or python script that allows the specification of user and group for removal am missing an obvious existing command or well known solution forthis thanks in advance thanks to for the pointer to the unix group module which is part of unix configfile it looks like the command deluser would do what want but was not in any of my existing repositories went ahead and wrote the perl script using the unix group module here is the script for your sysadmining pleasure usr bin perl usage removegroup pl login group purpose removes user from group while retaining current primary and supplementary groups notes there is debian specific utility that can do this called deluser but did not want any cross distribution dependencies date september validate arguments correct number format etc if argv argv print nusage removegroup pl login group print exit values print the removeuser pl script exits with the following values print success print invalid number of arguments print login or group name supplied greater than characters print login and or group name contains invalid characters exit check for well formed group and login names if length argv length argv print usage removegroup pl login group print error login and group names must be less than characters exit if argv argv print usage removegroup pl login group print error login and or group name contains invalid characters exit set some variables for readability login argv group argv requires the groupfile interface from perl unix configfile use unix groupfile grp new unix groupfile etc group grp remove user group login grp commit undef grp exit
|
here is very simple little perl script that should give you the list of groups you need my user user my groupnomore somegroup my groups join grep ne groupnomore split groups user getting and sanitizing the required arguments is left as an execrcise for the reader
|
QA
|
how do you test that python function throws an exception how does one write unittest that fails only if function does not throw an expected exception
|
have look at the assertraises method of the unittest module
|
QA
|
how do you test that python function throws an exception how does one write unittest that fails only if function does not throw an expected exception
|
use testcase assertraises or testcase failunlessraises from the unittest module for example import mymod class mytestcase unittest testcase def test self self assertraises somecoolexception mymod myfunc
|
QA
|
how do you test that python function throws an exception how does one write unittest that fails only if function does not throw an expected exception
|
your code should follow this pattern this is unittest module style test def test afunction throws exception self try afunction except expectedexception pass except exception as self fail unexpected exception raised else self fail expectedexception not raised on python this construct is useful for checking for specific values in the expected exception the unittest function assertraises only checks if an exception was raised
|
QA
|
how do you test that python function throws an exception how does one write unittest that fails only if function does not throw an expected exception
|
the code in my previous answer can be simplified to def test afunction throws exception self self assertraises expectedexception afunction and if afunction takes arguments just pass them into assertraises like this def test afunction throws exception self self assertraises expectedexception afunction arg arg
|
QA
|
generic exception handling in python the right way sometimes find myself in the situation where want to execute several sequential commands like such try foo except exception baz try bar except exception baz this same pattern occurs when exceptions simply need to be ignored this feels redundant and the excessive syntax causes it to be surprisingly difficult to follow when reading code in would have solved this type of problem easily with macro but unfortunately this cannot be done in straight python question how can best reduce the code footprint and increase code readability when coming across this pattern
|
you could try something like this this is vaguely macro like class tryorbaz object def init self that self that that def call self args try return self that args except exception baz tryorbaz foo tryorbaz bar
|
QA
|
should python import statements always be at the top of module pep states imports are always put at the top of the file just after any module comments and docstrings and before module globals and constants however if the class method function that am importing is only used in rare cases surely it is more efficient to do the import when it is needed is not this class someclass object def not often called self from datetime import datetime self datetime datetime now more efficient than this from datetime import datetime class someclass object def not often called self self datetime datetime now
|
putting the import statement inside of function can prevent circular dependencies
|
QA
|
using property on classmethods have class with two class methods using the classmethod function for getting and setting what is essentially static variable tried to use the property function with these but it results in an error was able to reproduce the error with the following in the interpreter class foo object var def getvar cls return cls var getvar classmethod getvar def setvar cls value cls var value setvar classmethod setvar var property getvar setvar getvar setvar getvar var traceback most recent call last file stdin line in typeerror classmethod object is not callable var traceback most recent call last file stdin line in typeerror classmethod object is not callable is it possible to use the property function with classmethod decorated functions
|
there is no reasonable way to make this class property system to work in python here is one unreasonable way to make it work you can certainly make it more seamless with increasing amounts of metaclass magic class classproperty object def init self getter setter self getter getter self setter setter def get self cls owner return getattr cls self getter def set self cls value getattr cls self setter value class metafoo type var classproperty getvar setvar class foo object metaclass metafoo var classmethod def getvar cls print getting var cls var return cls var classmethod def setvar cls value print setting var value cls var value foo var print foo var foo var foo var print foo var the knot of the issue is that properties are what python calls descriptors there is no short and easy way to explain how this sort of metaprogramming works so must point you to the descriptor howto you only ever need to understand this sort of things if you are implementing fairly advanced framework like transparent object persistence or rpc system or kind of domain specific language however in comment to previous answer you say that you need to modify an attribute that in such way that is seen by all instances of class and in the scope from which these class methods are called does not have references to all instances of the class it seems to me what you really want is an observer design pattern
|
QA
|
using property on classmethods have class with two class methods using the classmethod function for getting and setting what is essentially static variable tried to use the property function with these but it results in an error was able to reproduce the error with the following in the interpreter class foo object var def getvar cls return cls var getvar classmethod getvar def setvar cls value cls var value setvar classmethod setvar var property getvar setvar getvar setvar getvar var traceback most recent call last file stdin line in typeerror classmethod object is not callable var traceback most recent call last file stdin line in typeerror classmethod object is not callable is it possible to use the property function with classmethod decorated functions
|
because need to modify an attribute that in such way that is seen by all instances of class and in the scope from which these class methods are called does not have references to all instances of the class do you have access to at least one instance of the class can think of way to do it then class myclass object var none def set var self value type self var value def get var self return self var var property get var set var myclass myclass var foo print var
|
QA
|
does django support multi value cookies would like to set cookie via django with that has several different values to it similar to net httpcookie values property looking at the documentation cannot tell if this is possible it looks like it just takes string so is there another way have tried passing it an array and dictionary name scott id but they just get converted to their string format my current solution is to just use an arbitrary separator and then parse it when reading it in which feels icky if multi values are not possible is there better way would rather not use lots of cookies because that would get annoying
|
django does not support it the best way would be to separate the values with arbitrary separator and then just split the string like you already said
|
QA
|
using property on classmethods have class with two class methods using the classmethod function for getting and setting what is essentially static variable tried to use the property function with these but it results in an error was able to reproduce the error with the following in the interpreter class foo object var def getvar cls return cls var getvar classmethod getvar def setvar cls value cls var value setvar classmethod setvar var property getvar setvar getvar setvar getvar var traceback most recent call last file stdin line in typeerror classmethod object is not callable var traceback most recent call last file stdin line in typeerror classmethod object is not callable is it possible to use the property function with classmethod decorated functions
|
give this try it gets the job done without having to change add lot of existing code class foo object var def getvar cls return cls var getvar classmethod getvar def setvar cls value cls var value setvar classmethod setvar var property lambda self self getvar lambda self val self setvar val foo var var var the property function needs two callable arguments give them lambda wrappers which it passes the instance as its first argument and all is well
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.