prefix
stringclasses 1
value | input_text
stringlengths 19
27.3k
⌀ | target_text
stringlengths 2
24.8k
⌀ |
---|---|---|
QA
|
is there an inverse function for time gmtime that parses utc tuple to seconds since the epoch python time module seems little haphazard for example here is list of methods in there from the docstring time return current time in seconds since the epoch as float clock return cpu time since process start as float sleep delay for number of seconds given as float gmtime convert seconds since epoch to utc tuple localtime convert seconds since epoch to local time tuple asctime convert time tuple to string ctime convert time in seconds to string mktime convert local time tuple to seconds since epoch strftime convert time tuple to string according to format specification strptime parse string to time tuple according to format specification tzset change the local timezone looking at localtime and its inverse mktime why is there no inverse for gmtime bonus questions what would you name the method how would you implement it
|
always thought the time and datetime modules were little incoherent anyways here is the inverse of mktime import time def mkgmtime convert utc tuple to seconds since epoch return time mktime time timezone
|
QA
|
is there an inverse function for time gmtime that parses utc tuple to seconds since the epoch python time module seems little haphazard for example here is list of methods in there from the docstring time return current time in seconds since the epoch as float clock return cpu time since process start as float sleep delay for number of seconds given as float gmtime convert seconds since epoch to utc tuple localtime convert seconds since epoch to local time tuple asctime convert time tuple to string ctime convert time in seconds to string mktime convert local time tuple to seconds since epoch strftime convert time tuple to string according to format specification strptime parse string to time tuple according to format specification tzset change the local timezone looking at localtime and its inverse mktime why is there no inverse for gmtime bonus questions what would you name the method how would you implement it
|
am only newbie to python but here is my approach def mkgmtime fields now int time time gmt list time gmtime now gmt time localtime now tm isdst disp now time mktime tuple gmt return disp time mktime fields there my proposed name for the function too it is important to recalculate disp every time in case the daylight savings value changes or the like the conversion back to tuple is required for jython cpython does not seem to require it this is super ick because time gmtime sets the dst flag to false always hate the code though there is got to be better way to do it and there are probably some corner cases that have not got yet
|
QA
|
getting python to use the activetcl libraries is there any way to get python to use my activetcl installation instead of having to copy the activetcl libraries into the python tcl directory
|
not familiar with activetcl but in general here is how to get package module to be loaded when that name already exists in the standard library import sys dir name usr lib mydir sys path insert dir name substitute the value for dir name with the path to the directory containing your package module and run the above code before anything is imported this is often done through sitecustomize py file so that it will take effect as soon as the interpreter starts up so you will not need to worry about import ordering
|
QA
|
how do efficiently filter computed values within python list comprehension the python list comprehension syntax makes it easy to filter values within comprehension for example result for in mylist if type is int will return list of the squares of integers in mylist however what if the test involves some costly computation and you want to filter on the result one option is result expensive for in mylist if expensive this will result in list of non false expensive values however expensive is called twice for each is there comprehension syntax that allows you to do this test while only calling expensive once per
|
came up with my own answer after minute of thought it can be done with nested comprehensions result for in expensive for in mylist if guess that works though find nested comprehensions are only marginally readable
|
QA
|
how do efficiently filter computed values within python list comprehension the python list comprehension syntax makes it easy to filter values within comprehension for example result for in mylist if type is int will return list of the squares of integers in mylist however what if the test involves some costly computation and you want to filter on the result one option is result expensive for in mylist if expensive this will result in list of non false expensive values however expensive is called twice for each is there comprehension syntax that allows you to do this test while only calling expensive once per
|
result for in map expensive mylist if map will return list of the values of each object in mylist passed to expensive then you can list comprehend that and discard unnecessary values this is somewhat like nested comprehension but should be faster since the python interpreter can optimize it fairly easily
|
QA
|
how do efficiently filter computed values within python list comprehension the python list comprehension syntax makes it easy to filter values within comprehension for example result for in mylist if type is int will return list of the squares of integers in mylist however what if the test involves some costly computation and you want to filter on the result one option is result expensive for in mylist if expensive this will result in list of non false expensive values however expensive is called twice for each is there comprehension syntax that allows you to do this test while only calling expensive once per
|
you could always memoize the expensive function so that calling it the second time around is merely lookup for the computed value of here is just one of many implementations of memoize as decorator
|
QA
|
how do efficiently filter computed values within python list comprehension the python list comprehension syntax makes it easy to filter values within comprehension for example result for in mylist if type is int will return list of the squares of integers in mylist however what if the test involves some costly computation and you want to filter on the result one option is result expensive for in mylist if expensive this will result in list of non false expensive values however expensive is called twice for each is there comprehension syntax that allows you to do this test while only calling expensive once per
|
you could memoize expensive and if you are calling expensive frequently you probably should memoize it any way this page gives an implementation of memoize for python http code activestate com recipes this has the added benefit that expensive may be run less than times since any duplicate entries will make use of the memo from the previous execution note that this assumes expensive is true function and does not depend on external state that may change if expensive does depend on external state and you can detect when that state changes or you know it will not change during your list comprehension then you can reset the memos before the comprehension
|
QA
|
how do efficiently filter computed values within python list comprehension the python list comprehension syntax makes it easy to filter values within comprehension for example result for in mylist if type is int will return list of the squares of integers in mylist however what if the test involves some costly computation and you want to filter on the result one option is result expensive for in mylist if expensive this will result in list of non false expensive values however expensive is called twice for each is there comprehension syntax that allows you to do this test while only calling expensive once per
|
if the calculations are already nicely bundled into functions how about using filter and map result filter none map expensive mylist you can use itertools imap if the list is very large
|
QA
|
how do efficiently filter computed values within python list comprehension the python list comprehension syntax makes it easy to filter values within comprehension for example result for in mylist if type is int will return list of the squares of integers in mylist however what if the test involves some costly computation and you want to filter on the result one option is result expensive for in mylist if expensive this will result in list of non false expensive values however expensive is called twice for each is there comprehension syntax that allows you to do this test while only calling expensive once per
|
the most obvious and would argue most readable answer is to not use list comprehension or generator expression but rather real generator def gen expensive mylist for item in mylist result expensive item if result yield result it takes more horizontal space but it is much easier to see what it does at glance and you end up not repeating yourself
|
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
|
pyfacebook is django centric because it includes django example did not intend to irk but am merely looking for turbogears example using pyfacebook
|
QA
|
python date comparisons would like to find out if particular python datetime object is older than hours or minutes am trying to do something similar to if datetime now self timestamp where is either seconds or minutes this generates type error what is the proper way to do date time comparison in python already looked at workingwithtime which is close but not exactly what want assume just want the datetime object represented in seconds so that can do normal int comparison please post lists of datetime best practices
|
you can subtract two datetime objects to find the difference between them you can use datetime fromtimestamp to parse posix time stamp
|
QA
|
python date comparisons would like to find out if particular python datetime object is older than hours or minutes am trying to do something similar to if datetime now self timestamp where is either seconds or minutes this generates type error what is the proper way to do date time comparison in python already looked at workingwithtime which is close but not exactly what want assume just want the datetime object represented in seconds so that can do normal int comparison please post lists of datetime best practices
|
you can use combination of the days and seconds attributes of the returned object to figure out the answer like this def seconds difference stamp stamp delta stamp stamp return delta days delta seconds delta microseconds use abs in the answer if you always want positive number of seconds to discover how many seconds into the past timestamp is you can use it like this if seconds difference datetime datetime now timestamp pass
|
QA
|
python date comparisons would like to find out if particular python datetime object is older than hours or minutes am trying to do something similar to if datetime now self timestamp where is either seconds or minutes this generates type error what is the proper way to do date time comparison in python already looked at workingwithtime which is close but not exactly what want assume just want the datetime object represented in seconds so that can do normal int comparison please post lists of datetime best practices
|
compare the difference to timedelta that you create if datetime datetime now timestamp datetime timedelta seconds print older
|
QA
|
python date comparisons would like to find out if particular python datetime object is older than hours or minutes am trying to do something similar to if datetime now self timestamp where is either seconds or minutes this generates type error what is the proper way to do date time comparison in python already looked at workingwithtime which is close but not exactly what want assume just want the datetime object represented in seconds so that can do normal int comparison please post lists of datetime best practices
|
use the datetime timedelta class from datetime import datetime timedelta then datetime now timedelta hours now datetime now now then timedelta days false now then timedelta hours true your example could be written as if datetime now self timestamp timedelta seconds or if datetime now self timestamp timedelta minutes
|
QA
|
python date comparisons would like to find out if particular python datetime object is older than hours or minutes am trying to do something similar to if datetime now self timestamp where is either seconds or minutes this generates type error what is the proper way to do date time comparison in python already looked at workingwithtime which is close but not exactly what want assume just want the datetime object represented in seconds so that can do normal int comparison please post lists of datetime best practices
|
like so self timestamp should be datetime object if datetime now self timestamp seconds print object is over seconds old
|
QA
|
how to pass all visual studio macros to python script note this questions is similar to but not the same as this one visual studio defines several dozen macros which are sort of simulated environment variables completely unrelated to macros which contain information about the build in progress examples configurationname release targetpath work foo win release foo exe vcinstalldir programfiles microsoft visual studio vc here is the complete set of built in macros that see yours may differ depending on which version of vs you use and which tools you have enabled configurationname intdir rootnamespace targetfilename devenvdir outdir safeinputname targetframework frameworkdir parentname safeparentname targetname frameworksdkdir platformname saferootnamespace targetpath frameworkversion projectdir solutiondir vcinstalldir fxcopdir projectext solutionext vsinstalldir inputdir projectfilename solutionfilename webdeploypath inputext projectname solutionname webdeployroot inputfilename projectpath solutionpath windowssdkdir inputname references targetdir windowssdkdiria inputpath remotemachine targetext of these only four frameworkdir frameworksdkdir vcinstalldir and vsinstalldir are set in the environment used for build events as brian mentions user defined macros can be defined such as to be set in the environment in which build tasks execute my problem is with the built in macros use visual studio post build event to run python script as part of my build process would like to pass the entire set of macros built in and user defined to my script in the environment but do not know how within my script can access regular environment variables path systemroot but not these macros all can do now is pass them on by one as named options which then process within my script for example this is what my post build event command line looks like postbuild py targetpath configurationname besides being pain in the neck there is limit on the size of post build event command line so cannot pass dozens macros using this method even if wanted to because the command line is truncated does anyone know if there is way to pass the entire set of macro names and values to command that does not require switching to msbuild which believe is not available for native vc or some other make like build tool
|
this is bit hacky but it could work why not call multiple py scripts in row each scripts can pass in small subset of the parameters and the values to temp text file the final script will read and work off of the temp text file agree that this method is filled with danger and wtf but sometimes you have to just hack stuff together
|
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
|
python mmap module will allow you to insert into file the following sample shows how it can be done in unix windows mmap may be different note that this does not handle all error conditions and you might corrupt or lose the original file also this will not handle unicode strings import os from mmap import mmap def insert filename str pos if len str nothing to insert return open filename mmap fileno os path getsize filename origsize size or this could be an error if pos origsize pos origsize elif pos pos resize origsize len str pos len str pos origsize pos pos len str str close close it is also possible to do this without mmap with files opened in mode but it is less convenient and less efficient as you would have to read and temporarily store the contents of the file from the insertion position to eof which might be huge
|
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
|
if you are looking for something little more abstracted try using sessions believe the way they work is by storing an id in the cookie that matches database record you can store whatever you want in it it is not exactly the same as what you are looking for but it could work if you do not mind small amount of db overhead
|
QA
|
request uac elevation from within python script want my python script to copy files on vista when run it from normal cmd exe window no errors are generated yet the files are not copied if run cmd exe as administator and then run my script it works fine this makes sense since user account control uac normally prevents many file system actions is there way can from within python script invoke uac elevation request those dialogs that say something like such and such app needs admin access is this ok if that is not possible is there way my script can at least detect that it is not elevated so it can fail gracefully
|
it seems there is no way to elevate the application privileges for while for you to perform particular task windows needs to know at the start of the program whether the application requires certain privileges and will ask the user to confirm when the application performs any tasks that need those privileges there are two ways to do this write manifest file that tells windows the application might require some privileges run the application with elevated privileges from inside another program this two articles explain in much more detail how this works what would do if you do not want to write nasty ctypes wrapper for the createelevatedprocess api is use the shellexecuteex trick explained in the code project article pywin comes with wrapper for shellexecute how something like this when your program starts it checks if it has administrator privileges if it does not it runs itself using the shellexecute trick and exits immediately if it does it performs the task at hand as you describe your program as script suppose that is enough for your needs cheers
|
QA
|
style when to serialize django model instance signals vs model save method plan to serialize django model to xml when it is saved or updated the xml going to be imported into flash movie is it better to listen for post save or pre save signal and then perform the serialization or to just handle it in the model save methon
|
post save that way the new data the reason for performing the serialization is already in the database it will make for much cleaner bit of code that simply takes from the database and does not have to worry about adding an extra value the other way that comes to mind is to maintain the xml file in parallel to the database that is to say in your save add the data to the database and to the xml file this would have much less overhead if you are dealing with huge tables
|
QA
|
do have to cause an valueerror in python have this code chars some list try indx chars index chars except valueerror dosomething else dosomethingelse want to be able to do this because do not like knowfully causing exceptions chars some list indx chars index chars if indx dosomething else dosomethingelse is there way can do this
|
if element in mylist index mylist index element do something else do something else
|
QA
|
do have to cause an valueerror in python have this code chars some list try indx chars index chars except valueerror dosomething else dosomethingelse want to be able to do this because do not like knowfully causing exceptions chars some list indx chars index chars if indx dosomething else dosomethingelse is there way can do this
|
note that the latter approach is going against the generally accepted pythonic philosophy of eafp or it is easier to ask for forgiveness than permission while the former follows it
|
QA
|
do have to cause an valueerror in python have this code chars some list try indx chars index chars except valueerror dosomething else dosomethingelse want to be able to do this because do not like knowfully causing exceptions chars some list indx chars index chars if indx dosomething else dosomethingelse is there way can do this
|
for the specific case where your list is sequence of single character strings you can get what you want by changing the list to be searched to string in advance eg join chars you can then use the find method which does work as you want however there is no corresponding method for lists or tuples another possible option is to use dictionary instead eg dict loc for loc in enumerate chars index get chars to find second argument is default if not found this may also perform better if you are doing lot of searches on the list if it is just single search on throwaway list though its not worth doing
|
QA
|
showing the stack trace from running python application have this python application that gets stuck from time to time and cannot find out where is there any way to signal python interpreter to show you the exact code that is running some kind of on the fly stacktrace related questions print current call stack from method in python code check what running process is doing print stack trace of an uninstrumented python program
|
python dv yourscript py that will make the interpreter to run in debug mode and to give you trace of what the interpreter is doing if you want to interactively debug the code you should run it like this python pdb yourscript py that tells the python interpreter to run your script with the module pdb which is the python debugger if you run it like that the interpreter will be executed in interactive mode much like gdb
|
QA
|
showing the stack trace from running python application have this python application that gets stuck from time to time and cannot find out where is there any way to signal python interpreter to show you the exact code that is running some kind of on the fly stacktrace related questions print current call stack from method in python code check what running process is doing print stack trace of an uninstrumented python program
|
the traceback module has some nice functions among them print stack import traceback traceback print stack
|
QA
|
showing the stack trace from running python application have this python application that gets stuck from time to time and cannot find out where is there any way to signal python interpreter to show you the exact code that is running some kind of on the fly stacktrace related questions print current call stack from method in python code check what running process is doing print stack trace of an uninstrumented python program
|
import traceback def print traceback extract stack stdin module none stdin none you can also nicely format the stack trace see the docs edit to simulate java behavior as suggested by douglas leeder add this import signal import traceback signal signal signal sigusr lambda sig stack traceback print stack stack to the startup code in your application then you can print the stack by sending sigusr to the running python 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
|
see two ways of going about it working on python directly or working on something that utilizes python since you are beginner you are probably hesitant to work on the core python language or feel that you cannot contribute in meaningful way which is understandable however as beginner you are in good position to help improve documentation and other items that are essential to learning python for example the python tutorial is less of tutorial in the standard sense and more of feature listing at least in my opinion when tried to learn from it never got the feeling that was building up my knowledge like creating an application it felt more like was being shown all the parts that make up python but not how to put them together into cohesive structure once became more comfortable with the language mostly through books and lots of practice eventually wrote my own tutorial trying to provide not only the technical information but also lessons learned and newbie gotchas alternatively you can contribute to the python world by using python in programs you can contribute to projects already established django pygame etc or you can make your own program to scratch an itch either way you not only build your knowledge of python but you are giving back to the community finally you can become an advocate of python encouraging others to learn the language kept suggesting to my supervisor at my last job to use python rather than java when considering what to use for new project tell everyone know about the joys of python and encourage them to give it try convinced the administrator of computer forum frequent to create section for python and as already said wrote tutorial for python and am working on new one for wxpython there are many ways you can contribute to python that are not necessarily programming related as your programming skills grow you may want to move further into code contributions but you may gain more satisfaction by helping others find the same joy you found in python
|
QA
|
showing the stack trace from running python application have this python application that gets stuck from time to time and cannot find out where is there any way to signal python interpreter to show you the exact code that is running some kind of on the fly stacktrace related questions print current call stack from method in python code check what running process is doing print stack trace of an uninstrumented python program
|
do not know of anything similar to java response to sigquit so you might have to build it in to your application maybe you could make server in another thread that can get stacktrace on response to message of some kind
|
QA
|
showing the stack trace from running python application have this python application that gets stuck from time to time and cannot find out where is there any way to signal python interpreter to show you the exact code that is running some kind of on the fly stacktrace related questions print current call stack from method in python code check what running process is doing print stack trace of an uninstrumented python program
|
there is no way to hook into running python process and get reasonable results what do if processes lock up is hooking strace in and trying to figure out what exactly is happening unfortunately often strace is the observer that fixes race conditions so that the output is useless there too
|
QA
|
translate algorithmic to python would like to translate some code to python code or bytecode the code in question is what would call purely algorithmic platform independent no just algorithms and in memory data structures an example would be regular expression library translation tool would process library source code and produce functionally equivalent python module that can be run in sandboxed environment what specific approaches tools and techniques can you recommend note python extension or ctypes is not an option because the environment is sandboxed another note looks like there is to java bytecode compiler they even compiled libjpeg to java is java bytecode vm too different from cpython bytecode vm
|
why not keeping the code and creating python module which can be imported into running python environment
|
QA
|
translate algorithmic to python would like to translate some code to python code or bytecode the code in question is what would call purely algorithmic platform independent no just algorithms and in memory data structures an example would be regular expression library translation tool would process library source code and produce functionally equivalent python module that can be run in sandboxed environment what specific approaches tools and techniques can you recommend note python extension or ctypes is not an option because the environment is sandboxed another note looks like there is to java bytecode compiler they even compiled libjpeg to java is java bytecode vm too different from cpython bytecode vm
|
first would consider wrapping the existing library with pythonic goodness to provide an api in the form of python module would look at swig ctypes pyrex and whatever else is out there these days the library itself would stay there unchanged saves work but if really had to write original python code based on the there is no tool would use just my brain allows too many funny tricks with pointers clever things with macros etc that would never trust an automated tool even if someone pointed one out to me mentioned pyrex this is language similar to but also python oriented have not done much with it but it could be easier than writing pure python given that you are starting with as guide converting from more constrained tamer languages such as idl the data languages scientists like to use not the other idl is hard requiring manual and mental effort forget it not until the ufo people give us their fancy software tools that are thousand years ahead of our state of the art
|
QA
|
translate algorithmic to python would like to translate some code to python code or bytecode the code in question is what would call purely algorithmic platform independent no just algorithms and in memory data structures an example would be regular expression library translation tool would process library source code and produce functionally equivalent python module that can be run in sandboxed environment what specific approaches tools and techniques can you recommend note python extension or ctypes is not an option because the environment is sandboxed another note looks like there is to java bytecode compiler they even compiled libjpeg to java is java bytecode vm too different from cpython bytecode vm
|
there is frankly no way to mechanically and meaningfully translate to python without suffering an insane performance penalty as we all know python is not anywhere near speed with current compilers and interpreters but worse than that is that what is good at bit fiddling integer math tricks with blocks of memory python is very slow at and what python is good at you cannot express in directly direct translation would therefore be extra inefficient to the point of absurdity the much much better approach in general is indeed to keep the the and wrap it in python extension module using swig pyrex cython or writing wrapper manually or call the library directly using ctypes all the benefits and downsides of for what is already or you add later and all the convenience and downsides of python for any code in python that will not satisfy your sandboxing needs but you should realize that you cannot sandbox python particularly well anyway it takes lot of effort and modification of cpython and if you forget one little hole somewhere your jail is broken if you want to sandbox python you should start by sandboxing the entire process and then extensions can get sandboxed too
|
QA
|
translate algorithmic to python would like to translate some code to python code or bytecode the code in question is what would call purely algorithmic platform independent no just algorithms and in memory data structures an example would be regular expression library translation tool would process library source code and produce functionally equivalent python module that can be run in sandboxed environment what specific approaches tools and techniques can you recommend note python extension or ctypes is not an option because the environment is sandboxed another note looks like there is to java bytecode compiler they even compiled libjpeg to java is java bytecode vm too different from cpython bytecode vm
|
any automatic translation is going to suffer for not using the power of python type procedural code would run very slowly if translated directly into python you would need to profile and replace whole sections with more python optimized code
|
QA
|
translate algorithmic to python would like to translate some code to python code or bytecode the code in question is what would call purely algorithmic platform independent no just algorithms and in memory data structures an example would be regular expression library translation tool would process library source code and produce functionally equivalent python module that can be run in sandboxed environment what specific approaches tools and techniques can you recommend note python extension or ctypes is not an option because the environment is sandboxed another note looks like there is to java bytecode compiler they even compiled libjpeg to java is java bytecode vm too different from cpython bytecode vm
|
the fastest way in terms of programmer effort not efficiency would probably involve using an existing compiler to compile to something simple for example llvm and either interpret that in python exorbitant performance penalty translate that to python huge performance penalty translate that to python bytecode big performance penalty translating to python directly is possible and probably yields faster code than the above approaches but you would be essentially writing compiler backend which is huge task edit afterthought perhaps even more quick and dirty way of doing that is to take the parse tree for the code transform that to python data structure and interpret that in python
|
QA
|
regex to remove conditional comments want regex which can match conditional comments in html source page so can remove only those want to preserve the regular comments would also like to avoid using the notation if possible the text is foo if ie style type text css ul menu ul li font size px font weight normal padding top px style endif bar and want to remove everything in if ie and endif edit it is because of beautifulsoup want to remove these tags beautifulsoup fails to parse and gives an incomplete source edit if ie is not the only condition there are lots more and do not have any list of all possible combinations edit vinko vrsalovic solution works but the actual problem why beautifulsoup failed was because of rogue comment within the conditional comment like if lt ie script defer type text javascript src pngfix js script png fix for ie endif notice the png fix for ie comment though my problem was solve would love to get regex solution for this
|
do not use regular expression for this you will get confused about comments containing opening tags and what not and do the wrong thing html is not regular and trying to modify it with single regular expression will fail use html parser for this beautifulsoup is good easy flexible and sturdy one that is able to handle real world meaning hopelessly broken html with it you can just look up all comment nodes examine their content you can use regular expression for that if you wish and remove them if they need to be removed
|
QA
|
regex to remove conditional comments want regex which can match conditional comments in html source page so can remove only those want to preserve the regular comments would also like to avoid using the notation if possible the text is foo if ie style type text css ul menu ul li font size px font weight normal padding top px style endif bar and want to remove everything in if ie and endif edit it is because of beautifulsoup want to remove these tags beautifulsoup fails to parse and gives an incomplete source edit if ie is not the only condition there are lots more and do not have any list of all possible combinations edit vinko vrsalovic solution works but the actual problem why beautifulsoup failed was because of rogue comment within the conditional comment like if lt ie script defer type text javascript src pngfix js script png fix for ie endif notice the png fix for ie comment though my problem was solve would love to get regex solution for this
|
benoit small correction with multiline turned on if ie endif
|
QA
|
regex to remove conditional comments want regex which can match conditional comments in html source page so can remove only those want to preserve the regular comments would also like to avoid using the notation if possible the text is foo if ie style type text css ul menu ul li font size px font weight normal padding top px style endif bar and want to remove everything in if ie and endif edit it is because of beautifulsoup want to remove these tags beautifulsoup fails to parse and gives an incomplete source edit if ie is not the only condition there are lots more and do not have any list of all possible combinations edit vinko vrsalovic solution works but the actual problem why beautifulsoup failed was because of rogue comment within the conditional comment like if lt ie script defer type text javascript src pngfix js script png fix for ie endif notice the png fix for ie comment though my problem was solve would love to get regex solution for this
|
this works in visual studio where there is no line span option if ie endif
|
QA
|
regex to remove conditional comments want regex which can match conditional comments in html source page so can remove only those want to preserve the regular comments would also like to avoid using the notation if possible the text is foo if ie style type text css ul menu ul li font size px font weight normal padding top px style endif bar and want to remove everything in if ie and endif edit it is because of beautifulsoup want to remove these tags beautifulsoup fails to parse and gives an incomplete source edit if ie is not the only condition there are lots more and do not have any list of all possible combinations edit vinko vrsalovic solution works but the actual problem why beautifulsoup failed was because of rogue comment within the conditional comment like if lt ie script defer type text javascript src pngfix js script png fix for ie endif notice the png fix for ie comment though my problem was solve would love to get regex solution for this
|
from beautifulsoup import beautifulsoup comment html html if ie bloo blee endif html soup beautifulsoup html comments soup findall text lambda text isinstance text comment and text find if this is one line of course comment extract for comment in comments you if ie bloo blee endif print soup prettify html html if your data gets beautifulsoup confused you can fix it before hand or customize the parser among other solutions edit per your comment you just modify the lambda passed to findall as you need modified it
|
QA
|
regex to remove conditional comments want regex which can match conditional comments in html source page so can remove only those want to preserve the regular comments would also like to avoid using the notation if possible the text is foo if ie style type text css ul menu ul li font size px font weight normal padding top px style endif bar and want to remove everything in if ie and endif edit it is because of beautifulsoup want to remove these tags beautifulsoup fails to parse and gives an incomplete source edit if ie is not the only condition there are lots more and do not have any list of all possible combinations edit vinko vrsalovic solution works but the actual problem why beautifulsoup failed was because of rogue comment within the conditional comment like if lt ie script defer type text javascript src pngfix js script png fix for ie endif notice the png fix for ie comment though my problem was solve would love to get regex solution for this
|
here is what you will need endif it will filter out all sorts of conditional comments including if anything endif and if ie endif edit vinko vrsalovic solution works but the actual problem why beautifulsoup failed was because of rogue comment within the conditional comment like notice the comment though my problem was solve would love to get regex solution for this how about this endif do replace on that regular expression leaving or as the replacement know it has and in it see my comment on this post
|
QA
|
tabs versus spaces in python programming have always used tabs for indentation when do python programming but then came across question here on so where someone pointed out that most python programmers use spaces instead of tabs to minimize editor to editor mistakes how does that make difference are there other reasons why one would use spaces instead of tabs for python or is it simply not true should switch my editor to insert spaces instead of tabs right away or keep on going like used to
|
the only inconvenience experience with using spaces instead of tabs is that you cannot easily remove an indentation level you have to remove spaces instead of just one tab
|
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 doctest almost everywhere because like the fact that document and test my functions at the same time have look at this code def throw up something gowrong false throw up fish chips traceback most recent call last exception fish chips throw up fish chips gowrong true feel fine if gowrong return feel fine raise exception something if name main import doctest doctest testmod if you put this example in module and run it from the command line both test cases are evaluated and checked python documentation doctest test interactive python examples
|
QA
|
is there difference between and is in python my google fu has failed me in python are the following two tests for equality equivalent ha test one if print yay test two if is print yay does this hold true for objects where you would be comparing instances list say okay so this kind of answers my question append if print yay holds true but if is print yay does not so tests value where is tests to see if they are the same object
|
determines if the values are equivalent while is determines if they are the exact same object
|
QA
|
is there difference between and is in python my google fu has failed me in python are the following two tests for equality equivalent ha test one if print yay test two if is print yay does this hold true for objects where you would be comparing instances list say okay so this kind of answers my question append if print yay holds true but if is print yay does not so tests value where is tests to see if they are the same object
|
https docs python org library stdtypes html comparisons is tests for identity tests for equality each small integer value is mapped to single value so every is identical and equal this is an implementation detail not part of the language spec though
|
QA
|
is there difference between and is in python my google fu has failed me in python are the following two tests for equality equivalent ha test one if print yay test two if is print yay does this hold true for objects where you would be comparing instances list say okay so this kind of answers my question append if print yay holds true but if is print yay does not so tests value where is tests to see if they are the same object
|
is will return true if two variables point to the same object if the objects referred to by the variables are equal is true true is false true in your case the second test only works because python caches small integer objects which is an implementation detail for larger integers this does not work is false true the same holds true for string literals is true aa is true aa is false aa is intern true please see this question as well
|
QA
|
is there difference between and is in python my google fu has failed me in python are the following two tests for equality equivalent ha test one if print yay test two if is print yay does this hold true for objects where you would be comparing instances list say okay so this kind of answers my question append if print yay holds true but if is print yay does not so tests value where is tests to see if they are the same object
|
your answer is correct the is operator compares the identity of two objects the operator compares the values of two objects an object identity never changes once it has been created you may think of it as the object address in memory you can control comparison behaviour of object values by defining cmp method or rich comparison method like eq
|
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 this is always always the behaviour you want when particular function raises an exception you could use decorator def handle exception handler def decorate func def call function args kwargs try func args kwargs except exception handler return call function return decorate def baz print handle exception baz def foo return handle exception baz def bar return index usage foo unsupported operand type for int and str bar steve cheese substring not found
|
QA
|
showing the stack trace from running python application have this python application that gets stuck from time to time and cannot find out where is there any way to signal python interpreter to show you the exact code that is running some kind of on the fly stacktrace related questions print current call stack from method in python code check what running process is doing print stack trace of an uninstrumented python program
|
have module use for situations like this where process will be running for long time but gets stuck sometimes for unknown and irreproducible reasons its bit hacky and only works on unix requires signals import code traceback signal def debug sig frame interrupt running process and provide python prompt for interactive debugging frame frame allow access to frame object update frame globals unless shadowed by global update frame locals code interactiveconsole message signal received entering python she will ntraceback message join traceback format stack frame interact message def listen signal signal signal sigusr debug register handler to use just call the listen function at some point when your program starts up you could even stick it in site py to have all python programs use it and let it run at any point send the process sigusr signal using kill or in python os kill pid signal sigusr this will cause the program to break to python console at the point it is currently at showing you the stack trace and letting you manipulate the variables use control eof to continue running though note that you will probably interrupt any etc at the point you signal so it is not fully non intrusive have another script that does the same thing except it communicates with the running process through pipe to allow for debugging backgrounded processes etc its bit large to post here but have added it as python cookbook recipe
|
QA
|
how do efficiently filter computed values within python list comprehension the python list comprehension syntax makes it easy to filter values within comprehension for example result for in mylist if type is int will return list of the squares of integers in mylist however what if the test involves some costly computation and you want to filter on the result one option is result expensive for in mylist if expensive this will result in list of non false expensive values however expensive is called twice for each is there comprehension syntax that allows you to do this test while only calling expensive once per
|
this is exactly what generators are suited to handle result expensive for in mylist result do something for in result if some condition result for in result if finally list this makes it totally clear what is happening during each stage of the pipeline explicit over implicit uses generators everywhere until the final step so no large intermediate lists cf generator tricks for system programmers by david beazley
|
QA
|
running subversion under apache and mod python my apache server runs on some non default not root account when it tries to run python script which in turn executes subversion check out command svn checkout fails with the following error message svn cannot open file root subversion servers permission denied at the same time running that python script with subversion checkout command inside from command line under the same user account goes on perfectly well apache server with mod python runs on fedora core machine can anybody help me out thanks lot
|
try granting the apache user the user that the apache service is running under permissions on that file
|
QA
|
running subversion under apache and mod python my apache server runs on some non default not root account when it tries to run python script which in turn executes subversion check out command svn checkout fails with the following error message svn cannot open file root subversion servers permission denied at the same time running that python script with subversion checkout command inside from command line under the same user account goes on perfectly well apache server with mod python runs on fedora core machine can anybody help me out thanks lot
|
it sounds like the environment you apache process is running under is little unusual for whatever reason svn seems to think the user configuration files it needs are in root you can avoid having svn use the root versions of the files by specifying on the command line which config directory to use like so svn config dir home myuser subversion checkout http example com path while not fixing your enviornment it will at least allow you to have your script run properly
|
QA
|
running subversion under apache and mod python my apache server runs on some non default not root account when it tries to run python script which in turn executes subversion check out command svn checkout fails with the following error message svn cannot open file root subversion servers permission denied at the same time running that python script with subversion checkout command inside from command line under the same user account goes on perfectly well apache server with mod python runs on fedora core machine can anybody help me out thanks lot
|
does not apache error log give you clue maybe it has to do with selinux check var log audit audit log and adjust your selinux configuration accordingly if the audit log file indicates that it is selinux which denies apache access
|
QA
|
concurrent access to rrd rrdtool am using rrdtool http oss oetiker ch rrdtool as graphing back end for storing performance metrics this is done via the rrdtool cli from python script my problem is that the script is multithreaded and each thread updates the rrd at pretty rapid pace sometimes an update fails because one thread is accessing the rrd file while another one tries to access it also was under the impression that this is ok to try since rrdtool uses its own locking mechanism but guess that is not true does anyone have good approach for concurrent access to an rrd can think of few ways to go have thread create queue and only feed the rrd from single thread create my own locking mechanism inside the python script how would do this got anything better or have you run into this issue before
|
an exclusive lock ought to be enough for this problem python doc page use example define your lock object at the main level not at the thread level and you are done edit in response to comment if you define your lock lock new lock at the thread level you will have one lock object per running thread and you really want single lock for the file rrdtool updates so this definition must be at the main level
|
QA
|
efficiently match multiple regexes in python lexical analyzers are quite easy to write when you have regexes today wanted to write simple general analyzer in python and came up with import re import sys class token object simple token structure contains the token type value and position def init self type val pos self type type self val val self pos pos def str self return at self type self val self pos class lexererror exception lexer error exception pos position in the input line where the error occurred def init self pos self pos pos class lexer object simple regex based lexer tokenizer see below for an example of usage def init self rules skip whitespace true create lexer rules list of rules each rule is regex type pair where regex is the regular expression used to recognize the token and type is the type of the token to return when it is recognized skip whitespace if true whitespace will be skipped and not reported by the lexer otherwise you have to specify your rules for whitespace or it will be flagged as an error self rules for regex type in rules self rules append re compile regex type self skip whitespace skip whitespace self re ws skip re compile def input self buf initialize the lexer with buffer as input self buf buf self pos def token self return the next token token object found in the input buffer none is returned if the end of the buffer was reached in case of lexing error the current chunk of the buffer matches no rule lexererror is raised with the position of the error if self pos len self buf return none else if self skip whitespace self re ws skip search self buf self pos if self pos start else return none for token regex token type in self rules token regex match self buf self pos if value self buf self pos start self pos end tok token token type value self pos self pos end return tok if we are here no rule matched raise lexererror self pos def tokens self returns an iterator to the tokens found in the buffer while tok self token if tok is none break yield tok if name main rules number za identifier plus minus multiply divide lp rp equals lx lexer rules skip whitespace true lx input erw abc try for tok in lx tokens print tok except lexererror err print lexererror at position err pos it works just fine but am bit worried that it is too inefficient are there any regex tricks that will allow me to write it in more efficient elegant way specifically is there way to avoid looping over all the regex rules linearly to find one that fits
|
re match is anchored you can give it position argument pos end len text while pos end match regexp match text pos do something with your match pos match end have look for pygments which ships shitload of lexers for syntax highlighting purposes with different implementations most based on regular expressions
|
QA
|
efficiently match multiple regexes in python lexical analyzers are quite easy to write when you have regexes today wanted to write simple general analyzer in python and came up with import re import sys class token object simple token structure contains the token type value and position def init self type val pos self type type self val val self pos pos def str self return at self type self val self pos class lexererror exception lexer error exception pos position in the input line where the error occurred def init self pos self pos pos class lexer object simple regex based lexer tokenizer see below for an example of usage def init self rules skip whitespace true create lexer rules list of rules each rule is regex type pair where regex is the regular expression used to recognize the token and type is the type of the token to return when it is recognized skip whitespace if true whitespace will be skipped and not reported by the lexer otherwise you have to specify your rules for whitespace or it will be flagged as an error self rules for regex type in rules self rules append re compile regex type self skip whitespace skip whitespace self re ws skip re compile def input self buf initialize the lexer with buffer as input self buf buf self pos def token self return the next token token object found in the input buffer none is returned if the end of the buffer was reached in case of lexing error the current chunk of the buffer matches no rule lexererror is raised with the position of the error if self pos len self buf return none else if self skip whitespace self re ws skip search self buf self pos if self pos start else return none for token regex token type in self rules token regex match self buf self pos if value self buf self pos start self pos end tok token token type value self pos self pos end return tok if we are here no rule matched raise lexererror self pos def tokens self returns an iterator to the tokens found in the buffer while tok self token if tok is none break yield tok if name main rules number za identifier plus minus multiply divide lp rp equals lx lexer rules skip whitespace true lx input erw abc try for tok in lx tokens print tok except lexererror err print lexererror at position err pos it works just fine but am bit worried that it is too inefficient are there any regex tricks that will allow me to write it in more efficient elegant way specifically is there way to avoid looping over all the regex rules linearly to find one that fits
|
this is not exactly direct answer to your question but you might want to look at antlr according to this document the python code generation target should be up to date as to your regexes there are really two ways to go about speeding it up if you are sticking to regexes the first would be to order your regexes in the order of the probability of finding them in default text you could figure adding simple profiler to the code that collected token counts for each token type and running the lexer on body of work the other solution would be to bucket sort your regexes since your key space being character is relatively small and then use array or dictionary to perform the needed regexes after performing single discrimination on the first character however think that if you are going to go this route you should really try something like antlr which will be easier to maintain faster and less likely to have bugs
|
QA
|
efficiently match multiple regexes in python lexical analyzers are quite easy to write when you have regexes today wanted to write simple general analyzer in python and came up with import re import sys class token object simple token structure contains the token type value and position def init self type val pos self type type self val val self pos pos def str self return at self type self val self pos class lexererror exception lexer error exception pos position in the input line where the error occurred def init self pos self pos pos class lexer object simple regex based lexer tokenizer see below for an example of usage def init self rules skip whitespace true create lexer rules list of rules each rule is regex type pair where regex is the regular expression used to recognize the token and type is the type of the token to return when it is recognized skip whitespace if true whitespace will be skipped and not reported by the lexer otherwise you have to specify your rules for whitespace or it will be flagged as an error self rules for regex type in rules self rules append re compile regex type self skip whitespace skip whitespace self re ws skip re compile def input self buf initialize the lexer with buffer as input self buf buf self pos def token self return the next token token object found in the input buffer none is returned if the end of the buffer was reached in case of lexing error the current chunk of the buffer matches no rule lexererror is raised with the position of the error if self pos len self buf return none else if self skip whitespace self re ws skip search self buf self pos if self pos start else return none for token regex token type in self rules token regex match self buf self pos if value self buf self pos start self pos end tok token token type value self pos self pos end return tok if we are here no rule matched raise lexererror self pos def tokens self returns an iterator to the tokens found in the buffer while tok self token if tok is none break yield tok if name main rules number za identifier plus minus multiply divide lp rp equals lx lexer rules skip whitespace true lx input erw abc try for tok in lx tokens print tok except lexererror err print lexererror at position err pos it works just fine but am bit worried that it is too inefficient are there any regex tricks that will allow me to write it in more efficient elegant way specifically is there way to avoid looping over all the regex rules linearly to find one that fits
|
you can merge all your regexes into one using the operator and let the regex library do the work of discerning between tokens some care should be taken to ensure the preference of tokens for example to avoid matching keyword as an identifier
|
QA
|
is there difference between and is in python my google fu has failed me in python are the following two tests for equality equivalent ha test one if print yay test two if is print yay does this hold true for objects where you would be comparing instances list say okay so this kind of answers my question append if print yay holds true but if is print yay does not so tests value where is tests to see if they are the same object
|
they are completely different is checks for object identity while checks for equality notion that depends on the two operands types it is only lucky coincidence that is seems to work correctly with small integers that is because cpython optimizes the storage of integers in the range to by making them singletons https docs python org api int html pyint fromlong
|
QA
|
which is more preferable to use in python lambda functions or nested functions def mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior here are some trivial examples where they functionally do the same thing if either were found within another function lambda function lambda nested function def return is there advantages to using one over the other performance readability limitations consistency etc does it even matter if does not then does that violate the pythonic principle there should be one and preferably only one obvious way to do it
|
if you need to assign the lambda to name use def instead defs are just syntactic sugar for an assignment so the result is the same and they are lot more flexible and readable lambdas can be used for use once throw away functions which will not have name however this use case is very rare you rarely need to pass around unnamed function objects the builtins map and filter need function objects but list comprehensions and generator expressions are generally more readable than those functions and can cover all use cases without the need of lambdas for the cases you really need small function object you should use the operator module functions like operator add instead of lambda if you still need some lambda not covered you might consider writing def just to be more readable if the function is more complex than the ones at operator module def is probably better so real world good lambda use cases are very rare
|
QA
|
is there difference between and is in python my google fu has failed me in python are the following two tests for equality equivalent ha test one if print yay test two if is print yay does this hold true for objects where you would be comparing instances list say okay so this kind of answers my question append if print yay holds true but if is print yay does not so tests value where is tests to see if they are the same object
|
note that this is why if foo is none is the preferred null comparison for python all null objects are really pointers to the same value which python sets aside to mean none if is true and if is false also work in similar manner false and true are two special objects all true boolean values are true and all false boolean values are false
|
QA
|
which is more preferable to use in python lambda functions or nested functions def mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior here are some trivial examples where they functionally do the same thing if either were found within another function lambda function lambda nested function def return is there advantages to using one over the other performance readability limitations consistency etc does it even matter if does not then does that violate the pythonic principle there should be one and preferably only one obvious way to do it
|
agree with nosklo advice if you need to give the function name use def reserve lambda functions for cases where am just passing brief snippet of code to another function map lambda
|
QA
|
which is more preferable to use in python lambda functions or nested functions def mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior here are some trivial examples where they functionally do the same thing if either were found within another function lambda function lambda nested function def return is there advantages to using one over the other performance readability limitations consistency etc does it even matter if does not then does that violate the pythonic principle there should be one and preferably only one obvious way to do it
|
in this interview guido van rossum says he wishes he had not let lambda into python what feature of python are you least pleased with sometimes have been too quick in accepting contributions and later realized that it was mistake one example would be some of the functional programming features such as lambda functions lambda is keyword that let us you create small anonymous function built in functions such as map filter and reduce run function over sequence type such as list in practice it did not turn out that well python only has two scopes local and global this makes writing lambda functions painful because you often want to access variables in the scope where the lambda was defined but you cannot because of the two scopes there is way around this but it is something of kludge often it seems much easier in python to just use for loop instead of messing around with lambda functions map and friends work well only when there is already built in function that does what you want imho iambdas can be convenient sometimes but usually are convenient at the expense of readibility can you tell me what this does str reduce lambda map lambda range wrote it and it took me minute to figure it out this is from project euler will not say which problem because hate spoilers but it runs in seconds
|
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 perl implementation uses the mmap system call what that call does is establish pointer which to the process appears to be normal segment of memory or buffer to the program it maps the contents of file to region of memory there are performances advantages of doing this vs normal file io read one is that there are no user space library calls necessary to get access to the data another is that there are often less copy operations necessary eg moving data between kernel and user space perl strings and regular expressions are bit byte based as opposed to utf for java for example so perl native character type is the same encoding of the mmapped file when the regular expression engine then operates on the mmap backed variable it is directly accessing the file data via the mamped memory region without going through perl io functions or even libc io functions the mmap is probably largely responsible for the performance difference vs the python version using the normal python io libraries which additionally introduce the overhead of looking for line breaks the perl program also supports to parallelize the processing where the oepen causes fork where the file handle in the parent is to the child stdout the child processes serialize their results to stdout and the parent de serializes them to coordinate and summarize the results
|
QA
|
display number with leading zeros given want to display leading zero for all numbers with less than digits
|
for in print results read more information about string formatting using in the documentation
|
QA
|
display number with leading zeros given want to display leading zero for all numbers with less than digits
|
here you are print basically is like printf or sprint
|
QA
|
display number with leading zeros given want to display leading zero for all numbers with less than digits
|
use format string http docs python org lib typesseq strings html for example python print num num
|
QA
|
python library path in ruby the library path is provided in in perl it is in inc how do you get the list of paths that python searches for modules when you do an import
|
import sys sys path
|
QA
|
python library path in ruby the library path is provided in in perl it is in inc how do you get the list of paths that python searches for modules when you do an import
|
think you are looking for sys path import sys print sys path
|
QA
|
should you always favor xrange over range why or why not
|
xrange is more efficient because instead of generating list of objects it just generates one object at time instead of integers and all of their overhead and the list to put them in you just have one integer at time faster generation better memory use more efficient code unless specifically need list for something always favor xrange
|
QA
|
should you always favor xrange over range why or why not
|
you should favour range over xrange only when you need an actual list for instance when you want to modify the list returned by range or when you wish to slice it for iteration or even just normal indexing xrange will work fine and usually much more efficiently there is point where range is bit faster than xrange for very small lists but depending on your hardware and various other details the break even can be at result of length or not something to worry about prefer xrange
|
QA
|
how to pass all visual studio macros to python script note this questions is similar to but not the same as this one visual studio defines several dozen macros which are sort of simulated environment variables completely unrelated to macros which contain information about the build in progress examples configurationname release targetpath work foo win release foo exe vcinstalldir programfiles microsoft visual studio vc here is the complete set of built in macros that see yours may differ depending on which version of vs you use and which tools you have enabled configurationname intdir rootnamespace targetfilename devenvdir outdir safeinputname targetframework frameworkdir parentname safeparentname targetname frameworksdkdir platformname saferootnamespace targetpath frameworkversion projectdir solutiondir vcinstalldir fxcopdir projectext solutionext vsinstalldir inputdir projectfilename solutionfilename webdeploypath inputext projectname solutionname webdeployroot inputfilename projectpath solutionpath windowssdkdir inputname references targetdir windowssdkdiria inputpath remotemachine targetext of these only four frameworkdir frameworksdkdir vcinstalldir and vsinstalldir are set in the environment used for build events as brian mentions user defined macros can be defined such as to be set in the environment in which build tasks execute my problem is with the built in macros use visual studio post build event to run python script as part of my build process would like to pass the entire set of macros built in and user defined to my script in the environment but do not know how within my script can access regular environment variables path systemroot but not these macros all can do now is pass them on by one as named options which then process within my script for example this is what my post build event command line looks like postbuild py targetpath configurationname besides being pain in the neck there is limit on the size of post build event command line so cannot pass dozens macros using this method even if wanted to because the command line is truncated does anyone know if there is way to pass the entire set of macro names and values to command that does not require switching to msbuild which believe is not available for native vc or some other make like build tool
|
you might want to look into propertysheets these are files containing visual settings including user macros the sheets can inherit from other sheets and are attached to vc projects using the propertymanager view in visual studio when you create one of these sheets there is an interface for creating user macros when you add macro using this mechanism there is checkbox for setting the user macro as an environment variable we use this type of mechanism in our build system to rapidly set up projects to perform out of place builds our various build directories are all defined as user macros have not actually verified that the environment variables are set in an external script called from post build tend to use these macros as command line arguments to my post build scripts but would expect accessing them as environment variables should work for you
|
QA
|
should you always favor xrange over range why or why not
|
go with range for these reasons xrange will be going away in newer python versions this gives you easy future compatibility range will take on the efficiencies associated with xrange
|
QA
|
should you always favor xrange over range why or why not
|
for performance especially when you are iterating over large range xrange is usually better however there are still few cases why you might prefer range in python range does what xrange used to do and xrange does not exist if you want to write code that will run on both python and python you cannot use xrange range can actually be faster in some cases eg if iterating over the same sequence multiple times xrange has to reconstruct the integer object every time but range will have real integer objects it will always perform worse in terms of memory however xrange is not usable in all cases where real list is needed for instance it does not support slices or any list methods edit there are couple of posts mentioning how range will be upgraded by the to tool for the record here is the output of running the tool on some sample usages of range and xrange refactoringtool skipping implicit fixer buffer refactoringtool skipping implicit fixer idioms refactoringtool skipping implicit fixer ws comma range test py original range test py refactored for in range range list range list range for in range for in range xrange range as you can see when used in for loop or comprehension or where already wrapped with list range is left unchanged
|
QA
|
display number with leading zeros given want to display leading zero for all numbers with less than digits
|
in python you would use the format string method for in print num format num or using the built in for single number print format see the pep documentation for the new formatting functions
|
QA
|
should you always favor xrange over range why or why not
|
range returns list xrange returns an xrange object xrange is bit faster and bit more memory efficient but the gain is not very large the extra memory used by list is of course not just wasted lists have more functionality slice repeat insert exact differences can be found in the documentation there is no bonehard rule use what is needed python is still in development but iirc range will very similar to xrange of and list range can be used to generate lists
|
QA
|
reading bit packed binary data on bit system am attempting to write python extension that reads packed binary data it is stored as structs of structs and then parses it out into python objects everything works as expected on bit machine the binary files are always written on bit architecture but not on bit box is there preferred way of doing this it would be lot of code to post but as an example struct word version bool upgrade time time time time apparms file fp fp fopen filepath fread apparms sizeof apparms fp return py buildvalue sysversion apparms version powerfailtime apparms time normkitexpdate apparms time now on bit system this works great but on bit my time sizes are different bit vs bit longs damn you people are fast patrick originally started using the struct package but found it just way to slow for my needs plus was looking for an excuse to write python extension know this is stupid question but what types do need to watch out for thanks
|
what is your code for reading the binary data make sure you are copying the data into properly sized types like int instead of just int
|
QA
|
reading bit packed binary data on bit system am attempting to write python extension that reads packed binary data it is stored as structs of structs and then parses it out into python objects everything works as expected on bit machine the binary files are always written on bit architecture but not on bit box is there preferred way of doing this it would be lot of code to post but as an example struct word version bool upgrade time time time time apparms file fp fp fopen filepath fread apparms sizeof apparms fp return py buildvalue sysversion apparms version powerfailtime apparms time normkitexpdate apparms time now on bit system this works great but on bit my time sizes are different bit vs bit longs damn you people are fast patrick originally started using the struct package but found it just way to slow for my needs plus was looking for an excuse to write python extension know this is stupid question but what types do need to watch out for thanks
|
why are not you using the struct package
|
QA
|
python library path in ruby the library path is provided in in perl it is in inc how do you get the list of paths that python searches for modules when you do an import
|
you can also make additions to this path with the pythonpath environment variable at runtime in addition to import sys sys path append home user python libs
|
QA
|
reading bit packed binary data on bit system am attempting to write python extension that reads packed binary data it is stored as structs of structs and then parses it out into python objects everything works as expected on bit machine the binary files are always written on bit architecture but not on bit box is there preferred way of doing this it would be lot of code to post but as an example struct word version bool upgrade time time time time apparms file fp fp fopen filepath fread apparms sizeof apparms fp return py buildvalue sysversion apparms version powerfailtime apparms time normkitexpdate apparms time now on bit system this works great but on bit my time sizes are different bit vs bit longs damn you people are fast patrick originally started using the struct package but found it just way to slow for my needs plus was looking for an excuse to write python extension know this is stupid question but what types do need to watch out for thanks
|
the struct module should be able to do this although alignment of structs in the middle of the data is always an issue it is not very hard to get it right however find out once what boundary the structs in structs align to then pad manually with the specifier to that boundary you can doublecheck your padding by comparing struct calcsize with your actual data it is certainly easier than writing extension for it in order to keep using py buildvalue like that you have two options you can determine the size of time at compiletime in terms of fundamental types so an int or long or an ssize and then use the right format character to py buildvalue for an int for long for an ssize or you can use pyint fromssize manually in which case the compiler does the upcasting for you and then use the of format characters to pass the result to py buildvalue
|
QA
|
run pylons controller as separate app have pylons app where would like to move some of the logic to separate batch process have been running it under the main app for testing but it is going to be doing lot of work in the database and would like it to be separate process that will be running in the background constantly the main pylons app will submit jobs into the database and the new process will do the work requested in each job how can launch controller as stand alone script currently have from warehouse controllers import importserver importserver runserver and in the controller file but not part of the controller class def runserver sleep secs try imp importservercontroller while true imp runimport sleepfor sleep secs except exception log info unexpected error sys exc info log info but starting importserver py on the command line results in could not locate bind configured on mapper mapper mportjob imports sql expression or this session
|
am redacting my response and upvoting the other answer by ben bangert as it is the correct one answered and have since learned the correct way mentioned below if you really want to check out the history of this answer to see the wrong but working solution originally proposed
|
QA
|
reading bit packed binary data on bit system am attempting to write python extension that reads packed binary data it is stored as structs of structs and then parses it out into python objects everything works as expected on bit machine the binary files are always written on bit architecture but not on bit box is there preferred way of doing this it would be lot of code to post but as an example struct word version bool upgrade time time time time apparms file fp fp fopen filepath fread apparms sizeof apparms fp return py buildvalue sysversion apparms version powerfailtime apparms time normkitexpdate apparms time now on bit system this works great but on bit my time sizes are different bit vs bit longs damn you people are fast patrick originally started using the struct package but found it just way to slow for my needs plus was looking for an excuse to write python extension know this is stupid question but what types do need to watch out for thanks
|
explicitly specify that your data types integers are bit otherwise if you have two integers next to each other when you read them they will be read as one bit integer when you are dealing with cross platform issues the two main things to watch out for are bitness if your packed data is written with bit ints then all of your code must explicitly specify bit ints when reading and writing byte order if you move your code from intel chips to ppc or sparc your byte order will be wrong you will have to import your data and then byte flip it so that it matches up with the current architecture otherwise will be read as hopefully this helps
|
QA
|
how can closely achieve from in python in could easily write the following string stringvalue string isnullorempty otherstring defaultstring otherstring is there quick way of doing the same thing in python or am stuck with an if statement
|
in python there is if else which behaves lot like in however it is frowned upon for two reasons readability and the fact that there is usually simpler way to approach the problem for instance in your case stringvalue otherstring or defaultstring
|
QA
|
how can closely achieve from in python in could easily write the following string stringvalue string isnullorempty otherstring defaultstring otherstring is there quick way of doing the same thing in python or am stuck with an if statement
|
it is never bad thing to write readable expressive code if otherstring stringvalue otherstring else stringvalue defaultstring this type of code is longer and more expressive but also more readable and less likely to get tripped over or mis edited down the road do not be afraid to write expressively readable code should be goal not byproduct
|
QA
|
which is more preferable to use in python lambda functions or nested functions def mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior here are some trivial examples where they functionally do the same thing if either were found within another function lambda function lambda nested function def return is there advantages to using one over the other performance readability limitations consistency etc does it even matter if does not then does that violate the pythonic principle there should be one and preferably only one obvious way to do it
|
the primary use of lambda has always been for simple callback functions and for map reduce filter which require function as an argument with list comprehensions becoming the norm and the added allowed if as in for in range if it is hard to imagine real case for the use of lambda in daily use as result would say avoid lambda and create nested functions
|
QA
|
reading bit packed binary data on bit system am attempting to write python extension that reads packed binary data it is stored as structs of structs and then parses it out into python objects everything works as expected on bit machine the binary files are always written on bit architecture but not on bit box is there preferred way of doing this it would be lot of code to post but as an example struct word version bool upgrade time time time time apparms file fp fp fopen filepath fread apparms sizeof apparms fp return py buildvalue sysversion apparms version powerfailtime apparms time normkitexpdate apparms time now on bit system this works great but on bit my time sizes are different bit vs bit longs damn you people are fast patrick originally started using the struct package but found it just way to slow for my needs plus was looking for an excuse to write python extension know this is stupid question but what types do need to watch out for thanks
|
you need to make sure you are using architecture independent members for your struct for instance an int may be bits on one architecture and bits on another as others have suggested use the int style types instead if your struct contains unaligned members you may need to deal with padding added by the compiler too another common problem with cross architecture data is endianness intel architecture is little endian but if you are reading on completely different machine an alpha or sparc you will have to worry about this too the python struct module deals with both these situations using the prefix passed as part of the format string use native size endianness and alignment sizeof int sizeof long use native endianness but standard sizes and alignment bits bits little endian standard sizes alignment big endian standard sizes alignment in general if the data passes off your machine you should nail down the endianness and the size padding format to something specific ie use or as your format if you want to handle this in your extension you may need to add some code to handle it
|
QA
|
efficiently match multiple regexes in python lexical analyzers are quite easy to write when you have regexes today wanted to write simple general analyzer in python and came up with import re import sys class token object simple token structure contains the token type value and position def init self type val pos self type type self val val self pos pos def str self return at self type self val self pos class lexererror exception lexer error exception pos position in the input line where the error occurred def init self pos self pos pos class lexer object simple regex based lexer tokenizer see below for an example of usage def init self rules skip whitespace true create lexer rules list of rules each rule is regex type pair where regex is the regular expression used to recognize the token and type is the type of the token to return when it is recognized skip whitespace if true whitespace will be skipped and not reported by the lexer otherwise you have to specify your rules for whitespace or it will be flagged as an error self rules for regex type in rules self rules append re compile regex type self skip whitespace skip whitespace self re ws skip re compile def input self buf initialize the lexer with buffer as input self buf buf self pos def token self return the next token token object found in the input buffer none is returned if the end of the buffer was reached in case of lexing error the current chunk of the buffer matches no rule lexererror is raised with the position of the error if self pos len self buf return none else if self skip whitespace self re ws skip search self buf self pos if self pos start else return none for token regex token type in self rules token regex match self buf self pos if value self buf self pos start self pos end tok token token type value self pos self pos end return tok if we are here no rule matched raise lexererror self pos def tokens self returns an iterator to the tokens found in the buffer while tok self token if tok is none break yield tok if name main rules number za identifier plus minus multiply divide lp rp equals lx lexer rules skip whitespace true lx input erw abc try for tok in lx tokens print tok except lexererror err print lexererror at position err pos it works just fine but am bit worried that it is too inefficient are there any regex tricks that will allow me to write it in more efficient elegant way specifically is there way to avoid looping over all the regex rules linearly to find one that fits
|
it is possible that combining the token regexes will work but you would have to benchmark it something like re compile number var match groupdict var none number if token for in items if none the filter is where you will have to do some benchmarking update tested this and it seems as though if you combine all the tokens as stated and write function like def find token lst for tok in lst if tok none return tok raise exception you will get roughly the same speed maybe teensy faster for this believe the speedup must be in the number of calls to match but the loop for token discrimination is still there which of course kills it
|
QA
|
how can closely achieve from in python in could easily write the following string stringvalue string isnullorempty otherstring defaultstring otherstring is there quick way of doing the same thing in python or am stuck with an if statement
|
dan if otherstring stringvalue otherstring else stringvalue defaultstring this type of code is longer and more expressive but also more readable well yes it is longer not so sure about more expressive and more readable at the very least your claim is disputable would even go as far as saying it is downright wrong for two reasons first your code emphasizes the decision making rather extremely onthe other hand the conditional operator emphasizes something else namely the value resp the assignment of said value and this is exactly what the writer of this code wants the decision making is really rather by product of the code the important part here is the assignment operation your code hides this assignment in lot of syntactic noise the branching your code is less expressive because it shifts the emphasis from the important part even then your code would probably trump some obscure ascii art like an inline if would be preferable personally do not like the variant introduced with python because it is backwards would prefer something that reads in the same flow direction as the ternary operator but uses words instead of ascii characters if cond then else this wins hands down and unfortunately do not have such an expressive statement but and this is the second argument the ternary conditional operator of languages is so long established that it has become an idiom in itself the ternary operator is as much part of the language as the conventional if statement because it is an idiom anybody who knows the language immediately reads this code right furthermore it is an extremely short concise way of expressing these semantics in fact it is the shortest imaginable way it is extremely expressive because it does not obscure the essence with needless noise finally jeff atwood has written the perfect conclusion to this the best code is no code at all
|
QA
|
how can closely achieve from in python in could easily write the following string stringvalue string isnullorempty otherstring defaultstring otherstring is there quick way of doing the same thing in python or am stuck with an if statement
|
by the way rd you do not please do not write code like this in apart from the fact that the isdefaultornull is actually called isnullorempty this is pure code bloat offers the coalesce operator for situations like these string stringvalue otherstring defaultstring it is true that this only works if otherstring is null rather than empty but if this can be ensured beforehand and often it can it makes the code much more readable
|
QA
|
should you always favor xrange over range why or why not
|
okay everyone here as different opinion as to the tradeoffs and advantages of xrange versus range they are mostly correct xrange is an iterator and range fleshes out and creates an actual list for the majority of cases you will not really notice difference between the two you can use map with range but not with xrange but it uses up more memory what think you rally want to hear however is that the preferred choice is xrange since range in python is an iterator the code conversion tool to will correctly convert all uses of xrange to range and will throw out an error or warning for uses of range if you want to be sure to easily convert your code in the future you will use xrange only and list xrange when you are sure that you want list learned this during the cpython sprint at pycon this year in chicago
|
QA
|
should you always favor xrange over range why or why not
|
no they both have their uses use xrange when iterating as it saves memory say for in xrange one zillion rather than for in range one zillion on the other hand use range if you actually want list of numbers multiples of seven range print multiples of seven multiples of seven
|
QA
|
how many bytes per element are there in python list tuple for example how much memory is required to store list of one million bit integers alist range or list range in python
|
it depends python allocates space for lists in such way as to achieve amortized constant time for appending elements to the list in practice what this means with the current implementation is the list always has space allocated for power of two number of elements so range will actually allocate list big enough to hold elements million this is only the space required to store the list structure itself which is an array of pointers to the python objects for each element bit system will require bytes per element bit system will use bytes per element furthermore you need space to store the actual elements this varies widely for small integers to currently no additional space is needed but for larger numbers python allocates new object for each integer which takes bytes and tends to fragment memory bottom line it is complicated and python lists are not good way to store large homogeneous data structures for that use the array module or if you need to do vectorized math use numpy ps tuples unlike lists are not designed to have elements progressively appended to them do not know how the allocator works but do not even think about using it for large data structures
|
QA
|
how do you translate this regular expression idiom from perl into python switched from perl to python about year ago and have not looked back there is only one idiom that have ever found can do more easily in perl than in python if var foo do something with elsif var bar do something with elsif var baz do something with the corresponding python code is not so elegant since the if statements keep getting nested re search foo var if do something with group else re search bar var if do something with group else re search baz var if do something with group does anyone have an elegant way to reproduce this pattern in python have seen anonymous function dispatch tables used but those seem kind of unwieldy to me for small number of regular expressions
|
this is an extension of the re module it stores the last successful match object and let us you access it is methods and attributes via this module this module exports the following additional functions expand return the string obtained by doing backslash substitution on template string group returns one or more subgroups of the match groups return tuple containing all the subgroups of the match start return the indices of the start of the substring matched by group end return the indices of the end of the substring matched by group span returns tuple of start end of the substring matched by group this module defines the following additional public attributes pos the value of pos which was passed to the search or match method endpos the value of endpos which was passed to the search or match method lastindex the integer index of the last matched capturing group lastgroup the name of the last matched capturing group re the regular expression object which as passed to search or match string the string passed to match or search import re as re from re import from functools import wraps all re all expand group groups start end span last match pos endpos lastindex lastgroup re string last match pos endpos lastindex lastgroup re string none def set match match none global last match pos endpos lastindex lastgroup re string if match is not none last match match pos match pos endpos match endpos lastindex match lastindex lastgroup match lastgroup re match re string match string return match wraps re match def match pattern string flags return set match re match pattern string flags wraps re search def search pattern string flags return set match re search pattern string flags wraps re findall def findall pattern string flags matches re findall pattern string flags if matches set match matches return matches wraps re finditer def finditer pattern string flags for match in re finditer pattern string flags yield set match match def expand template if last match is none raise typeerror no successful match yet return last match expand template def group indices if last match is none raise typeerror no successful match yet return last match group indices def groups default none if last match is none raise typeerror no successful match yet return last match groups default def groupdict default none if last match is none raise typeerror no successful match yet return last match groupdict default def start group if last match is none raise typeerror no successful match yet return last match start group def end group if last match is none raise typeerror no successful match yet return last match end group def span group if last match is none raise typeerror no successful match yet return last match span group del wraps not needed past module compilation for example if gre match foo var do something with gre group elif gre match bar var do something with gre group elif gre match baz var do something with gre group
|
QA
|
how many bytes per element are there in python list tuple for example how much memory is required to store list of one million bit integers alist range or list range in python
|
this is implementation specific am pretty sure certainly it depends on the internal representation of integers you cannot assume they will be stored as bit since python gives you arbitrarily large integers so perhaps small ints are stored more compactly on my python on fedora on core duo the vmsize before allocation is kb after is kb after one more million element assignment vmsize goes to kb this very grossly indicates around kb for integers which is around bytes per integer that suggests lot of overhead for the list would take these numbers with large pinch of salt
|
QA
|
which is more preferable to use in python lambda functions or nested functions def mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior here are some trivial examples where they functionally do the same thing if either were found within another function lambda function lambda nested function def return is there advantages to using one over the other performance readability limitations consistency etc does it even matter if does not then does that violate the pythonic principle there should be one and preferably only one obvious way to do it
|
agree with nosklo by the way even with use once throw away function most of the time you just want to use something from the operator module you have function with this signature myfunction data callback function you want to pass function that add elements using lambda myfunction data lambda the pythonic way import operator myfunction data operator add or course this is simple example but there is lot of stuff the operator module provides including the items setters getters for list and dict really cool
|
QA
|
translate algorithmic to python would like to translate some code to python code or bytecode the code in question is what would call purely algorithmic platform independent no just algorithms and in memory data structures an example would be regular expression library translation tool would process library source code and produce functionally equivalent python module that can be run in sandboxed environment what specific approaches tools and techniques can you recommend note python extension or ctypes is not an option because the environment is sandboxed another note looks like there is to java bytecode compiler they even compiled libjpeg to java is java bytecode vm too different from cpython bytecode vm
|
would personnaly use tool to extract an uml sheme from the code then use it to generate python code from this squeleton start to get rid of the uncessary style structures and then would fill the methods with python code think it would be the safer and yet most efficient way
|
QA
|
python swig vs ctypes in python under what circumstances is swig better choice than ctypes for calling entry points in shared libraries let us assume you do not already have the swig interface file what are the performance metrics of the two
|
ctypes is very cool and much easier than swig but it has the drawback that poorly or malevolently written python code can actually crash the python process you should also consider boost python imho it is actually easier than swig while giving you more control over the final python interface if you are using anyway you also do not add any other languages to your mix
|
QA
|
how do use django core urlresolvers reverse with function reference instead of named url pattern in my urls py file have from myapp import views categories views categories where categories is view function inside myapp views py no other urlconf lines reference views categories in unit test file trying to grab this url using django core urlresolvers reverse instead of just copying categories dry and all that so have from django core urlresolvers import reverse from myapp import views url reverse views categories when run my tests get noreversematch error noreversematch reverse for function categories at with arguments and keyword arguments not found it matches just fine if make the url pattern named pattern like this url categories views categories myapp categories and use the pattern name to match it url reverse myapp categories but as far as can tell from the reverse documentation shouldn need to make it named url pattern just to use reverse any ideas what doing wrong
|
this does work and all the code that you have pasted is correct and works fine just copied it into clean test project app and it reversed the url without any problem so there is something else going on here that you have not showed us simplify down to the bare bones basics until it works then start adding complexity back in and see where it is breaking also you can do manage py she will and then interactively import the reverse function and your view function and try the reverse that will remove the test setup as possible because
|
QA
|
how can closely achieve from in python in could easily write the following string stringvalue string isnullorempty otherstring defaultstring otherstring is there quick way of doing the same thing in python or am stuck with an if statement
|
also discovered that just using the or operator does pretty well for instance finalstring get override or defaultstring if get override returns or none it will always use defaultstring
|
QA
|
regex to remove conditional comments want regex which can match conditional comments in html source page so can remove only those want to preserve the regular comments would also like to avoid using the notation if possible the text is foo if ie style type text css ul menu ul li font size px font weight normal padding top px style endif bar and want to remove everything in if ie and endif edit it is because of beautifulsoup want to remove these tags beautifulsoup fails to parse and gives an incomplete source edit if ie is not the only condition there are lots more and do not have any list of all possible combinations edit vinko vrsalovic solution works but the actual problem why beautifulsoup failed was because of rogue comment within the conditional comment like if lt ie script defer type text javascript src pngfix js script png fix for ie endif notice the png fix for ie comment though my problem was solve would love to get regex solution for this
|
would simply go with import re html fjlk wb dsqfjqdsmlkf fdsijfmldsqjfl fjdslmfkqsjf fdjslmjkqfs if lt ie script defer type text javascript src pngfix js script png fix for ie endif fjlk wb dsqfjqdsmlkf fdsijfmldsqjfl fjdslmfkqsjf fdjslmjkqfs here the black magic occurs whithout clean html join re split endif html print clean html fjlk wb dsqfjqdsmlkf fdsijfmldsqjfl fjdslmfkqsjf fdjslmjkqfs fjlk wb dsqfjqdsmlkf fdsijfmldsqjfl fjdslmfkqsjf fdjslmjkqfs will match any char that is not this is really useful since it is lightning fast and this char can be found on any keyboard but the trick is it is really hard to type no one will type it by mistake and nobody uses it it is generical money devise char if you do not feel like using however you can use chr to generate the system bell char wich is unprintable and cannot be found in web page
|
QA
|
python swig vs ctypes in python under what circumstances is swig better choice than ctypes for calling entry points in shared libraries let us assume you do not already have the swig interface file what are the performance metrics of the two
|
swig generates rather ugly or code it is straightforward to use for simple functions things that can be translated directly and reasonably easy to use for more complex functions such as functions with output parameters that need an extra translation step to represent in python for more powerful interfacing you often need to write bits of as part of the interface file for anything but simple use you will need to know about cpython and how it represents objects not hard but something to keep in mind ctypes allows you to directly access functions structures and other data and load arbitrary shared libraries you do not need to write any for this but you do need to understand how works it is you could argue the flip side of swig it does not generate code and it does not require compiler at runtime but for anything but simple use it does require that you understand how things like datatypes casting memory management and alignment work you also need to manually or automatically translate structs unions and arrays into the equivalent ctypes datastructure including the right memory layout it is likely that in pure execution swig is faster than ctypes because the management around the actual work is done in at compiletime rather than in python at runtime however unless you interface lot of different functions but each only few times it is unlikely the overhead will be really noticeable in development time ctypes has much lower startup cost you do not have to learn about interface files you do not have to generate files and compile them you do not have to check out and silence warnings you can just jump in and start using single function with minimal effort then expand it to more and you get to test and try things out directly in the python interpreter wrapping lots of code is somewhat tedious although there are attempts to make that simpler like ctypes configure swig on the other hand can be used to generate wrappers for multiple languages barring language specific details that need filling in like the custom code mentioned above when wrapping lots and lots of code that swig can handle with little help the code generation can also be lot simpler to set up than the ctypes equivalents
|
QA
|
python swig vs ctypes in python under what circumstances is swig better choice than ctypes for calling entry points in shared libraries let us assume you do not already have the swig interface file what are the performance metrics of the two
|
you can also use pyrex which can act as glue between high level python code and low level code lxml is written in pyrex for instance
|
QA
|
how many bytes per element are there in python list tuple for example how much memory is required to store list of one million bit integers alist range or list range in python
|
useful links how to get memory size usage of python object memory sizes of python objects if you put data into dictionary how do we calculate the data size however they do not give definitive answer the way to go measure memory consumed by python interpreter with without the list use os tools use third party extension module which defines some sort of sizeof pyobject update recipe size of python objects revised import asizeof print asizeof asizeof range python winxp bit linux bit linux
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.