prefix
stringclasses
1 value
input_text
stringlengths
19
27.3k
target_text
stringlengths
2
24.8k
QA
writing domain specific language for selecting rows from table am writing server that expect to be run by many different people not all of whom will have direct contact with the servers will communicate with each other in cluster part of the server functionality involves selecting small subset of rows from potentially very large table the exact choice of what rows are selected will need some tuning and it is important that it is possible for the person running the cluster eg myself to update the selection criteria without getting each and every server administrator to deploy new version of the server simply writing the function in python is not really an option since nobody is going to want to install server that downloads and executes arbitrary python code at runtime what need are suggestions on the simplest way to implement domain specific language to achieve this goal the language needs to be capable of simple expression evaluation as well as querying table indexes and iterating through the returned rows ease of writing and reading the language is secondary to ease of implementing it would also prefer not to have to write an entire query optimiser so something that explicitly specifies what indexes to query would be ideal the interface that this will have to compile against will be similar in capabilities to what the app engine datastore exports you can query for sequential ranges on any index on the table eg less than greater than range and equality queries then filter the returned row by any boolean expression you can also concatenate multiple independent result sets together realise this question sounds lot like am asking for sql however do not want to require that the datastore backing this data be relational database and do not want the overhead of trying to reimplement sql myself am also dealing with only single table with known schema finally no joins will be required something much simpler would be far preferable edit expanded description to clear up some misconceptions
think we are going to need bit more information here let me know if any of the following is based on incorrect assumptions first of all as you pointed out yourself there already exists dsl for selecting rows from arbitrary tables it is called sql since you do not want to reinvent sql am assuming that you only need to query from single table with fixed format if this is the case you probably do not need to implement dsl although that is certainly one way to go it may be easier if you are used to object orientation to create filter object more specifically filter collection that would hold one or more selectioncriterion objects you can implement these to inherit from one or more base classes representing types of selections range lessthan exactmatch like etc once these base classes are in place you can create column specific inherited versions which are appropriate to that column finally depending on the complexity of the queries you want to support you will want to implement some kind of connective glue to handle and and or and not linkages between the various criteria if you feel like it you can create simple gui to load up the collection would look at the filtering in excel as model if you do not have anything else in mind finally it should be trivial to convert the contents of this collection to the corresponding sql and pass that to the database however if what you are after is simplicity and your users understand sql you could simply ask them to type in the contents of where clause and programmatically build up the rest of the query from security perspective if your code has control over the columns selected and the from clause and your database permissions are set properly and you do some sanity checking on the string coming in from the users this would be relatively safe option
QA
writing domain specific language for selecting rows from table am writing server that expect to be run by many different people not all of whom will have direct contact with the servers will communicate with each other in cluster part of the server functionality involves selecting small subset of rows from potentially very large table the exact choice of what rows are selected will need some tuning and it is important that it is possible for the person running the cluster eg myself to update the selection criteria without getting each and every server administrator to deploy new version of the server simply writing the function in python is not really an option since nobody is going to want to install server that downloads and executes arbitrary python code at runtime what need are suggestions on the simplest way to implement domain specific language to achieve this goal the language needs to be capable of simple expression evaluation as well as querying table indexes and iterating through the returned rows ease of writing and reading the language is secondary to ease of implementing it would also prefer not to have to write an entire query optimiser so something that explicitly specifies what indexes to query would be ideal the interface that this will have to compile against will be similar in capabilities to what the app engine datastore exports you can query for sequential ranges on any index on the table eg less than greater than range and equality queries then filter the returned row by any boolean expression you can also concatenate multiple independent result sets together realise this question sounds lot like am asking for sql however do not want to require that the datastore backing this data be relational database and do not want the overhead of trying to reimplement sql myself am also dealing with only single table with known schema finally no joins will be required something much simpler would be far preferable edit expanded description to clear up some misconceptions
it really sounds like sql but perhaps it is worth to try using sqlite if you want to keep it simple
QA
authenticating against active directory using python ldap how do authenticate against ad using python ldap am currently using the python ldap library and all it is producing is tears cannot even bind to perform simple query import sys import ldap server ldap my ldap server dn secret un sys argv base dc mydomain dc co dc uk scope ldap scope subtree filter objectclass user samaccountname un attrs displayname ldap initialize server protocol version print simple bind dn secret are search base scope filter attrs type user result name attrs user if hasattr attrs has key and attrs has key displayname displayname attrs displayname print displayname sys exit running this with myusername mydomain co uk password username gives me one of two errors invalid credentials when mistype or intentionally use wrong credentials it fails to authenticate ldap invalid credentials info ldaperr dsid comment acceptsecuritycontext error data vece desc invalid credentials or ldap operations error info ldaperr dsid comment in order to perform this operation successful bind must be completed on the connection data vece desc operations error what am missing out to bind properly am getting the same errors on fedora and windows
was missing set option ldap opt referrals from the init
QA
authenticating against active directory using python ldap how do authenticate against ad using python ldap am currently using the python ldap library and all it is producing is tears cannot even bind to perform simple query import sys import ldap server ldap my ldap server dn secret un sys argv base dc mydomain dc co dc uk scope ldap scope subtree filter objectclass user samaccountname un attrs displayname ldap initialize server protocol version print simple bind dn secret are search base scope filter attrs type user result name attrs user if hasattr attrs has key and attrs has key displayname displayname attrs displayname print displayname sys exit running this with myusername mydomain co uk password username gives me one of two errors invalid credentials when mistype or intentionally use wrong credentials it fails to authenticate ldap invalid credentials info ldaperr dsid comment acceptsecuritycontext error data vece desc invalid credentials or ldap operations error info ldaperr dsid comment in order to perform this operation successful bind must be completed on the connection data vece desc operations error what am missing out to bind properly am getting the same errors on fedora and windows
use distinguished name to log on your system cn your user cn users dc dc local it should work on any ldap system including ad
QA
regular expressions but for writing in the match when using regular expressions we generally if not always use them to extract some kind of information what need is to replace the match value with some other value right now am doing this def getexpandedtext pattern text replacevalue one liner really ugly but it is only used in here return text replace text text find re findall pattern text replacevalue text text find re findall pattern text len replacevalue so if do sth like getexpandedtext aaa bbb hola aaaiiibbb como estas ooo hola aaaooobbb como estas it changes the with ooo do you guys know whether with python regular expressions we can do this thanks lot guys
if you want to continue using the syntax you mentioned replace the match value instead of replacing the part that did not match and considering you will only have one group you could use the code below def getexpandedtext pattern text replacevalue re search pattern text expandedtext text start replacevalue text end return expandedtext
QA
looking for file traversal functions in python that are like java in java you can do file listfiles and receive all of the files in directory you can then easily recurse through directory trees is there an analogous way to do this in python
straight from python refererence library import glob glob glob gif txt glob glob gif gif card gif glob glob gif gif
QA
looking for file traversal functions in python that are like java in java you can do file listfiles and receive all of the files in directory you can then easily recurse through directory trees is there an analogous way to do this in python
try listdir in the os module docs import os print os listdir
QA
looking for file traversal functions in python that are like java in java you can do file listfiles and receive all of the files in directory you can then easily recurse through directory trees is there an analogous way to do this in python
take look at os walk and the examples here with os walk you can easily process whole directory tree an example from the link above delete everything reachable from the directory named in top assuming there are no symbolic links caution this is dangerous for example if top it could delete all your disk files import os for root dirs files in os walk top topdown false for name in files os remove os path join root name for name in dirs os rmdir os path join root name
QA
looking for file traversal functions in python that are like java in java you can do file listfiles and receive all of the files in directory you can then easily recurse through directory trees is there an analogous way to do this in python
yes there is the python way is even better there are three possibilities like file listfiles python has the function os listdir path it works like the java method pathname pattern expansion with glob the module glob contains functions to list files on the file system using unix she will like pattern files glob glob usr joe gif file traversal with walk really nice is the os walk function of python the walk method returns generation function that recursively list all directories and files below given starting path an example import os from os path import join for root dirs files in os walk usr print current directory root print sub directories dirs print files files you can even on the fly remove directories from dirs to avoid walking to that dir if joe in dirs dirs remove joe to avoid walking into directories called joe listdir and walk are documented here glob is documented here
QA
looking for file traversal functions in python that are like java in java you can do file listfiles and receive all of the files in directory you can then easily recurse through directory trees is there an analogous way to do this in python
use os path walk if you want subdirectories as well walk top func arg directory tree walk with callback function for each directory in the directory tree rooted at top including top itself but excluding and call func arg dirname fnames dirname is the name of the directory and fnames list of the names of the files and subdirectories in dirname excluding and func may modify the fnames list in place via del or slice assignment and walk will only recurse into the subdirectories whose names remain in fnames this can be used to implement filter or to impose specific order of visiting no semantics are defined for or required of arg beyond that arg is always passed to func it can be used to pass filename pattern or mutable object designed to accumulate statistics passing none for arg is common
QA
can regex be used for this particular string manipulation need to replace character say with character say in string but only if it is contained in quoted substring an example makes it clearer axbx cxdxe fxgh ixj axbx cpdpe fxgh ipj let us assume for the sake of simplicity that quotes always come in pairs the obvious way is to just process the string one character at time simple state machine approach however am wondering if regular expressions can be used to do all the processing in one go my target language is but guess my question pertains to any language having builtin or library support for regular expressions
usr bin perl use strict break up the string the spliting uses quotes as the delimiter put every broken substring into the fields array my fields while fields split for every substring indexed with an odd number search for and replace it with my count my end fields for count count end count if count fields count would not this chunk do the job
QA
pure python xslt library is there an xslt library that is pure python installing libxml libxslt or any similar libraries is problem on some of the platforms need to support really only need basic xslt support and speed is not major issue
if you only need basic support and your xml is not too crazy consider removing the xslt element from the equation and just using dom sax parser here is some info from the pythoninfo wiki dom sucks up an entire xml file holds it in memory and let us you work with it sax on the other hand emits events as it goes step by step through the file what do you think
QA
why results of map and list comprehension are different the following test fails usr bin env python def args map lambda lambda lambda for in lambda for in alist for in args print alist if name main import doctest doctest testmod in other words args for in args append lambda map lambda args args for in args append lambda lambda map lambda args args for in args append lambda map lambda args
expression lambda is equivalent to def return expression lambda is equivalent to def return is free variable in the first case and it is bound to the function parameter in the second case it is local variable in that case values for default parameters are evaluated at the time of function definition generator expression is the nearest enclosing scope where is defined for name in the lambda expression therefore is resolved in that block lambda for in is local variable of the lambda block therefore the object it refers to is defined in that block map lambda lambda
QA
is there any list of blog engines written in django is there any list of blog engines written in django
nathan borror has great package of basic apps that has blog these are well written well documented apps that you should try out get ideas from etc http code google com django basic apps
QA
looking for file traversal functions in python that are like java in java you can do file listfiles and receive all of the files in directory you can then easily recurse through directory trees is there an analogous way to do this in python
would recommend against os path walk as it is being removed in python os walk is simpler anyway or at least find it simpler
QA
how to list only top level directories in python want to be able to list only the directories inside some folder this means do not want filenames listed nor do want additional sub folders let us see if an example helps in the current directory we have os listdir os getcwd cx oracle doc dlls doc include lib libs license txt mod ython wininst log news txt pymssql wininst log python exe pythonw ex readme txt removemod python exe removepymssql exe scripts tcl tools xpopen exe however do not want filenames listed nor do want sub folders such as lib curses essentially what want works with the following for root dirnames filenames in os walk print dirnames break cx oracle doc dlls doc include lib libs scripts tcl tools however am wondering if there is simpler way of achieving the same results get the impression that using os walk only to return the top level is inefficient too much
directories for in os listdir os getcwd if os path isdir
QA
how to list only top level directories in python want to be able to list only the directories inside some folder this means do not want filenames listed nor do want additional sub folders let us see if an example helps in the current directory we have os listdir os getcwd cx oracle doc dlls doc include lib libs license txt mod ython wininst log news txt pymssql wininst log python exe pythonw ex readme txt removemod python exe removepymssql exe scripts tcl tools xpopen exe however do not want filenames listed nor do want sub folders such as lib curses essentially what want works with the following for root dirnames filenames in os walk print dirnames break cx oracle doc dlls doc include lib libs scripts tcl tools however am wondering if there is simpler way of achieving the same results get the impression that using os walk only to return the top level is inefficient too much
like so path for path in os listdir os getcwd if os path isdir path
QA
how to list only top level directories in python want to be able to list only the directories inside some folder this means do not want filenames listed nor do want additional sub folders let us see if an example helps in the current directory we have os listdir os getcwd cx oracle doc dlls doc include lib libs license txt mod ython wininst log news txt pymssql wininst log python exe pythonw ex readme txt removemod python exe removepymssql exe scripts tcl tools xpopen exe however do not want filenames listed nor do want sub folders such as lib curses essentially what want works with the following for root dirnames filenames in os walk print dirnames break cx oracle doc dlls doc include lib libs scripts tcl tools however am wondering if there is simpler way of achieving the same results get the impression that using os walk only to return the top level is inefficient too much
for in os listdir somedir if os path isdir os path join somedir
QA
how to list only top level directories in python want to be able to list only the directories inside some folder this means do not want filenames listed nor do want additional sub folders let us see if an example helps in the current directory we have os listdir os getcwd cx oracle doc dlls doc include lib libs license txt mod ython wininst log news txt pymssql wininst log python exe pythonw ex readme txt removemod python exe removepymssql exe scripts tcl tools xpopen exe however do not want filenames listed nor do want sub folders such as lib curses essentially what want works with the following for root dirnames filenames in os walk print dirnames break cx oracle doc dlls doc include lib libs scripts tcl tools however am wondering if there is simpler way of achieving the same results get the impression that using os walk only to return the top level is inefficient too much
filter the result using os path isdir and use os path join to get the real path name for name in os listdir thedir if os path isdir os path join thedir name ctypes distutils encodings lib tk config idlelib xml bsddb hotshot logging doc test compiler curses site packages email sqlite lib dynload wsgiref plat linux plat mac
QA
how to list only top level directories in python want to be able to list only the directories inside some folder this means do not want filenames listed nor do want additional sub folders let us see if an example helps in the current directory we have os listdir os getcwd cx oracle doc dlls doc include lib libs license txt mod ython wininst log news txt pymssql wininst log python exe pythonw ex readme txt removemod python exe removepymssql exe scripts tcl tools xpopen exe however do not want filenames listed nor do want sub folders such as lib curses essentially what want works with the following for root dirnames filenames in os walk print dirnames break cx oracle doc dlls doc include lib libs scripts tcl tools however am wondering if there is simpler way of achieving the same results get the impression that using os walk only to return the top level is inefficient too much
filter the list using os path isdir to detect directories filter os path isdir os listdir os getcwd
QA
can you explain closures as they relate to python have been reading lot about closures and think understand them but without clouding the picture for myself and others am hoping someone can explain closures as succinctly and clearly as possible am looking for simple explanation that might help me understand where and why would want to use them
closure on closures objects are data with methods attached closures are functions with data attached def make counter def counter counter is closure nonlocal return return counter make counter make counter print
QA
how do wrap string in file in python how do create file like object same duck type as file with the contents of string
use the stringio module for example from cstringio import stringio stringio foo read foo use cstringio which is faster but note that it does not accept unicode strings that cannot be encoded as plain ascii strings you can switch to stringio by changing from cstringio to from stringio
QA
is there an easy way to populate slugfield from charfield class foo models model title models charfield max length slug models slugfield is there built in way to get the slug field to autopopulate based on the title perhaps in the admin and outside of the admin
for pre slug models slugfield prepopulate from title should work just fine for use camflan
QA
is there an easy way to populate slugfield from charfield class foo models model title models charfield max length slug models slugfield is there built in way to get the slug field to autopopulate based on the title perhaps in the admin and outside of the admin
for admin in django and up you would need to use prepopulated fields slug title in your admin py your key in the prepopulated fields dictionary is the field you want filled and the value is tuple of fields you want concatenated outside of admin you can use the slugify function in your views in templates you can use the slugify filter there is also this package which will take care of this automatically https pypi python org pypi django autoslug
QA
overloading init in python let us say have class that has member called data which is list want to be able to initialize the class with for example filename which contains data to initialize the list or with an actual list what is your technique for doing this do you just check the type by looking at class is there some trick might be missing am used to where overloading by argument type is easy thanks
better way would be to use isinstance and type conversion if am understanding you right you want this def init self filename if isinstance filename basestring filename is string else try to convert to list self path list filename
QA
overloading init in python let us say have class that has member called data which is list want to be able to initialize the class with for example filename which contains data to initialize the list or with an actual list what is your technique for doing this do you just check the type by looking at class is there some trick might be missing am used to where overloading by argument type is easy thanks
you probably want the isinstance builtin function self data data if isinstance data list else self parse data
QA
overloading init in python let us say have class that has member called data which is list want to be able to initialize the class with for example filename which contains data to initialize the list or with an actual list what is your technique for doing this do you just check the type by looking at class is there some trick might be missing am used to where overloading by argument type is easy thanks
you should use isinstance isinstance isinstance object class or type or tuple bool return whether an object is an instance of class or of subclass thereof with type as second argument return whether that is the object type the form using tuple isinstance is shortcut for isinstance or isinstance or etc
QA
what limitations have closures in python compared to language closures where is any programming language javascript lisp perl ruby scheme etc which supports some flavour of closures some limitations are mentioned in the closures in python compared to ruby closures but the article is old and many limitations do not exist in modern python any more seeing code example for concrete limitation would be great related questions can you explain closures as they relate to python what is closure how does javascript closure work
the only difficulty have seen people encounter with python in particular is when they try to mix non functional features like variable reassignment with closures and are surprised when this does not work def outer def inner print return inner outer usually just pointing out that function has its own local variables is enough to deter such silliness
QA
what limitations have closures in python compared to language closures where is any programming language javascript lisp perl ruby scheme etc which supports some flavour of closures some limitations are mentioned in the closures in python compared to ruby closures but the article is old and many limitations do not exist in modern python any more seeing code example for concrete limitation would be great related questions can you explain closures as they relate to python what is closure how does javascript closure work
the most important limitation currently is that you cannot assign to an outer scope variable in other words closures are read only def outer def inner reads will return outer return def inner writes will assign to local not the outer def inner error will produce an error is local because of the assignment but we use it before it is assigned to tmp return tmp return inner reads inner writes inner error inner reads inner writes inner error outer inner reads inner writes inner reads inner error traceback most recent call last file stdin line in module file stdin line in inner error unboundlocalerror local variable referenced before assignment name that gets assigned to in local scope function is always local unless declared otherwise while there is the global declaration to declare variable global even when it is assigned to there is no such declaration for enclosed variables yet in python there is will be the nonlocal declaration that does just that you can work around this limitation in the mean time by using mutable container type def outer def inner reads will return outer first and only element return def inner writes will look up outer then mutate it def inner error will now work because is not assigned to just referenced tmp return tmp return inner reads inner writes inner error inner reads inner writes inner error outer inner reads inner writes inner reads inner error inner reads
QA
authenticating against active directory using python ldap how do authenticate against ad using python ldap am currently using the python ldap library and all it is producing is tears cannot even bind to perform simple query import sys import ldap server ldap my ldap server dn secret un sys argv base dc mydomain dc co dc uk scope ldap scope subtree filter objectclass user samaccountname un attrs displayname ldap initialize server protocol version print simple bind dn secret are search base scope filter attrs type user result name attrs user if hasattr attrs has key and attrs has key displayname displayname attrs displayname print displayname sys exit running this with myusername mydomain co uk password username gives me one of two errors invalid credentials when mistype or intentionally use wrong credentials it fails to authenticate ldap invalid credentials info ldaperr dsid comment acceptsecuritycontext error data vece desc invalid credentials or ldap operations error info ldaperr dsid comment in order to perform this operation successful bind must be completed on the connection data vece desc operations error what am missing out to bind properly am getting the same errors on fedora and windows
if you are open to using pywin you can use win calls from python this is what we do in our cherrypy web server import win security token win security logonuser username domain password win security logon logon network win security logon provider default authenticated bool token
QA
what limitations have closures in python compared to language closures where is any programming language javascript lisp perl ruby scheme etc which supports some flavour of closures some limitations are mentioned in the closures in python compared to ruby closures but the article is old and many limitations do not exist in modern python any more seeing code example for concrete limitation would be great related questions can you explain closures as they relate to python what is closure how does javascript closure work
john millikin def outer local to outer def inner local to inner print return def inner nonlocal print local to outer change it is not local to inner return local to outer return inner inner for inner in outer print inner
QA
what limitations have closures in python compared to language closures where is any programming language javascript lisp perl ruby scheme etc which supports some flavour of closures some limitations are mentioned in the closures in python compared to ruby closures but the article is old and many limitations do not exist in modern python any more seeing code example for concrete limitation would be great related questions can you explain closures as they relate to python what is closure how does javascript closure work
fixed in python via the nonlocal statement the nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals this is important because the default behavior for binding is to search the local namespace first the statement allows encapsulated code to rebind variables outside of the local scope besides the global module scope
QA
overloading init in python let us say have class that has member called data which is list want to be able to initialize the class with for example filename which contains data to initialize the list or with an actual list what is your technique for doing this do you just check the type by looking at class is there some trick might be missing am used to where overloading by argument type is easy thanks
much neater way to get alternate constructors is to use classmethods for instance class mydata def init self data initialize mydata from sequence self data data classmethod def fromfilename cls filename initialize mydata from file data open filename readlines return cls data classmethod def fromdict cls datadict initialize mydata from dict items return cls datadict items mydata data mydata fromfilename tmp foobar data foo bar baz mydata fromdict spam ham data spam ham the reason it is neater is that there is no doubt about what type is expected and you are not forced to guess at what the caller intended for you to do with the datatype it gave you the problem with isinstance basestring is that there is no way for the caller to tell you for instance that even though the type is not basestring you should treat it as string and not another sequence and perhaps the caller would like to use the same type for different purposes sometimes as single item and sometimes as sequence of items being explicit takes all doubt away and leads to more robust and clearer code
QA
how do dump an entire python process for later debugging inspection have python application in strange state do not want to do live debugging of the process can dump it to file and examine its state later know have restored corefiles of programs in gdb later but do not know how to examine python application in useful way from gdb this is variation on my question about debugging memleaks in production system
there is no builtin way other than aborting with os abort causing the coredump if resource limits allow it although you can certainly build your own dump function that dumps relevant information about the data you care about there are no ready made tools for it as for handling the corefile of python process the python source has gdbinit file that contains useful macros it is still lot more painful than somehow getting into the process itself with pdb or the interactive interpreter but it makes life little easier
QA
writing domain specific language for selecting rows from table am writing server that expect to be run by many different people not all of whom will have direct contact with the servers will communicate with each other in cluster part of the server functionality involves selecting small subset of rows from potentially very large table the exact choice of what rows are selected will need some tuning and it is important that it is possible for the person running the cluster eg myself to update the selection criteria without getting each and every server administrator to deploy new version of the server simply writing the function in python is not really an option since nobody is going to want to install server that downloads and executes arbitrary python code at runtime what need are suggestions on the simplest way to implement domain specific language to achieve this goal the language needs to be capable of simple expression evaluation as well as querying table indexes and iterating through the returned rows ease of writing and reading the language is secondary to ease of implementing it would also prefer not to have to write an entire query optimiser so something that explicitly specifies what indexes to query would be ideal the interface that this will have to compile against will be similar in capabilities to what the app engine datastore exports you can query for sequential ranges on any index on the table eg less than greater than range and equality queries then filter the returned row by any boolean expression you can also concatenate multiple independent result sets together realise this question sounds lot like am asking for sql however do not want to require that the datastore backing this data be relational database and do not want the overhead of trying to reimplement sql myself am also dealing with only single table with known schema finally no joins will be required something much simpler would be far preferable edit expanded description to clear up some misconceptions
implement domain specific language nobody is going to want to install server that downloads and executes arbitrary python code at runtime want dsl but do not want python to be that dsl okay how will you execute this dsl what runtime is acceptable if not python what if have program that happens to embed the python interpreter is that acceptable and if python is not an acceptable runtime why does this have python tag
QA
what limitations have closures in python compared to language closures where is any programming language javascript lisp perl ruby scheme etc which supports some flavour of closures some limitations are mentioned in the closures in python compared to ruby closures but the article is old and many limitations do not exist in modern python any more seeing code example for concrete limitation would be great related questions can you explain closures as they relate to python what is closure how does javascript closure work
comment for kevin little answer to include the code example nonlocal does not solve completely this problem on python global def outer local to outer def inner global change global print change global return def inner nonlocal cannot use nonlocal here print prints global cannot change here return return inner inner for inner in outer print inner on the other hand def outer local to outer def inner global print local to inner return def inner nonlocal print local to outer return return inner inner for inner in outer print inner it works on python
QA
is there an easy way to populate slugfield from charfield class foo models model title models charfield max length slug models slugfield is there built in way to get the slug field to autopopulate based on the title perhaps in the admin and outside of the admin
outside the admin see this django snippet put it in your save and it will work with objects created programmatically inside the admin as the others have said use prepopulated fields
QA
writing domain specific language for selecting rows from table am writing server that expect to be run by many different people not all of whom will have direct contact with the servers will communicate with each other in cluster part of the server functionality involves selecting small subset of rows from potentially very large table the exact choice of what rows are selected will need some tuning and it is important that it is possible for the person running the cluster eg myself to update the selection criteria without getting each and every server administrator to deploy new version of the server simply writing the function in python is not really an option since nobody is going to want to install server that downloads and executes arbitrary python code at runtime what need are suggestions on the simplest way to implement domain specific language to achieve this goal the language needs to be capable of simple expression evaluation as well as querying table indexes and iterating through the returned rows ease of writing and reading the language is secondary to ease of implementing it would also prefer not to have to write an entire query optimiser so something that explicitly specifies what indexes to query would be ideal the interface that this will have to compile against will be similar in capabilities to what the app engine datastore exports you can query for sequential ranges on any index on the table eg less than greater than range and equality queries then filter the returned row by any boolean expression you can also concatenate multiple independent result sets together realise this question sounds lot like am asking for sql however do not want to require that the datastore backing this data be relational database and do not want the overhead of trying to reimplement sql myself am also dealing with only single table with known schema finally no joins will be required something much simpler would be far preferable edit expanded description to clear up some misconceptions
it sounds like you want to create grammar not dsl would look into antlr which will allow you to create specific parser that will interpret text and translate to specific commands antlr provides libraries for python sql java etc also here is fine example of an antlr calculation engine created in
QA
how do dump an entire python process for later debugging inspection have python application in strange state do not want to do live debugging of the process can dump it to file and examine its state later know have restored corefiles of programs in gdb later but do not know how to examine python application in useful way from gdb this is variation on my question about debugging memleaks in production system
someone above said that there is no builtin way to perform this but that is not entirely true for an example you could take look at the pylons debugging tools whene there is an exception the exception handler saves the stack trace and prints url on the console that can be used to retrieve the debugging session over http while they are probably keeping these sessions in memory they are just python objects so there is nothing to stop you from pickling stack dump and restoring it later for inspection it would mean some changes to the app but it should be possible after some research it turns out the relevant code is actually coming from paste evalexception module you should be able to look there to figure out what you need
QA
how do get the key value of db referenceproperty without database hit is there way to get the key or id value of db referenceproperty without dereferencing the actual entity it points to have been digging around it looks like the key is stored as the property name preceeded with an but have been unable to get any code working examples would be much appreciated thanks edit here is what have unsuccessfully tried class comment db model series db referenceproperty reference class series def series id self return self series and in my template href games view series html series comment series id comm comment key id more the result href games view series html series comm more
you are correct the key is stored as the property name prefixed with you should just be able to access it directly on the model object can you demonstrate what you are trying have used this technique in the past with no problems edit have you tried calling series id directly or referencing series in your template directly am not sure whether django automatically calls methods with no arguments if you specify them in this context you could also try putting the property decorator on the method
QA
how do find what is using memory in python process in production system my production system occasionally exhibits memory leak have not been able to reproduce in development environment have used python memory profiler specifically heapy with some success in the development environment but it cannot help me with things cannot reproduce and am reluctant to instrument our production system with heapy because it takes while to do its thing and its threaded remote interface does not work well in our server what think want is way to dump snapshot of the production python process or at least gc get objects and then analyze it offline to see where it is using memory how do get core dump of python process like this once have one how do do something useful with it
do not know how to dump an entire python interpreter state and restore it it would be useful will keep my eye on this answer in case anyone else has ideas if you have an idea where the memory is leaking you can add checks the refcounts of your objects for example someobject later oldrefcount sys getrefcount suspiciousfunction if oldrefcount sys getrefcount print possible memory leak you could also check for reference counts higher than some number that is reasonable for your app to take it further you could modify the python interpreter to do these kinds of check by replacing the py incref and py decref macros with your own this might be bit dangerous in production app though here is an essay with more info on debugging these sorts of things it is more geared for plugin authors but most of it applies debugging reference counts
QA
how can create status bar item with cocoa and python pyobjc have created brand new project in xcode and have the following in my appdelegate py file from foundation import from appkit import class myapplicationappdelegate nsobject def applicationdidfinishlaunching self sender nslog application did finish launching statusitem nsstatusbar systemstatusbar statusitemwithlength nsvariablestatusitemlength statusitem settitle you statusitem sethighlightmode true statusitem setenabled true however when launch the application no status bar item shows up all the other code in main py and main is default
had to do this to make it work open mainmenu xib make sure the class of the app delegate is myapplicationappdelegate am not sure if you will have to do this but did it was wrong and so the app delegate never got called in the first place add statusitem retain because it gets autoreleased right away
QA
how do find what is using memory in python process in production system my production system occasionally exhibits memory leak have not been able to reproduce in development environment have used python memory profiler specifically heapy with some success in the development environment but it cannot help me with things cannot reproduce and am reluctant to instrument our production system with heapy because it takes while to do its thing and its threaded remote interface does not work well in our server what think want is way to dump snapshot of the production python process or at least gc get objects and then analyze it offline to see where it is using memory how do get core dump of python process like this once have one how do do something useful with it
the gc module has some functions that might be useful like listing all objects the garbage collector found to be unreachable but cannot free or list of all objects being tracked if you have suspicion which objects might leak the weakref module could be handy to find out if when objects are collected
QA
regular expressions but for writing in the match when using regular expressions we generally if not always use them to extract some kind of information what need is to replace the match value with some other value right now am doing this def getexpandedtext pattern text replacevalue one liner really ugly but it is only used in here return text replace text text find re findall pattern text replacevalue text text find re findall pattern text len replacevalue so if do sth like getexpandedtext aaa bbb hola aaaiiibbb como estas ooo hola aaaooobbb como estas it changes the with ooo do you guys know whether with python regular expressions we can do this thanks lot guys
def getexpandedtext pattern text group searches for pattern in the text and replaces all captures with the values in group tag renaming html div abc span id def span ghi div getexpandedtext span html div div abc div id def div ghi div nested groups capture references getexpandedtext abacdzefbgh aba ef bgh pattern re compile pattern ret last for in pattern finditer text for in xrange len groups start end span nested or skipped group if start last or group is none continue text between the previous and current match if last start ret append text last start last end ret append expand group ret append text last return join ret edit allow capture references in the replacement strings
QA
how do wrap string in file in python how do create file like object same duck type as file with the contents of string
in python import io with io stringio as write abcdef print gh file seek print read
QA
writing domain specific language for selecting rows from table am writing server that expect to be run by many different people not all of whom will have direct contact with the servers will communicate with each other in cluster part of the server functionality involves selecting small subset of rows from potentially very large table the exact choice of what rows are selected will need some tuning and it is important that it is possible for the person running the cluster eg myself to update the selection criteria without getting each and every server administrator to deploy new version of the server simply writing the function in python is not really an option since nobody is going to want to install server that downloads and executes arbitrary python code at runtime what need are suggestions on the simplest way to implement domain specific language to achieve this goal the language needs to be capable of simple expression evaluation as well as querying table indexes and iterating through the returned rows ease of writing and reading the language is secondary to ease of implementing it would also prefer not to have to write an entire query optimiser so something that explicitly specifies what indexes to query would be ideal the interface that this will have to compile against will be similar in capabilities to what the app engine datastore exports you can query for sequential ranges on any index on the table eg less than greater than range and equality queries then filter the returned row by any boolean expression you can also concatenate multiple independent result sets together realise this question sounds lot like am asking for sql however do not want to require that the datastore backing this data be relational database and do not want the overhead of trying to reimplement sql myself am also dealing with only single table with known schema finally no joins will be required something much simpler would be far preferable edit expanded description to clear up some misconceptions
building dsl to be interpreted by python step build the run time classes and objects these classes will have all the cursor loops and sql statements and all of that algorithmic processing tucked away in their methods you will make heavy use of the command and strategy design patterns to build these classes most things are command options and choices are plug in strategies look at the design for apache ant task api it is good example step validate that this system of objects actually works be sure that the design is simple and complete you are tests will construct the command and strategy objects and then execute the top level command object the command objects will do the work at this point you are largely done your run time is just configuration of objects created from the above domain this is not as easy as it sounds it requires some care to define set of classes that can be instantiated and then talk among themselves to do the work of your application note that what you will have will require nothing more than declarations what is wrong with procedural one you start to write dsl with procedural elements you find that you need more and more features until you have written python with different syntax not good further procedural language interpreters are simply hard to write state of execution and scope of references are simply hard to manage you can use native python and stop worrying about getting out of the sandbox indeed that is how you will unit test everything using short python script to create your objects python will be the dsl but wait you say if simply use python as the dsl people can execute arbitrary things depends on what is on the pythonpath and sys path look at the site module for ways to control what is available declarative dsl is simplest it is entirely an exercise in representation block of python that merely sets the values of some variables is nice that is what django uses you can use the configparser as language for representing your run time configuration of objects you can use json or yaml as language for representing your run time configuration of objects ready made parsers are totally available you can use xml too it is harder to design and parse but it works fine people love it that is how ant and maven and lots of other tools use declarative syntax to describe procedures do not recommend it because it is wordy pain in the neck recommend simply using python or you can go off the deep end and invent your own syntax and write your own parser
QA
how to specify an authenticated proxy for python http connection what is the best way to specify proxy with username and password for an http connection in python
or if you want to install it so that it is always used with urllib urlopen so you do not need to keep reference to the opener around import urllib url www proxyurl com username user password pass password mgr urllib httppasswordmgrwithdefaultrealm none with the withdefaultrealm password manager means that the user pass will be used for any realm where there is not more specific match password mgr add password none url username password auth handler urllib httpbasicauthhandler password mgr opener urllib build opener auth handler urllib install opener opener print urllib urlopen http www example com folder page html read
QA
how to list only top level directories in python want to be able to list only the directories inside some folder this means do not want filenames listed nor do want additional sub folders let us see if an example helps in the current directory we have os listdir os getcwd cx oracle doc dlls doc include lib libs license txt mod ython wininst log news txt pymssql wininst log python exe pythonw ex readme txt removemod python exe removepymssql exe scripts tcl tools xpopen exe however do not want filenames listed nor do want sub folders such as lib curses essentially what want works with the following for root dirnames filenames in os walk print dirnames break cx oracle doc dlls doc include lib libs scripts tcl tools however am wondering if there is simpler way of achieving the same results get the impression that using os walk only to return the top level is inefficient too much
note that instead of doing os listdir os getcwd it is preferable to do os listdir os path curdir one less function call and it is as portable so to complete the answer to get list of directories in folder def listdirs folder return for in os listdir folder if os path isdir os path join folder if you prefer full pathnames then use this function def listdirs folder return for in os path join folder for in os listdir folder if os path isdir
QA
socket programming for mobile phones in python have written code for communication between my phone and comp thru tcp sockets when type out the code line by line in the interactive console it works fine however when try running the script directly through filebrowser py it just will not work am using nokia is there anyway can run this script directly without using filebrowser py am new to python for mobile phones so any suggestions would be appreciated thanks
have you read hack mobile phone with linux and python it is rather old but maybe you find it helpful
QA
how do find what is using memory in python process in production system my production system occasionally exhibits memory leak have not been able to reproduce in development environment have used python memory profiler specifically heapy with some success in the development environment but it cannot help me with things cannot reproduce and am reluctant to instrument our production system with heapy because it takes while to do its thing and its threaded remote interface does not work well in our server what think want is way to dump snapshot of the production python process or at least gc get objects and then analyze it offline to see where it is using memory how do get core dump of python process like this once have one how do do something useful with it
could you record the traffic via log on your production site then re play it on your development server instrumented with python memory debugger recommend dozer http pypi python org pypi dozer
QA
listing all functions in python module have python module installed on my system and would like to be able to see what functions classes methods are available in it want to call the doc function on each one in ruby can do something like classname methods to get list of all the methods available on that class is there something similar in python eg something like from somemodule import foo print foo methods or whatever is the correct method to call
this will do the trick dir module however if you find it annoying to read the returned list just use the following loop to get one name per line for in dir module print
QA
socket programming for mobile phones in python have written code for communication between my phone and comp thru tcp sockets when type out the code line by line in the interactive console it works fine however when try running the script directly through filebrowser py it just will not work am using nokia is there anyway can run this script directly without using filebrowser py am new to python for mobile phones so any suggestions would be appreciated thanks
if the code is working in the interactive interpreter when typed but not when run directly then would suggest seeing if your code has reached deadlock on the socket for example both ends are waiting for data from the other when typing into the interactive interpreter there is longer delay between the execution of each line on code
QA
how to list only top level directories in python want to be able to list only the directories inside some folder this means do not want filenames listed nor do want additional sub folders let us see if an example helps in the current directory we have os listdir os getcwd cx oracle doc dlls doc include lib libs license txt mod ython wininst log news txt pymssql wininst log python exe pythonw ex readme txt removemod python exe removepymssql exe scripts tcl tools xpopen exe however do not want filenames listed nor do want sub folders such as lib curses essentially what want works with the following for root dirnames filenames in os walk print dirnames break cx oracle doc dlls doc include lib libs scripts tcl tools however am wondering if there is simpler way of achieving the same results get the impression that using os walk only to return the top level is inefficient too much
os walk next
QA
python how to make cross module variable the debug variable is handy in part because it affects every module if want to create another variable that works the same way how would do it the variable let us be original and call it foo does not have to be truly global in the sense that if change foo in one module it is updated in others would be fine if could set foo before importing other modules and then they would see the same value for it
this sounds like modifying the builtin name space to do it import builtin builtin foo some value do not use the builtins directly notice the extra apparently this can be dictionary or module thanks to for pointing this out more can be found here now foo is available for use everywhere do not recommend doing this generally but the use of this is up to the programmer assigning to it must be done as above just setting foo some other value will only set it in the current namespace
QA
python how to make cross module variable the debug variable is handy in part because it affects every module if want to create another variable that works the same way how would do it the variable let us be original and call it foo does not have to be truly global in the sense that if change foo in one module it is updated in others would be fine if could set foo before importing other modules and then they would see the same value for it
do not endorse this solution in any way shape or form but if you add variable to the builtin module it will be accessible as if global from any other module that includes builtin which is all of them by default py contains print foo py contains import builtin builtin foo import the result is that is printed edit the builtin module is available as the local symbol builtins that is the reason for the discrepancy between two of these answers also note that builtin has been renamed to builtins in python
QA
how do find what is using memory in python process in production system my production system occasionally exhibits memory leak have not been able to reproduce in development environment have used python memory profiler specifically heapy with some success in the development environment but it cannot help me with things cannot reproduce and am reluctant to instrument our production system with heapy because it takes while to do its thing and its threaded remote interface does not work well in our server what think want is way to dump snapshot of the production python process or at least gc get objects and then analyze it offline to see where it is using memory how do get core dump of python process like this once have one how do do something useful with it
make your program dump core then clone an instance of the program on sufficiently similar box using gdb there are special macros to help with debugging python programs within gdb but if you can get your program to concurrently serve up remote she will you could just continue the program execution and query it with python have never had to do this so am not sure it will work but perhaps the pointers will be helpful
QA
python how to make cross module variable the debug variable is handy in part because it affects every module if want to create another variable that works the same way how would do it the variable let us be original and call it foo does not have to be truly global in the sense that if change foo in one module it is updated in others would be fine if could set foo before importing other modules and then they would see the same value for it
define module call it globalbaz and have the variables defined inside it all the modules using this pseudoglobal should import the globalbaz module and refer to it using globalbaz var name this works regardless of the place of the change you can change the variable before or after the import the imported module will use the latest value tested this in toy example for clarification globalbaz py looks just like this var name my useful string
QA
how do dump an entire python process for later debugging inspection have python application in strange state do not want to do live debugging of the process can dump it to file and examine its state later know have restored corefiles of programs in gdb later but do not know how to examine python application in useful way from gdb this is variation on my question about debugging memleaks in production system
this answer suggests making your program core dump and then continuing execution on another sufficiently similar box
QA
python how to make cross module variable the debug variable is handy in part because it affects every module if want to create another variable that works the same way how would do it the variable let us be original and call it foo does not have to be truly global in the sense that if change foo in one module it is updated in others would be fine if could set foo before importing other modules and then they would see the same value for it
if you need global cross module variable maybe just simple global module level variable will suffice py var py import print var import print var py import var test python py real world example django global settings py though in django apps settings are used by importing the object django conf settings
QA
python how to make cross module variable the debug variable is handy in part because it affects every module if want to create another variable that works the same way how would do it the variable let us be original and call it foo does not have to be truly global in the sense that if change foo in one module it is updated in others would be fine if could set foo before importing other modules and then they would see the same value for it
global variables are usually bad idea but you can do this by assigning to builtins builtins foo something print foo also modules themselves are variables that you can access from any module so if you define module called my globals py my globals py foo something then you can use that from anywhere as well import my globals print my globals foo using modules rather than modifying builtins is generally cleaner way to do globals of this sort
QA
doing crud in turbogears are there any good packages or methods for doing extensive crud create retrieve update delete interfaces in the turbogears framework the fastdatagrid widget is too much of black box to be useful and crudtemplate looks like more trouble than rolling my own ideas suggestions
while crudtemplate looks mildly complex would say that you can implement crud abcd using just about any orm that you choose it just depends on how much of it you with to automate which generally means defining models schemas ahead of time you may learn more and have better control if you put together your own using sqlalchemy or sqlobject woth of which work great with turbogears
QA
how do upgrade python to python rc on ubuntu linux would like to how to upgrade the default python installation supplied with ubuntu to python rc would like to make the default python version on the system and migrate all the other useful installed python libraries installed on to python rc please let me know how can achieve this thanks dirk
with the warning that think it is tremendously bad idea to replace the default python with an unreleased beta version first install rc you can download the source from the python website standard configure make sudo make install installation style next remove the usr bin python symlink do not remove usr bin python add symlink to with ln usr local bin python usr bin python once again think this is terrible idea there is almost certainly better way to do whatever you are trying to accomplish migrating installed libraries is much longer process look in the usr lib python site packages and usr local lib python site packages directories any libraries installed to them will need to be re installed with since you are not using packaged python version you cannot use ubuntu packages you will have to manually upgrade all the libraries yourself most of them can probably be installed with sudo easy install name but some like pygtk are not so easy you will have to follow custom installation procedures for each such library
QA
python reading oracle path on my desktop have written small pylons app that connects to oracle am now trying to deploy it to my server which is running win my desktop is bit xp the oracle installation on the server is also bit was getting errors about loading the oci dll so installed the bit client into oracle if add this to the path environment variable it works great but also want to run the pylons app as service using this recipe and do not want to put this bit library on the path for all other applications tried using sys path append oracle bin but that does not seem to work
if your python application runs in the bit space you will need to access bit installation of oracle oci dll rather than the bit version normally you would update the system path to include the appropriate oracle home bin directory prior to running the script the solution may also vary depending on what component you are using to access oracle from python
QA
how do upgrade python to python rc on ubuntu linux would like to how to upgrade the default python installation supplied with ubuntu to python rc would like to make the default python version on the system and migrate all the other useful installed python libraries installed on to python rc please let me know how can achieve this thanks dirk
is there any need to ubuntu in general does not package rc releases will not be available in ubuntu until jaunty jackalope however if you insist that you need to install it then you will have to do so without package manager download the package and unzip it to directory run the following commands waiting for each to finish as you do so configure make sudo make install there you have it installed it is better to wait for it to be packaged first espescially as python is used in lot of ubuntu internals so may break your system horribly
QA
socket programming for mobile phones in python have written code for communication between my phone and comp thru tcp sockets when type out the code line by line in the interactive console it works fine however when try running the script directly through filebrowser py it just will not work am using nokia is there anyway can run this script directly without using filebrowser py am new to python for mobile phones so any suggestions would be appreciated thanks
well it does not appear to be deadlock situation it throws an error saying remote server refused connection however like said before if type the very same code into the interactive interpreter it works just fine am wondering if the error is because the script is run through filebrowser py
QA
using locale setlocale in embedded python without breaking file parsing in thread we are using third party middleware product that allows us to write code in an embedded python interpreter and which exposes an api that we can call into some of these api calls allow us to load various kinds of file and the loading code is implemented in file loading happens in separate thread and calls back into python when the data is available so far all well and dandy we have been ing heh our product and one thing we would like to do is format user facing numerical output according to the user locale settings so from python we do this import locale locale setlocale locale lc all now this works in that the user facing numbers are formatted correctly for their locale however if the user locale differs from the default locale any files that are subsequently loaded will return incorrect data presumably because all string to float conversion has been affected right down to the metal we cannot work around this by implementing locale aware file loading so our current workaround is to only set the locale when formatting output for the user and then set it back again afterwards that is something like import locale currentlocale locale getlocale locale lc all locale setlocale locale lc all displaynumberstotheuser locale setlocale locale lc all currentlocale this seems bit clunky and was wondering whether this is common approach to formatting locale aware output for the user my other concern is that this is obviously not thread safe so we will presumably still get problems if any file parsing occurs in separate thread when the locale is changed any information on best practice is appreciated do not have much experience with this sort of thing
setting the locale after multiple threads have started operating may have unexpected results unless could figure out more subtle approach would probably just split file loading and the user interface into separate processes communicating through pipe or file socket
QA
does python have bitfield type need compact representation of an array of booleans does python have builtin bitfield type or will need to find an alternate solution
numpy has array interface module that you can use to make bitfield
QA
does python have bitfield type need compact representation of an array of booleans does python have builtin bitfield type or will need to find an alternate solution
the bitvector package may be what you need it is not built in to my python installation but easy to track down on the python site https pypi python org pypi bitvector for the current version
QA
drag and drop onto python script in windows explorer would like to drag and drop my data file onto python script and have it process the file and generate output the python script accepts the name of the data file as command line parameter but windows explorer does not allow the script to be drop target is there some kind of configuration that needs to be done somewhere for this work
sure from mindless technology article called make python scripts droppable in windows you can add drop handler by adding registry key here registry import file that you can use to do this copy the following into reg file and run it make sure that your py extensions are mapped to python file windows registry editor version hkey classes root python file shellex drophandler ca cf aa this makes python scripts use the wsh drop handler which is compatible with long filenames to use the short filename handler replace the guid with comment in that post indicates that one can enable dropping on no console python files pyw or compiled python files pyc by using the python noconfile and python compiledfile classes
QA
does python have bitfield type need compact representation of an array of booleans does python have builtin bitfield type or will need to find an alternate solution
bitarray was the best answer found when recently had similar need it is extension so much faster than bitvector which is pure python and stores its data in an actual bitfield so it is eight times more memory efficient than numpy boolean array which appears to use byte per element
QA
looking for file traversal functions in python that are like java in java you can do file listfiles and receive all of the files in directory you can then easily recurse through directory trees is there an analogous way to do this in python
as long time pythonista have to say the path file manipulation functions in the std library are sub par they are not object oriented and they reflect an obsolete let us wrap os system functions without thinking philosophy would heartily recommend the path module as wrapper around os os path glob and tempfile if you must know much nicer and oopy http pypi python org pypi path py this is walk with the path module dir path os environ home for in dir walk if isfile and endswith remove
QA
does python have bitfield type need compact representation of an array of booleans does python have builtin bitfield type or will need to find an alternate solution
if your bitfield is short you can probably use the struct module otherwise would recommend some sort of wrapper around the array module also the ctypes module does contain bitfields but have never used it myself caveat emptor
QA
how do wrap string in file in python how do create file like object same duck type as file with the contents of string
two good answers add little trick if you need real file object some methods expect one not just an interface here is way to create an adapter http www rfk id au software filelike
QA
does python have bitfield type need compact representation of an array of booleans does python have builtin bitfield type or will need to find an alternate solution
use the binary bit wise operators and they work really well and are implemented directly in the underlying which is usually directly on the underlying hardware
QA
upload files in google app engine am planning to create web app that allows users to downgrade their visual studio project files however it seems google app engine accepts files uploading and flat file storing on the google server through db textproperty and db blobproperty will be glad anyone can provide code sample both the client and the server side on how this can be done
there is thread in google groups about it uploading files with lot of useful code that discussion helped me very much in uploading files
QA
why does python pep strongly recommend spaces over tabs for indentation see on stack overflow and pep that the recommendation is to use spaces only for indentation in python programs can understand the need for consistent indentation and have felt that pain is there an underlying reason for spaces to be preferred would have thought that tabs were far easier to work with
the answer to the question is pep wants to make recommendation and has decided that since spaces are more popular it will strongly recommend spaces over tabs notes on pep pep says use spaces per indentation level its clear that this is the standard recommendation for really old code that you do not want to mess up you can continue to use space tabs its clear that there are some circumstances when tabs can be used never mix tabs and spaces this is clear prohibition of mixing think we all agree on this python can detect this and often chokes using the tt argument makes this an explicit error the most popular way of indenting python is with spaces only the second most popular way is with tabs only this clearly states that both are used just to be ultra clear you should still never mix spaces and tabs in same file for new projects spaces only are strongly recommended over tabs this is clear recommendation and strong one but not prohibition of tabs cannot find good answer to my own question in pep use tabs which have used historically in other languages python accepts source with exclusive use of tabs that is good enough for me thought would have go at working with spaces in my editor configured file type to use spaces exclusively and so it inserts spaces if press tab if press tab too many times have to delete the spaces arrgh four times as many deletes as tabs my editor cannot tell that am using spaces for indents although an editor might be able to do this and obviously insists on deleting the spaces one at time could not python be told to consider tabs to be spaces when its reading indentations if we could agree on spaces per indentation and spaces per tab and allow python to accept this then there would be no problems we should find win win solutions to problems
QA
ocsp libraries for python java going back to my previous question on ocsp does anybody know of reliable ocsp libraries for python java and need client ocsp functionality as will be checking the status of certs against an ocsp responder so responder functionality is not that important thanks
have you check pyopenssl am sure openssl supports ocsp and python binding may support it
QA
crypto certificate parsing libraries for python any recommended crypto libraries for python know have asked something similar in certificate parsing libraries for java but should have split the question in two what need is the ability to parse certificates to extract the information contained in them looking around have found two options python openssl wrappers http sourceforge net projects pow pyopenssl of the two pyopenssl seems to be the most maintained but would like some feedback on anybody who might have experience with them
you might want to try keyczar as mentioned by me in your other post since that library actually has implementations for both python and java that would make it easier to use it in both contexts word of warning have not actually used this library so please take this with grain of salt
QA
why does python pep strongly recommend spaces over tabs for indentation see on stack overflow and pep that the recommendation is to use spaces only for indentation in python programs can understand the need for consistent indentation and have felt that pain is there an underlying reason for spaces to be preferred would have thought that tabs were far easier to work with
the main problems with indentation occur when you mix tabs and spaces obviously this does not tell you which you should choose but it is good reason to to recommend one even if you pick it by flipping coin however imho there are few minor reasons to favour spaces over tabs different tools sometimes code gets displayed outside of programmer editor eg posted to newsgroup or forum spaces generally do better than tabs here everywhere spaces would get mangled tabs do as well but not vice versa programmers see the source differently this is deeply subjective its either the main benefit of tabs or reason to avoid them depending on which side you are on on the plus side developers can view the source with their preferred indentation so developer preferring space indent can work with an space developer on the same source and still see it as they like the downside is that there are repercussions to this some people like space because it gives very visible feedback that they are too deeply nested they may see code checked in by the indenter constantly wrapping in their editor having every developer see the code the same way leads to more consistency wrt line lengths and other matters too continued line indentation sometimes you want to indent line to indicate it is carried from the previous one eg def foo some function with lots of args foo bar baz xyzzy blah if using tabs there is no way to align this for people using different tabstops in their editor without mixing spaces and tabs this effectively kills the above benefit obviously though this is deeply religious issue which programming is plagued with the most important issue is that we should choose one even if that is not the one you favour sometimes think that the biggest advantage of significant indentation is that at least we are spared brace placement flamewars also worth reading is this article by jamie zawinski on the issue
QA
why does python pep strongly recommend spaces over tabs for indentation see on stack overflow and pep that the recommendation is to use spaces only for indentation in python programs can understand the need for consistent indentation and have felt that pain is there an underlying reason for spaces to be preferred would have thought that tabs were far easier to work with
jwz says it best when people are reading code and when they are done writing new code they care about how many screen columns by which the code tends to indent when new scope or sexpr or whatever opens my opinion is that the best way to solve the technical issues is to mandate that the ascii tab character never appear in disk files program your editor to expand tabs to an appropriate number of spaces before writing the lines to disk this assumes that you never use tabs in places where they are actually significant like in string or character constants but never do that when it matters that it is tab always use instead
QA
ocsp libraries for python java going back to my previous question on ocsp does anybody know of reliable ocsp libraries for python java and need client ocsp functionality as will be checking the status of certs against an ocsp responder so responder functionality is not that important thanks
java has support of revocation checking via ocsp built in if you want to build an ocsp responder or have finer control over revocation checking check out bouncy castle you can use this to implement your own certpathchecker that for example uses non blocking in its status checks
QA
has anyone found good set of python plugins for vim specifically module completion am looking for suite of plugins that can help me finally switch over to vim full time right now am using komodo with some good success but their vim bindings have enough little errors that am tired of it what do love in komodo though is the code completion so here is what am looking for ordered by importance code completion meaning the ability to code complete modules functions etc in any module that is on the pythonpath not just system modules bonus points for showing docstrings when completing jump to class definition am guessing ctags will do this so how do you all manage automatically updating your tags files project type management for managing buffers ideally the ability to grep for filename in directory structure to open it bonus for showing an index of class definitions while buffer is open bzr integration not super important since most of it can just drop to the she will to do
here you can find some info about this it covers code completion having list of classes and functions in open files have not got around to do full configuration for vim since do not use python primarily but have the same interests in transforming vim in better python ide edit the original site is down so found it saved on the web archive
QA
significant figures in the decimal module so have decided to try to solve my physics homework by writing some python scripts to solve problems for me one problem that am running into is that significant figures do not always seem to come out properly for example this handles significant figures properly from decimal import decimal decimal decimal decimal but this does not decimal decimal decimal so two questions am right that this is not the expected amount of significant digits or do need to brush up on significant digit math is there any way to do this without having to set the decimal precision manually granted am sure can use numpy to do this but just want to know if there is way to do this with the decimal module out of curiosity
decimal defaults to places of precision the only way to limit the number of digits it returns is by altering the precision
QA
significant figures in the decimal module so have decided to try to solve my physics homework by writing some python scripts to solve problems for me one problem that am running into is that significant figures do not always seem to come out properly for example this handles significant figures properly from decimal import decimal decimal decimal decimal but this does not decimal decimal decimal so two questions am right that this is not the expected amount of significant digits or do need to brush up on significant digit math is there any way to do this without having to set the decimal precision manually granted am sure can use numpy to do this but just want to know if there is way to do this with the decimal module out of curiosity
decimals will not throw away decimal places like that if you really want to limit precision to then try decimal getcontext prec edit you can alternatively call quantize every time you multiply or divide addition and subtraction will preserve the dps
QA
significant figures in the decimal module so have decided to try to solve my physics homework by writing some python scripts to solve problems for me one problem that am running into is that significant figures do not always seem to come out properly for example this handles significant figures properly from decimal import decimal decimal decimal decimal but this does not decimal decimal decimal so two questions am right that this is not the expected amount of significant digits or do need to brush up on significant digit math is there any way to do this without having to set the decimal precision manually granted am sure can use numpy to do this but just want to know if there is way to do this with the decimal module out of curiosity
if undertand decimal correctly the precision is the number of digits after the decimal point in decimal notation you seem to want something else the number of significant digits that is one more than the number of digits after the decimal point in scientific notation would be interested in learning about python module that does significant digits aware floating point point computations
QA
significant figures in the decimal module so have decided to try to solve my physics homework by writing some python scripts to solve problems for me one problem that am running into is that significant figures do not always seem to come out properly for example this handles significant figures properly from decimal import decimal decimal decimal decimal but this does not decimal decimal decimal so two questions am right that this is not the expected amount of significant digits or do need to brush up on significant digit math is there any way to do this without having to set the decimal precision manually granted am sure can use numpy to do this but just want to know if there is way to do this with the decimal module out of curiosity
what is wrong with floating point it was designed for scientific style calculations with limited number of significant digits
QA
has anyone found good set of python plugins for vim specifically module completion am looking for suite of plugins that can help me finally switch over to vim full time right now am using komodo with some good success but their vim bindings have enough little errors that am tired of it what do love in komodo though is the code completion so here is what am looking for ordered by importance code completion meaning the ability to code complete modules functions etc in any module that is on the pythonpath not just system modules bonus points for showing docstrings when completing jump to class definition am guessing ctags will do this so how do you all manage automatically updating your tags files project type management for managing buffers ideally the ability to grep for filename in directory structure to open it bonus for showing an index of class definitions while buffer is open bzr integration not super important since most of it can just drop to the she will to do
here is some info on bazaar integration if you are interested https launchpad net bzr vim commands
QA
python postgresql modules which is best have seen number of postgresql modules for python like pygresql pypgsql psyco most of them are python db api compliant some are not being actively developed anymore which module do you recommend why
psycopg seems to be the most popular have never had any trouble with it there is actually pure python interface for postgresql too called bpgsql would not recommend it over psycopg but it is recently become capable enough to support django and is useful if you cannot compile modules
QA
significant figures in the decimal module so have decided to try to solve my physics homework by writing some python scripts to solve problems for me one problem that am running into is that significant figures do not always seem to come out properly for example this handles significant figures properly from decimal import decimal decimal decimal decimal but this does not decimal decimal decimal so two questions am right that this is not the expected amount of significant digits or do need to brush up on significant digit math is there any way to do this without having to set the decimal precision manually granted am sure can use numpy to do this but just want to know if there is way to do this with the decimal module out of curiosity
changing the decimal working precision to digits is not good idea unless you absolutely only are going to perform single operation you should always perform calculations at higher precision than the level of significance and only round the final result if you perform long sequence of calculations and round to the number of significant digits at each step errors will accumulate the decimal module does not know whether any particular operation is one in long sequence or the final result so it assumes that it should not round more than necessary ideally it would use infinite precision but that is too expensive so the python developers settled for digits once you have arrived at the final result what you probably want is quantize decimal decimal quantize decimal decimal you have to keep track of significance manually if you want automatic significance tracking you should use interval arithmetic there are some libraries available for python including pyinterval and mpmath which supports arbitrary precision it is also straightforward to implement interval arithmetic with the decimal library since it supports directed rounding you may also want to read the decimal arithmetic faq is the decimal arithmetic significance arithmetic
QA
has anyone found good set of python plugins for vim specifically module completion am looking for suite of plugins that can help me finally switch over to vim full time right now am using komodo with some good success but their vim bindings have enough little errors that am tired of it what do love in komodo though is the code completion so here is what am looking for ordered by importance code completion meaning the ability to code complete modules functions etc in any module that is on the pythonpath not just system modules bonus points for showing docstrings when completing jump to class definition am guessing ctags will do this so how do you all manage automatically updating your tags files project type management for managing buffers ideally the ability to grep for filename in directory structure to open it bonus for showing an index of class definitions while buffer is open bzr integration not super important since most of it can just drop to the she will to do
for refactoring ropevim
QA
can write native iphone apps using python using pyobjc you can use python to write cocoa applications for os can write native iphone apps using python and if so how
the iphone sdk agreement is also rather vague about whether you are even allowed to run scripting languages outside of webview javascript my reading is that it is ok as long as none of the scripts you execute are downloaded from the network so pre installed and user edited scripts seem to be ok ianal etc etc
QA
something like explorer icon grid view in python gui am making python gui project that needs to duplicate the look of windows gui environment ie explorer have my own custom icons to draw but they should be selectable by the same methods as usual click ctrl click drag box etc are any of the gui toolkits going to help with this or will have to implement it all myself if there are not any tools to help with this advice would be greatly appreciated edit am not trying to recreate explorer that would be madness simply want to be able to take icons and lay them out in scrollable window any number of them may be selected at once it would be great if there was something that could select deselect them in the same appearing at least way that windows does then all would need is list of all the selected icons
will assume you are serious and suggest that you check out the many wonderful gui libraries available for python
QA
something like explorer icon grid view in python gui am making python gui project that needs to duplicate the look of windows gui environment ie explorer have my own custom icons to draw but they should be selectable by the same methods as usual click ctrl click drag box etc are any of the gui toolkits going to help with this or will have to implement it all myself if there are not any tools to help with this advice would be greatly appreciated edit am not trying to recreate explorer that would be madness simply want to be able to take icons and lay them out in scrollable window any number of them may be selected at once it would be great if there was something that could select deselect them in the same appearing at least way that windows does then all would need is list of all the selected icons
python has extensions for accessing the win api but good luck trying to re write explorer in that by yourself your best bet is to use toolkit like qt but you will still have to write the vast majority of the application from scratch is there any way you can re use explorer itself in your project updated for edited question gtk has an icon grid widget that you could use see reference for pygtk gtk iconview
QA
something like explorer icon grid view in python gui am making python gui project that needs to duplicate the look of windows gui environment ie explorer have my own custom icons to draw but they should be selectable by the same methods as usual click ctrl click drag box etc are any of the gui toolkits going to help with this or will have to implement it all myself if there are not any tools to help with this advice would be greatly appreciated edit am not trying to recreate explorer that would be madness simply want to be able to take icons and lay them out in scrollable window any number of them may be selected at once it would be great if there was something that could select deselect them in the same appearing at least way that windows does then all would need is list of all the selected icons
in wxpython there is plethora of ready made list and tree controls customtreectrl treelistctrl and others mixture of which you can use to create simple explorer in minutes the wxpython demo even has few relevant examples see the demo of mvctree
QA
calling from python what would be the quickest way to construct python binding to or library using windows if this matters
the quickest way to do this is using swig example from swig tutorial file example int fact int if return else return fact interface file example module example put header files here or function declarations like below extern int fact int extern int fact int building python module on unix swig python example gcc fpic example example wrap usr local include python gcc shared example example wrap example so usage import example example fact note that you have to have python dev also in some systems python header files will be in usr include python based on the way you have installed it from the tutorial swig is fairly complete compiler with support for nearly every language feature this includes preprocessing pointers classes inheritance and even templates swig can also be used to package structures and classes into proxy classes in the target language exposing the underlying functionality in very natural manner
QA
calling from python what would be the quickest way to construct python binding to or library using windows if this matters
ve never used it but ve heard good things about ctypes if you re trying to use it with be sure to evade name mangling via extern thanks for the comment florian sch
QA
calling from python what would be the quickest way to construct python binding to or library using windows if this matters
this paper claiming python to be all scientist needs basically says first prototype everything in python then when you need to speed part up use swig and translate this part to
QA
calling from python what would be the quickest way to construct python binding to or library using windows if this matters
one of the official python documents contains details on extending python using even without the use of swig it quite straightforward and works perfectly well on windows
QA
calling from python what would be the quickest way to construct python binding to or library using windows if this matters
check out pyrex or cython they are python like languages for interfacing between and python
QA
calling from python what would be the quickest way to construct python binding to or library using windows if this matters
you should have look at boost python here is the short introdution taken from their website the boost python library is framework for interfacing python and it allows you to quickly and seamlessly expose classes functions and objects to python and vice versa using no special tools just your compiler it is designed to wrap interfaces non intrusively so that you should not have to change the code at all in order to wrap it making boost python ideal for exposing rd party libraries to python the library use of advanced metaprogramming techniques simplifies its syntax for users so that wrapping code takes on the look of kind of declarative interface definition language idl