prefix
stringclasses
1 value
input_text
stringlengths
19
27.3k
target_text
stringlengths
2
24.8k
QA
recommended data format for describing the rules of chess am going to be writing chess server and one or more clients for chess and want to describe the rules of chess allowable moves based on game state rules for when game is complete in programming language independant way this is bit tricky since some of the chess rules king castling en passent draws based on or more repeated moves are based not only on the board layout but also on the history of moves would prefer the format to be textual human readable based on standard yaml xml easily parsable in variety of languages but am willing to sacrifice any of these for suitable solution my main question is how can build algorithms of such complexity that operate on such complex state from data format followup queston is can you provide an example of similar problem solved in similar manner that can act as starting point edit in response to request for clarity consider that will have server written in python one client written in and another client written in java would like to avoid specifying the rules for allowable piece movement circumstances for check etc in each place would prefer to specify these rules once in language independant manner
there is already widely used format specific to chess called portable game notation there is also smart game format which is adaptable to many different games
QA
recommended data format for describing the rules of chess am going to be writing chess server and one or more clients for chess and want to describe the rules of chess allowable moves based on game state rules for when game is complete in programming language independant way this is bit tricky since some of the chess rules king castling en passent draws based on or more repeated moves are based not only on the board layout but also on the history of moves would prefer the format to be textual human readable based on standard yaml xml easily parsable in variety of languages but am willing to sacrifice any of these for suitable solution my main question is how can build algorithms of such complexity that operate on such complex state from data format followup queston is can you provide an example of similar problem solved in similar manner that can act as starting point edit in response to request for clarity consider that will have server written in python one client written in and another client written in java would like to avoid specifying the rules for allowable piece movement circumstances for check etc in each place would prefer to specify these rules once in language independant manner
would suggest prolog for describing the rules
QA
recommended data format for describing the rules of chess am going to be writing chess server and one or more clients for chess and want to describe the rules of chess allowable moves based on game state rules for when game is complete in programming language independant way this is bit tricky since some of the chess rules king castling en passent draws based on or more repeated moves are based not only on the board layout but also on the history of moves would prefer the format to be textual human readable based on standard yaml xml easily parsable in variety of languages but am willing to sacrifice any of these for suitable solution my main question is how can build algorithms of such complexity that operate on such complex state from data format followup queston is can you provide an example of similar problem solved in similar manner that can act as starting point edit in response to request for clarity consider that will have server written in python one client written in and another client written in java would like to avoid specifying the rules for allowable piece movement circumstances for check etc in each place would prefer to specify these rules once in language independant manner
drools has modern human readable rules implementation https www jboss org drools they have way users can enter their rules in excel lot more users can understand what is in excel than in other tools
QA
what are good rules of thumb for python imports am little confused by the multitude of ways in which you can import modules in python import import as from import have been reading up about scoping and namespaces but would like some practical advice on what is the best strategy under which circumstances and why should imports happen at module level or method function level in the init py or in the module code itself my question is not really answered by python packages import by class not file although it is obviously related
let me just paste part of conversation on django dev mailing list started by guido van rossum for example it is part of the google python style guides that all imports must import module not class or function from that module there are way more classes and functions than there are modules so recalling where particular thing comes from is much easier if it is prefixed with module name often multiple modules happen to define things with the same name so reader of the code does not have to go back to the top of the file to see from which module given name is imported source http groups google com group django developers browse thread thread cdfb http code google com soc wiki pythonstyleguide module and package imports
QA
python code organization question eggs packages buildout unit tests svn have several python projects that share common modules until now have been ahem keeping multiple copies of the common code and synchronizing by hand but would clearly prefer to do something else it looks to me now as if zc buildout maybe what need guess that what should be doing is putting each reusable component of my system into separate egg and then using buildout to assemble them into projects am also thinking that for any particular module should put the unit tests into separate package or egg so that am not also installing copies of the component unit tests in every project only want to unit test in place where my library is developed not where it is just being used so maybe want something like this projects lib tests code lib tests code app tests appcode app tests appcode etc where both app and app are independent applications with their own code and tests but are also including and using both lib and lib and lib test lib code lib test lib code app app are separate eggs does this sound right however now get confused assume that when develop app want buildout to pull copies of lib lib and app into separate working directory rather than put copies of these libraries under app directly but how does this work with my svn source control if the working directory is dynamically constructed with buildout it cannot be live svn directory from which can check the changes back into the repository have misunderstood how buildout is meant to be used would be better going for completely different approach how do you mix source control with module reuse between projects update thanks to the two people who have currently answered this question am experimenting more with this
this is why you have the site module it sets the internal sys path to include all packages and modules from lib site packages including directories eggs and pth files pythonpath this way there is exactly one working copy of your libraries there are an unlimited ways to make use of this here are two in each lib write setup py that deploys your lib properly when you make changes you do an svn up to collect the changes and python setup py install to deploy the one working copy that every application shares in each app either depend on things being in the pythonpath environment variable be sure that projects lib and projects lib are won the pythonpath each app then shares the one working copy of the various libraries
QA
what is the best way to open file for exclusive access in python what is the most elegant way to solve this open file for reading but only if it is not already opened for writing open file for writing but only if it is not already opened for reading or writing the built in functions work like this path scr txt file open path print file open file scr txt mode at file open path print file open file scr txt mode at file write file write file close scr txt now contains file close scr txt was overwritten and now contains on windows python the solution should work inside the same process like in the example above as well as when another process has opened the file it is preferred if crashing program will not keep the lock open
the solution should work inside the same process like in the example above as well as when another process has opened the file if by another process you mean whatever process not your program in linux there is no way to accomplish this relying only on system calls fcntl friends what you want is mandatory locking and the linux way to obtain it is bit more involved remount the partition that contains your file with the mand option mount remount mand dev hdxy set the sgid flag for your file chmod yourfile in your python code obtain an exclusive lock on that file fcntl flock fd fcntl lock ex now even cat will not be able to read the file until you release the lock
QA
python code organization question eggs packages buildout unit tests svn have several python projects that share common modules until now have been ahem keeping multiple copies of the common code and synchronizing by hand but would clearly prefer to do something else it looks to me now as if zc buildout maybe what need guess that what should be doing is putting each reusable component of my system into separate egg and then using buildout to assemble them into projects am also thinking that for any particular module should put the unit tests into separate package or egg so that am not also installing copies of the component unit tests in every project only want to unit test in place where my library is developed not where it is just being used so maybe want something like this projects lib tests code lib tests code app tests appcode app tests appcode etc where both app and app are independent applications with their own code and tests but are also including and using both lib and lib and lib test lib code lib test lib code app app are separate eggs does this sound right however now get confused assume that when develop app want buildout to pull copies of lib lib and app into separate working directory rather than put copies of these libraries under app directly but how does this work with my svn source control if the working directory is dynamically constructed with buildout it cannot be live svn directory from which can check the changes back into the repository have misunderstood how buildout is meant to be used would be better going for completely different approach how do you mix source control with module reuse between projects update thanks to the two people who have currently answered this question am experimenting more with this
have use the following structure quite effectively in svn lib branches tags trunk lib tests setup py lib branches tags trunk lib tests setup py app branches tags trunk app tests setup py app branches tags trunk app tests setup py would then create my dev workspace use eclipse pydev as follows checking out from either trunk or branch lib lib tests setup py lib lib tests setup py app app tests setup py app app tests setup py would then use either eclipse project dependencies setup python path which works well with eclipse code completion setup py also works but does not support having multiple workspaces well for deployment use create single zip with the following structure app lib py egg lib py egg app sitecustomize py app lib py egg lib py egg app sitecustomize py do not use setup install because want to support multiple versions of the app also have some control of the runtime environment so do not package python with my deployment but should be easy to add python into the deployment package if it is needed
QA
python decimal does anyone know of faster decimal implementation in python as example below demonstrates standard python decimal is times slower than float from timeit import timer def run val the class test the class for in xrange the class val test test test test test str abs if name main timer run float from decimal benchmark import run print float timeit timer run decimal from decimal benchmark import run from decimal import decimal print decimal timeit float decimal thanks maksim
the gmp library is one of the best arbitrary precision math libraries around and there is python binding available at gmpy would try that method
QA
running web app in grails vs django am currently in the planning stage for web application and find myself trying to decide on using grails or django from an operation perspective which ecosystem is easier to maintain migrations backup disaster recovery etc if using grails it will probably be typical tomcat mysql on linux if django it will be apache mysql on linux does django or grails have better choice of cheap and flexible hosting initially it will probably be low bandwidth requirements am not sure about the exact specs required but from what have been reading it seems like django would require far less server resources even mb server is ok than grails
think python tend to have lower hosting requirements grails needs jvm and most el cheapo hosts do not provide one where as they usually provide python support plus google app engine supports django to some extend but if you got the dough grails is so much better imho
QA
python decimal does anyone know of faster decimal implementation in python as example below demonstrates standard python decimal is times slower than float from timeit import timer def run val the class test the class for in xrange the class val test test test test test str abs if name main timer run float from decimal benchmark import run print float timeit timer run decimal from decimal benchmark import run from decimal import decimal print decimal timeit float decimal thanks maksim
you should compare decimal to long integer performance not floating point floating point is mostly hardware these days decimal is used for decimal precision while floating point is for wider range use the decimal package for monetary calculations to quote the decimal package manual decimal numbers can be represented exactly in contrast numbers like do not have an exact representation in binary floating point end users typically would not expect to display as as it does with binary floating point the exactness carries over into arithmetic in decimal floating point is exactly equal to zero in binary floating point result is while near to zero the differences prevent reliable equality testing and differences can accumulate for this reason decimal would be preferred in accounting applications which have strict equality invariants
QA
running web app in grails vs django am currently in the planning stage for web application and find myself trying to decide on using grails or django from an operation perspective which ecosystem is easier to maintain migrations backup disaster recovery etc if using grails it will probably be typical tomcat mysql on linux if django it will be apache mysql on linux does django or grails have better choice of cheap and flexible hosting initially it will probably be low bandwidth requirements am not sure about the exact specs required but from what have been reading it seems like django would require far less server resources even mb server is ok than grails
you can run grails in megs of ram many members of the community are doing so that being said would say in either platform you want much more ram than that to make sure your performant but might also reccomend checking out www linode com you can get quality hosting for very reasonable cost and adding bit of ram for grails will not break your budget also if your interested in cloud based solutions morph is hosting grails apps http developer mor ph grails like django but for the maturity of the platform and the amount of quality java work out there in terms of libaries and frameworks chose grails in truth think they are both good solutions but you cannot deny that your options are much greater with grails
QA
how can find the full path to font from its display name on mac am using the photoshop javascript api to find the fonts in given psd given font name returned by the api want to find the actual physical font file that that font name corresponds to on the disc this is all happening in python program running on osx so guess am looking for one of some photoshop javascript python function an osx api that can call from python
there must be method in cocoa to get list of fonts then you would have to use the pyobjc bindings to call it depending on what you need them for you could probably just use something like the following import os def get font list fonts for font path in library fonts os path expanduser library fonts if os path isdir font path fonts extend os path join font path cur font for cur font in os listdir font path return fonts
QA
running compiled python py exe as administrator in vista is it possible to programaticly run compiled python comiled via py exe as administrator in vista some more clarification have written program that modifies the windows hosts file windows system drivers etc hosts in vista the program will not run and will fail with an exception unless you right click and run as administrator even when the user has administrator privileges unlike in xp where it will run if the user has administration rights so need way to elevate it to the correct privileges programaticly
do you mean that you want windows to prompt for elevation when your program is run this is controlled by adding uac manifest to the exe resources this blog entry explains how to create the manifest and how to compile it into res file do not know what facilities py exe has for embedding custom res files so you might need to use the mt exe tool from the platform sdk to embed the manifest in your program mt exe does not need res files it can merge the manifest file directly
QA
how to avoid computation every time python module is reloaded have python module that makes use of huge dictionary global variable currently put the computation code in the top section every first time import or reload of the module takes more then one minute which is totally unacceptable how can save the computation result somewhere so that the next import reload does not have to compute it tried cpickle but loading the dictionary variable from file takes approximately the same time as computation to give more information about my problem fd freqdist word for word in brown words this line of code takes min
assume you have pasted the dict literal into the source and that is what is taking minute do not know how to get around that but you could probably avoid instantiating this dict upon import you could lazily instantiate it the first time it is actually used
QA
what is the time complexity of popping elements from list in python wonder what is the time complexity of pop method of list objects in python in cpython particulary also does the value of for list pop affects the complexity
pop for the last element ought to be since you only need to return the element referred to by the last element in the array and update the index of the last element would expect pop to be and require on average operations since you would need to move any elements beyond the nth one one position up in the array of pointers
QA
how to avoid computation every time python module is reloaded have python module that makes use of huge dictionary global variable currently put the computation code in the top section every first time import or reload of the module takes more then one minute which is totally unacceptable how can save the computation result somewhere so that the next import reload does not have to compute it tried cpickle but loading the dictionary variable from file takes approximately the same time as computation to give more information about my problem fd freqdist word for word in brown words this line of code takes min
you can use shelve to store your data on disc instead of loading the whole data into memory so startup time will be very fast but the trade off will be slower access time shelve will pickle the dict values too but will do the un pickle not at startup for all the items but only at access time for each item itself
QA
how to avoid computation every time python module is reloaded have python module that makes use of huge dictionary global variable currently put the computation code in the top section every first time import or reload of the module takes more then one minute which is totally unacceptable how can save the computation result somewhere so that the next import reload does not have to compute it tried cpickle but loading the dictionary variable from file takes approximately the same time as computation to give more information about my problem fd freqdist word for word in brown words this line of code takes min
calculate your global var on the first use class proxy property def global name self calculate your global var here enable cache if needed proxy object proxy global name proxy object global name or better yet access necessery data via special data object class data global name property data data example from some module import data print data global name see django settings
QA
how to avoid computation every time python module is reloaded have python module that makes use of huge dictionary global variable currently put the computation code in the top section every first time import or reload of the module takes more then one minute which is totally unacceptable how can save the computation result somewhere so that the next import reload does not have to compute it tried cpickle but loading the dictionary variable from file takes approximately the same time as computation to give more information about my problem fd freqdist word for word in brown words this line of code takes min
you could try using the marshal module instead of the pickle one it could be faster this module is used by python to store values in binary format note especially the following paragraph to see if marshal fits your needs not all python object types are supported in general only objects whose value is independent from particular invocation of python can be written and read by this module the following types are supported none integers long integers floating point numbers strings unicode objects tuples lists sets dictionaries and code objects where it should be understood that tuples lists and dictionaries are only supported as long as the values contained therein are themselves supported and recursive lists and dictionaries should not be written they will cause infinite loops just to be on the safe side before unmarshalling the dict make sure that the python version that unmarshals the dict is the same as the one that did the marshal since there are no guarantees for backwards compatibility
QA
standalone python applications in linux how can distribute standalone python application in linux think can take for granted the presence of recent python interpreter in any modern distribution the problem is dealing with those libraries that do not belong to the standard library wxpython scipy python cryptographic toolkit reportlab and so on is there working linux counterpart to say py exe which by the way have never tried is there free opensource one
setuptools is overkill for me since my program usage is quite limited so here is my homegrown alternative bundle third party directory that includes all prerequisites and use site addsitedir so they do not need to be installed globally program startup code import os import sys import site path os path abspath os path dirname file ver python sys version info thirdparty os path join path third party lib ver site packages site addsitedir thirdparty most of my prereqs have setup py installers each bundled module gets its own install process so any customized stuff configure can be run automatically my install script runs this makefile as part of the install process sample third party makefile python ver python import sys print python sys version info python path lib python ver site packages mods egenix mx base etc phony all init clean realclean mods all mods mods init init mkdir bin mkdir python path clean rm rf mods realclean clean rm rf bin rm rf lib egenix mx base tar xzf tar gz cd python setup py install prefix rm rf
QA
how to avoid computation every time python module is reloaded have python module that makes use of huge dictionary global variable currently put the computation code in the top section every first time import or reload of the module takes more then one minute which is totally unacceptable how can save the computation result somewhere so that the next import reload does not have to compute it tried cpickle but loading the dictionary variable from file takes approximately the same time as computation to give more information about my problem fd freqdist word for word in brown words this line of code takes min
expanding on the delayed calculation idea why not turn the dict into class that supplies and caches elements as necessary you might also use psyco to speed up overall execution
QA
what is the easiest way best tutorials to get familiar with sqlalchemy what are best resources tutorials for starting up with sqlalchemy maybe some simple step by step stuff like creating simple table and using it and going up from there
personally would buy this book and cram it into the noggin over the course of week or so have tried tackling sqlalchemy on the job without learning the details first had hard time with it because found the online documentation to be sparse and cryptic read the source for more info sa also provides several levels of abstraction at which you can work and was not confident that was ever working at the correct level
QA
how to avoid computation every time python module is reloaded have python module that makes use of huge dictionary global variable currently put the computation code in the top section every first time import or reload of the module takes more then one minute which is totally unacceptable how can save the computation result somewhere so that the next import reload does not have to compute it tried cpickle but loading the dictionary variable from file takes approximately the same time as computation to give more information about my problem fd freqdist word for word in brown words this line of code takes min
or you could just use database for storing the values in check out sqlobject which makes it very easy to store stuff to database
QA
what is the time complexity of popping elements from list in python wonder what is the time complexity of pop method of list objects in python in cpython particulary also does the value of for list pop affects the complexity
yes it is to pop the last element of python list and to pop an arbitrary element since the whole rest of the list has to be shifted here is great article on how python lists are stored and manipulated http effbot org zone python list htm
QA
how to avoid computation every time python module is reloaded have python module that makes use of huge dictionary global variable currently put the computation code in the top section every first time import or reload of the module takes more then one minute which is totally unacceptable how can save the computation result somewhere so that the next import reload does not have to compute it tried cpickle but loading the dictionary variable from file takes approximately the same time as computation to give more information about my problem fd freqdist word for word in brown words this line of code takes min
just to clarify the code in the body of module is not executed every time the module is imported it is run only once after which future imports find the already created module rather than recreating it take look at sys modules to see the list of cached modules however if your problem is the time it takes for the first import after the program is run you will probably need to use some other method than python dict probably best would be to use an on disk form for instance sqlite database one of the dbm modules for minimal change in your interface the shelve module may be your best option this puts pretty transparent interface between the dbm modules that makes them act like an arbitrary python dict allowing any picklable value to be stored here is an example create dict with million items import shelve shelve open path to my persistant dict update key for in xrange close then in the next process use it there should be no large delay as lookups are only performed for the key requested on the on disk form so everything does not have to get loaded into memory shelve open path to my persistant dict print key it is bit slower than real dict and it will still take long time to load if you do something that requires all the keys eg try to print it but may solve your problem
QA
in production apache mod wsgi or nginx mod wsgi what to use for medium to large python wsgi application apache mod wsgi or nginx mod wsgi which combination will need more memory and cpu time which one is faster which is known for being more stable than the other am also thinking to use cherrypy wsgi server but hear it is not very suitable for very high load application what do you know about this note did not use any python web framework just wrote the whole thing from scratch note other suggestions are also welcome
one thing that cherrypy webserver has going for it is that it is pure python webserver afaik which may or may not make deployment easier for you plus could see the benefits of using it if you are just using server for wsgi and static content shameless plug warning wrote the wsgi code that am about to mention kamaelia will have wsgi support coming in the next release the cool thing is that you will likely be able to either use the pre made one or build your own using the existing http and wsgi code end shameless plug with that said given the current options would personally probably go with cherrypy because it seems to be the simplest to configure and can understand python code moreso than can understand code you may do best to try each of them out and see what the pros and cons of each one are for your specific application though
QA
what is the easiest way best tutorials to get familiar with sqlalchemy what are best resources tutorials for starting up with sqlalchemy maybe some simple step by step stuff like creating simple table and using it and going up from there
probably the sqlalchemy orm tutorial started with it
QA
running compiled python py exe as administrator in vista is it possible to programaticly run compiled python comiled via py exe as administrator in vista some more clarification have written program that modifies the windows hosts file windows system drivers etc hosts in vista the program will not run and will fail with an exception unless you right click and run as administrator even when the user has administrator privileges unlike in xp where it will run if the user has administration rights so need way to elevate it to the correct privileges programaticly
following up roger lipscombe comment have used manifest file in py exe without any real knowledge of what was doing so this might work in setup py manifest copied from http blogs msdn com shawnfa archive aspx manifest assembly xmlns urn schemas microsoft com asm manifestversion asmv trustinfo xmlns asmv urn schemas microsoft com asm asmv security asmv requestedprivileges asmv requestedexecutionlevel level asinvoker uiaccess false asmv requestedprivileges asmv security asmv trustinfo assembly setup name myapp windows other resources manifest you may need to do some fiddling though
QA
how to avoid computation every time python module is reloaded have python module that makes use of huge dictionary global variable currently put the computation code in the top section every first time import or reload of the module takes more then one minute which is totally unacceptable how can save the computation result somewhere so that the next import reload does not have to compute it tried cpickle but loading the dictionary variable from file takes approximately the same time as computation to give more information about my problem fd freqdist word for word in brown words this line of code takes min
couple of things that will help speed up imports you might try running python using the oo flag when running python this will do some optimizations that will reduce import time of modules is there any reason why you could not break the dictionary up into smaller dictionaries in separate modules that can be loaded more quickly as last resort you could do the calculations asynchronously so that they will not delay your program until it needs the results or maybe even put the dictionary in separate process and pass data back and forth using ipc if you want to take advantage of multi core architectures with that said agree that you should not be experiencing any delay in importing modules after the first time you import it here are couple of other general thoughts are you importing the module within function if so this can lead to performance problems since it has to check and see if the module is loaded every time it hits the import statement is your program multi threaded have seen occassions where executing code upon module import in multi threaded app can cause some wonkiness and application instability most notably with the cgitb module if this is global variable be aware that global variable lookup times can be significantly longer than local variable lookup times in this case you can achieve significant performance improvement by binding the dictionary to local variable if you are using it multiple times in the same context with that said it is tad bit difficult to give you any specific advice without little bit more context more specifically where are you importing it and what are the computations
QA
mysqldb execute timeout sometimes in our production environment occurs situation when connection between service which is python program that uses mysqldb and mysql server is flacky some packages are lost some black magic happens and execute of mysqldb cursor object never ends or take great amount of time to end this is very bad because it is waste of service worker threads sometimes it leads to exhausting of workers pool and service stops responding at all so the question is is there way to interrupt mysqldb connection execute operation after given amount of time
if the communication is such problem consider writing proxy that receives your sql commands over the flaky connection and relays them to the mysql server on reliable channel maybe running on the same box as the mysql server this way you have total control over failure detection and retrying
QA
how to check if string in python is in ascii want to check whether string is in ascii or not am aware of ord however when try ord have typeerror ord expected character but string of length found understood it is caused by the way built python as explained in ord documentation is there another way to check
you could use the regular expression library which accepts the posix standard ascii definition
QA
how to check if string in python is in ascii want to check whether string is in ascii or not am aware of ord however when try ord have typeerror ord expected character but string of length found understood it is caused by the way built python as explained in ord documentation is there another way to check
think you are not asking the right question string in python has no property corresponding to ascii utf or any other encoding the source of your string whether you read it from file input from keyboard etc may have encoded unicode string in ascii to produce your string but that is where you need to go for an answer perhaps the question you can ask is is this string the result of encoding unicode string in ascii this you can answer by trying try mystring decode ascii except unicodedecodeerror print it was not ascii encoded unicode string else print it may have been an ascii encoded unicode string
QA
how to check if string in python is in ascii want to check whether string is in ascii or not am aware of ord however when try ord have typeerror ord expected character but string of length found understood it is caused by the way built python as explained in ord documentation is there another way to check
def is ascii return all ord for in
QA
why java and python garbage collection methods are different python uses the reference count method to handle object life time so an object that has no more use will be immediately destroyed but in java the gc garbage collector destroys objects which are no longer used at specific time why does java choose this strategy and what is the benefit from this is this better than the python approach
actually reference counting and the strategies used by the sun jvm are all different types of garbage collection algorithms there are two broad approaches for tracking down dead objects tracing and reference counting in tracing the gc starts from the roots things like stack references and traces all reachable live objects anything that cannot be reached is considered dead in reference counting each time reference is modified the object involved have their count updated any object whose reference count gets set to zero is considered dead with basically all gc implementations there are trade offs but tracing is usually good for high through put fast operation but has longer pause times larger gaps where the ui or program may freeze up reference counting can operate in smaller chunks but will be slower overall it may mean less freezes but poorer performance overall additionally reference counting gc requires cycle detector to clean up any objects in cycle that will not be caught by their reference count alone perl did not have cycle detector in its gc implementation and could leak memory that was cyclic research has also been done to get the best of both worlds low pause times high throughput http cs anu edu au steve blackburn pubs papers urc oopsla pdf
QA
in production apache mod wsgi or nginx mod wsgi what to use for medium to large python wsgi application apache mod wsgi or nginx mod wsgi which combination will need more memory and cpu time which one is faster which is known for being more stable than the other am also thinking to use cherrypy wsgi server but hear it is not very suitable for very high load application what do you know about this note did not use any python web framework just wrote the whole thing from scratch note other suggestions are also welcome
the main difference is that nginx is built to handle large numbers of connections in much smaller memory space this makes it very well suited for apps that are doing comet like connections that can have many idle open connections this also gives it quite smaller memory foot print from raw performance perspective nginx is faster but not so much faster that would include that as determining factor apache has the advantage in the area of modules available and the fact that it is pretty much standard any web host you go with will have it installed and most techs are going to be very familiar with it also if you use mod wsgi it is your wsgi server so you do not even need cherrypy other than that the best advice can give is try setting up your app under both and do some benchmarking since no matter what any one tells you your mileage may vary
QA
how do you design data models for bigtable datastore gae since the google app engine datastore is based on bigtable and we know that is not relational database how do you design database schema data model for applications that use this type of database system
you can use www web py com you build the model and the application once and it works on gae but also witl sqlite mysql posgres oracle mssql firebird
QA
how can search through stack overflow questions from script given string of keywords such as python best practices would like to obtain the first stack overflow questions that contain that keywords sorted by relevance say from python script my goal is to end up with list of tuples title url how can accomplish this would you consider querying google instead how would you do it from python
you could screen scrape the returned html from valid http request but that would result in bad karma and the loss of the ability to enjoy good night sleep
QA
how can search through stack overflow questions from script given string of keywords such as python best practices would like to obtain the first stack overflow questions that contain that keywords sorted by relevance say from python script my goal is to end up with list of tuples title url how can accomplish this would you consider querying google instead how would you do it from python
since stackoverflow already has this feature you just need to get the contents of the search results page and scrape the information you need here is the url for search by relevance http stackoverflow com search python best practices sort relevance if you view source you will see that the information you need for each question is on line like this href questions what are the best rss feeds for programmersdevelopers class answer title what are the best rss feeds for programmers developers so you should be able to get the first ten by doing regex search for string of that form
QA
how can search through stack overflow questions from script given string of keywords such as python best practices would like to obtain the first stack overflow questions that contain that keywords sorted by relevance say from python script my goal is to end up with list of tuples title url how can accomplish this would you consider querying google instead how would you do it from python
suggest that rest api be added to so http stackoverflow uservoice com
QA
what is the best way to escape python strings in php have php application which needs to output python script more specifically bunch of variable assignment statements eg subject prefix this string from user input msg footer this one too the contents of subject prefix et al need to be written to take user input as such need to escape the contents of the strings writing something like the following is not going to cut it we are stuffed as soon as someone uses quote or newline or anything else that am not aware of that could be hazardous echo subject prefix subject prefix so any ideas rewriting the app in python is not possible due to time constraints edit years later this was for integration between web app written in php and mailman written in python could not modify the install of the latter so needed to come up with way to talk in its language to manage its configuration this was also really bad idea
would start by standardizing the string type was using in python to use triple quoted strings this should reduce the incidents of problems from stray quotes in the input you will still need to escape it of course but it should reduce the number of issues that are concern what did to escape the strings would somewhat depend on what am worried about getting slipped in and the context that they are getting printed out again if you are just worried about quotes causing problems you could simply check for and occurrences of and escape them on the other hand if was worried about the input itself being malicious and it is user input so you probably should then would look at options like strip tags or other similar functions
QA
which aes library to use in ruby python need to be able to send encrypted data between ruby client and python server and vice versa and have been having trouble with the ruby aes gem library the library is very easy to use but we have been having trouble passing data between it and the pycrypto aes library for python these libraries seem to be fine when they are the only one being used but they do not seem to play well across language boundaries any ideas edit we are doing the communication over soap and have also tried converting the binary data to base to no avail also it is more that the encryption decryption is almost but not exactly the same between the two the lengths differ by one or there is extra garbage characters on the end of the decrypted string
kind of depends on how you are transferring the encrypted data it is possible that you are writing file in one language and then trying to read it in from the other python especially on windows requires that you specify binary mode for binary files so in python assuming you want to decrypt there you should open the file like this open path to file rb the indicates binary and if you are writing the encrypted data to file from python open path to file wb write encrypted data
QA
how can search through stack overflow questions from script given string of keywords such as python best practices would like to obtain the first stack overflow questions that contain that keywords sorted by relevance say from python script my goal is to end up with list of tuples title url how can accomplish this would you consider querying google instead how would you do it from python
would just use pycurl to concatenate the search terms onto the query uri
QA
open source alternative to matlab fmincon function is there an open source alternative to matlab fmincon function for constrained linear optimization am rewriting matlab program to use python numpy scipy and this is the only function have not found an equivalent to numpy based solution would be ideal but any language will do
is your problem convex linear non linear agree that scipy optimize will probably do the job but fmincon is sort of bazooka for solving optimization problems and you will be better off if you can confine it to one of the categories below in increasing level of difficulty to solve efficiently linear program lp quadratic program qp convex quadratically constrained quadratic program qcqp second order cone program socp semidefinite program sdp non linear convex problem non convex problem there are also combinatoric problems such as mixed integer linear programs milp but you did not mention any sort of integrality constraints suffice to say that they fall into different class of problems the cvxopt package will be of great use to you if your problem is convex if your problem is not convex you need to choose between finding local solution or the global solution many convex solvers sort of work in non convex domain finding good approximation to the global solution would require some form simulated annealing or genetic algorithm finding the global solution will require an enumeration of all local solutions or combinatorial strategy such as branch and bound
QA
how do emulate python named printf parameters in ruby in python you can do this print hi am name and am age years old name brian age what is the closest simplest ruby idiom to replicate this behavior no monkeypatching the string class please edit one of the really excellent benefits of this is that you can store the pre processed string in variable and use it as template like so template hi am name and am age years old def greet template name age print template name name age age this is obviously trivial example but there is lot of utility in being able to store such string for later use ruby hi am name convention is cursorily similar but the immediate evaluation makes it less versatile please do not downvote answers suggesting the var technique as they came from before this edit random idea kernel perhaps answers should be protected from votes if question author marks them as outdated
in double quoted string in ruby you can insert the result of ruby expression like this puts hi am name and am age years old just put an expression inside the curly braces it could also be something more complex like age or name last name or function call
QA
how do emulate python named printf parameters in ruby in python you can do this print hi am name and am age years old name brian age what is the closest simplest ruby idiom to replicate this behavior no monkeypatching the string class please edit one of the really excellent benefits of this is that you can store the pre processed string in variable and use it as template like so template hi am name and am age years old def greet template name age print template name name age age this is obviously trivial example but there is lot of utility in being able to store such string for later use ruby hi am name convention is cursorily similar but the immediate evaluation makes it less versatile please do not downvote answers suggesting the var technique as they came from before this edit random idea kernel perhaps answers should be protected from votes if question author marks them as outdated
puts hi am name and am age years old
QA
how can search through stack overflow questions from script given string of keywords such as python best practices would like to obtain the first stack overflow questions that contain that keywords sorted by relevance say from python script my goal is to end up with list of tuples title url how can accomplish this would you consider querying google instead how would you do it from python
from urllib import urlencode params urlencode python best practices sort relevance params python best practices sort relevance from urllib import urlopen html urlopen http stackoverflow com search params read import re links re findall href class answer title html links questions what are the best rss feeds for programmersdevelopers what are the best rss feeds for programmers developers questions best ways to teach beginner to program best ways to teach beginner to program questions textual versus graphical programming languages textual versus graphical programming languages questions what defines pythonian or pythonic what defines pythonian or pythonic questions cxoracle how do access oracle from python cx oracle how do access oracle from python questions recommendation for straight forward python frameworks recommendation for straight forward python frameworks questions why is if not someobj better than if someobj none in python why is if not someobj better than if someobj none in python questions presentations on switching from perl to python presentations on switching from perl to python questions after python or java after python or java from urlparse import urljoin links urljoin http stackoverflow com url title for url title in links links http stackoverflow com questions what are the best rss feeds for programmersdevelopers what are the best rss feeds for programmers developers http stackoverflow com questions best ways to teach beginner to program best ways to teach beginner to program http stackoverflow com questions textual versus graphical programming languages textual versus graphical programming languages http stackoverflow com questions what defines pythonian or pythonic what defines pythonian or pythonic http stackoverflow com questions cxoracle how do access oracle from python cx oracle how do access oracle from python http stackoverflow com questions recommendation for straight forward python frameworks recommendation for straight forward python frameworks http stackoverflow com questions why is if not someobj better than if someobj none in python why is if not someobj better than if someobj none in python http stackoverflow com questions presentations on switching from perl to python presentations on switching from perl to python http stackoverflow com questions after python or java after python or java converting this to function should be trivial edit heck will do it def get stackoverflow query import urllib urllib re urlparse params urllib urlencode query sort relevance html urllib urlopen http stackoverflow com search params read links re findall href class answer title html links urlparse urljoin http stackoverflow com url title for url title in links return links
QA
how do emulate python named printf parameters in ruby in python you can do this print hi am name and am age years old name brian age what is the closest simplest ruby idiom to replicate this behavior no monkeypatching the string class please edit one of the really excellent benefits of this is that you can store the pre processed string in variable and use it as template like so template hi am name and am age years old def greet template name age print template name name age age this is obviously trivial example but there is lot of utility in being able to store such string for later use ruby hi am name convention is cursorily similar but the immediate evaluation makes it less versatile please do not downvote answers suggesting the var technique as they came from before this edit random idea kernel perhaps answers should be protected from votes if question author marks them as outdated
there are some nice trick to this in ruby name peter age instance variable puts hi you are name and your age is age
QA
how can quantify difference between two images here is what would like to do am taking pictures with webcam at regular intervals sort of like time lapse thing however if nothing has really changed that is the picture pretty much looks the same do not want to store the latest snapshot imagine there is some way of quantifying the difference and would have to empirically determine threshold am looking for simplicity rather than perfection am using python
you can compare two images using functions from pil import image import imagechops im image open splash png im image open splash png different imagechops difference im im the different object is an image in which every pixel is the result of the subtraction of the color values of that pixel in the second image from the first image using the different image you can do several things the simplest one is the different getbbox function it will tell you the minimal rectangle that contains all the changes between your two images you can probably implement approximations of the other stuff mentioned here using functions from pil as well
QA
mysqldb execute timeout sometimes in our production environment occurs situation when connection between service which is python program that uses mysqldb and mysql server is flacky some packages are lost some black magic happens and execute of mysqldb cursor object never ends or take great amount of time to end this is very bad because it is waste of service worker threads sometimes it leads to exhausting of workers pool and service stops responding at all so the question is is there way to interrupt mysqldb connection execute operation after given amount of time
you need to analyse exactly what the problem is mysql connections should eventually timeout if the server is gone tcp keepalives are generally enabled you may be able to tune the os level tcp timeouts if the database is flaky then you definitely need to investigate how it seems unlikely that the database really is the problem more likely that networking in between is if you are using some stateful firewalls of any kind it is possible that they are losing some of the state thus causing otherwise good long lived connections to go dead you might want to consider changing the idle timeout parameter in mysql otherwise long lived unused connection may go stale where the server and client both think it is still alive but some stateful network element in between has forgotten about the tcp connection an application trying to use such stale connection will have long wait before receiving an error but it should eventually
QA
which aes library to use in ruby python need to be able to send encrypted data between ruby client and python server and vice versa and have been having trouble with the ruby aes gem library the library is very easy to use but we have been having trouble passing data between it and the pycrypto aes library for python these libraries seem to be fine when they are the only one being used but they do not seem to play well across language boundaries any ideas edit we are doing the communication over soap and have also tried converting the binary data to base to no avail also it is more that the encryption decryption is almost but not exactly the same between the two the lengths differ by one or there is extra garbage characters on the end of the decrypted string
it is hard to even guess at what is happening without more information if were you would check that in your python and ruby programs the keys are the same obviously dump them as hex and compare each byte the initialization vectors are the same this is the parameter iv in aes new in pycrypto dump them as hex too the modes are the same the parameter mode in aes new in pycrypto there are defaults for iv and mode in pycrypto but do not trust that they are the same as in the ruby implementation use one of the simpler modes like cbc have found that different libraries have different interpretations of how the mode complex modes such as ptr work wikipedia has great article about how block cipher modes
QA
which aes library to use in ruby python need to be able to send encrypted data between ruby client and python server and vice versa and have been having trouble with the ruby aes gem library the library is very easy to use but we have been having trouble passing data between it and the pycrypto aes library for python these libraries seem to be fine when they are the only one being used but they do not seem to play well across language boundaries any ideas edit we are doing the communication over soap and have also tried converting the binary data to base to no avail also it is more that the encryption decryption is almost but not exactly the same between the two the lengths differ by one or there is extra garbage characters on the end of the decrypted string
turns out what happened was that ruby aes automatically pads data to fill up chars and sticks null character on the end of the final string as delimiter pycrypto requires you to do multiples of chars so that was how we figured out what ruby aes was doing
QA
how to check if os is vista in python how in the simplest possible way distinguish between windows xp and windows vista using python and pywin or wxpython essentially need function that called will return true iff current os is vista iswindowsvista true
the simplest solution found is this one import sys def iswindowsvista return true iff current os is windows vista if sys platform win return false import win api ver nt workstation version win api getversionex if not version or len version return false return version and version and version ver nt workstation
QA
how to ensure user submit only english text am building project involving natural language processing since the nlp module currently only deal with english text so have to make sure the user submitted content not long only several words is in english are there established ways to achieve this python or javascript way preferred
you could break the phrase up into words and check dictionary there are some that you can download this may be of interest but that would require that the dictionary you used was good enough it would also fall over for proper nouns my name is not in the dictionary for example
QA
how to ensure user submit only english text am building project involving natural language processing since the nlp module currently only deal with english text so have to make sure the user submitted content not long only several words is in english are there established ways to achieve this python or javascript way preferred
if the content is long enough would suggest some frequency analysis on the letters but for few words think your best bet is to compare them to an english dictionary and accept the input if half of them match
QA
how to ensure user submit only english text am building project involving natural language processing since the nlp module currently only deal with english text so have to make sure the user submitted content not long only several words is in english are there established ways to achieve this python or javascript way preferred
try http wordlist sourceforge net for list of english words you will need to be careful of names canberra or bill clinton these will not appear in the word list suggest just checking whether the first letter is capitalized as first attempt
QA
how to check if os is vista in python how in the simplest possible way distinguish between windows xp and windows vista using python and pywin or wxpython essentially need function that called will return true iff current os is vista iswindowsvista true
the solution used in twisted which does not need pywin def isvista if getattr sys getwindowsversion none is not none return sys getwindowsversion else return false note that it will also match windows server
QA
what is the best way to escape python strings in php have php application which needs to output python script more specifically bunch of variable assignment statements eg subject prefix this string from user input msg footer this one too the contents of subject prefix et al need to be written to take user input as such need to escape the contents of the strings writing something like the following is not going to cut it we are stuffed as soon as someone uses quote or newline or anything else that am not aware of that could be hazardous echo subject prefix subject prefix so any ideas rewriting the app in python is not possible due to time constraints edit years later this was for integration between web app written in php and mailman written in python could not modify the install of the latter so needed to come up with way to talk in its language to manage its configuration this was also really bad idea
another option may be to export the data as array or object as json string and modify the python code slightly to handle the new input while the escaping via json is not bulletproof it will be still better than own escaping routines and you will be able to handle errors if the json string is malformatted there is package for python to encode and decode json python json
QA
how to ensure user submit only english text am building project involving natural language processing since the nlp module currently only deal with english text so have to make sure the user submitted content not long only several words is in english are there established ways to achieve this python or javascript way preferred
think the most effective way would be to ask the users to submit english text only you can show language selection drop down over your text area with english other as the options when user selects other disable the text area with message that only english language is supported at the moment
QA
how to ensure user submit only english text am building project involving natural language processing since the nlp module currently only deal with english text so have to make sure the user submitted content not long only several words is in english are there established ways to achieve this python or javascript way preferred
check the language recognition chart
QA
can you list the keyword arguments python function receives have dict which need to pass key values as keyword arguments for example args kw value kw value example args this works fine but if there are values in the args dict that are not accepted by the example function it obviously dies say if the example function is defined as def example kw this is problem since do not control either the generation of the args or the example function they both come from external modules and example only accepts some of the keyword arguments from the dict ideally would just do parsed kwargs feedparser parse the url valid kwargs get valid kwargs parsed kwargs valid for pyrss gen rss pyrss gen rss valid kwargs will probably just filter the dict from list of valid keyword arguments but was wondering is there way to programatically list the keyword arguments the specific function takes
this will print names of all passable arguments keyword and non keyword ones def func one two value one two return print func func code co varnames func func code co argcount this is because first co varnames are always parameters next are local variables like in the example above so now you could have function def getvalidargs func argsdict return dictionary without invalid function arguments validargs func func code co varnames func func code co argcount return dict key value for key value in argsdict iteritems if key in validargs which you then could use like this func getvalidargs func args edit small addition if you really need only keyword arguments of function you can use the func defaults attribute to extract them def getvalidkwargs func argsdict validargs func func code co varnames func func code co argcount kwargslen len func func defaults number of keyword arguments validkwargs validargs kwargslen because kwargs are last return dict key value for key value in argsdict iteritems if key in validkwargs you could now call your function with known args but extracted kwargs func param param getvalidkwargs func kwargsdict this assumes that func uses no args or kwargs magic in its signature
QA
can you list the keyword arguments python function receives have dict which need to pass key values as keyword arguments for example args kw value kw value example args this works fine but if there are values in the args dict that are not accepted by the example function it obviously dies say if the example function is defined as def example kw this is problem since do not control either the generation of the args or the example function they both come from external modules and example only accepts some of the keyword arguments from the dict ideally would just do parsed kwargs feedparser parse the url valid kwargs get valid kwargs parsed kwargs valid for pyrss gen rss pyrss gen rss valid kwargs will probably just filter the dict from list of valid keyword arguments but was wondering is there way to programatically list the keyword arguments the specific function takes
extending dzinx answer argnames example func code co varnames func func code co argcount args dict key val for key val in args iteritems if key in argnames example args
QA
how to ensure user submit only english text am building project involving natural language processing since the nlp module currently only deal with english text so have to make sure the user submitted content not long only several words is in english are there established ways to achieve this python or javascript way preferred
try gram based statistical language recognition this is link to demo of an algorithm using this technique there is also link to paper describing the algorithm there try the demo it performs quite well even on very short texts words
QA
how to find out whether subversion working directory is locked by svn python script is running two parallel python processes created via os fork each of which eventually tries to check out subversion repository leaf into the same working copy dir before running svn co command in sub process via python subprocess module the parent python code checks if the working copy dir already exists if os path isdir checkout dir working copy dir already exists return checkout dir so that if it does there should not be any svn co running but rather immediate return from the parent function nevertheless some collision happened and one of the python processes failed on svn co with the following error checked out failed svn working copy tmp qm locked svn run svn cleanup to remove locks type svn help cleanup for details so the first question is why the working copy dir existence check did not work and the second is there way to find out that working copy dir is locked by svn and loop until it is unlocked thanks
within the directory there should be directory called svn within this file named locked indicates that the directory is locked
QA
can you list the keyword arguments python function receives have dict which need to pass key values as keyword arguments for example args kw value kw value example args this works fine but if there are values in the args dict that are not accepted by the example function it obviously dies say if the example function is defined as def example kw this is problem since do not control either the generation of the args or the example function they both come from external modules and example only accepts some of the keyword arguments from the dict ideally would just do parsed kwargs feedparser parse the url valid kwargs get valid kwargs parsed kwargs valid for pyrss gen rss pyrss gen rss valid kwargs will probably just filter the dict from list of valid keyword arguments but was wondering is there way to programatically list the keyword arguments the specific function takes
little nicer than inspecting the code object directly and working out the variables is to use the inspect module import inspect def func args kwargs pass inspect getargspec func args kwargs if you want to know if its callable with particular set of args you need the args without default already specified these can be got by def getrequiredargs func args varargs varkw defaults inspect getargspec func if defaults args args len defaults return args args and kwargs are not required so ignore them then function to tell what you are missing from your particular dict is def missingargs func argdict return set getrequiredargs func difference argdict similarly to check for invalid args use def invalidargs func argdict args varargs varkw defaults inspect getargspec func if varkw return set all accepted return set argdict set args and so full test if it is callable is def iscallablewithargs func argdict return not missingargs func argdict and not invalidargs func argdict this is good only as far as python arg parsing any runtime checks for invalid values in kwargs obviously cannot be detected
QA
how to ensure user submit only english text am building project involving natural language processing since the nlp module currently only deal with english text so have to make sure the user submitted content not long only several words is in english are there established ways to achieve this python or javascript way preferred
you are already doing nlp if your module does not understand what language the text was then either the module does not work or the input was not in the correct language
QA
how to ensure user submit only english text am building project involving natural language processing since the nlp module currently only deal with english text so have to make sure the user submitted content not long only several words is in english are there established ways to achieve this python or javascript way preferred
the dictionary switcher firefox extensions has an option to detect the right dictionary as type guess it checks words against the installed dictionaries and selects the one giving the less errors you cannot expect all words of the text to be in the dictionary abbreviations proper nouns typos beside some words are common to several languages french rock group even made the titles of their disks to have different meaning both in french and in english so it is statistical thing if more than of words are found in good english dictionary chances are the user types in this language even if there are mistakes like probably in this answer since am not native english
QA
can you list the keyword arguments python function receives have dict which need to pass key values as keyword arguments for example args kw value kw value example args this works fine but if there are values in the args dict that are not accepted by the example function it obviously dies say if the example function is defined as def example kw this is problem since do not control either the generation of the args or the example function they both come from external modules and example only accepts some of the keyword arguments from the dict ideally would just do parsed kwargs feedparser parse the url valid kwargs get valid kwargs parsed kwargs valid for pyrss gen rss pyrss gen rss valid kwargs will probably just filter the dict from list of valid keyword arguments but was wondering is there way to programatically list the keyword arguments the specific function takes
in python import inspect import fileinput print inspect getfullargspec fileinput input fullargspec args files inplace backup bufsize mode openhook varargs none varkw none defaults none none kwonlyargs kwdefaults none annotations
QA
how to make python command line program autocomplete arbitrary things not interpreter am aware of how to setup autocompletion of python objects in the python interpreter on unix google shows many hits for explanations on how to do this unfortunately there are so many references to that it is difficult to find what need to do which is slightly different need to know how to enable tab auto completion of arbitrary items in command line program written in python my specific use case is command line python program that needs to send emails want to be able to autocomplete email addresses have the addresses on disk when the user types part of it and optionally presses the tab key do not need it to work on windows or mac just linux
since you say not interpreter in your question guess you do not want answers involving python readline and suchlike edit in hindsight that is obviously not the case ho hum think this info is interesting anyway so will leave it here think you might be after this it is about adding she will level completion to arbitrary commands extending bash own tab completion in nutshell you will create file containing she will function that will generate possible completions save it into etc bash completion and register it with the command complete here is snippet from the linked page foo local cur prev opts compreply cur comp words comp cword prev comp words comp cword opts help verbose version if cur then compreply compgen opts cur return fi complete foo foo in this case the typing foo tab will give you the values in the variable opts help verbose and version for your purposes you will essentially want to customise the values that are put into opts do have look at the example on the linked page it is all pretty straightforward
QA
docstrings for data is there way to describe the module data in similar way that docstring describes module or funcion class myclass object def my function this docstring works return true my list this docstring does not work
to my knowledge it is not possible to assign docstrings to module data members pep suggests this feature but the pep was rejected suggest you document the data members of module in the module docstring module py about the module module data contains the word spam data spam
QA
which aes library to use in ruby python need to be able to send encrypted data between ruby client and python server and vice versa and have been having trouble with the ruby aes gem library the library is very easy to use but we have been having trouble passing data between it and the pycrypto aes library for python these libraries seem to be fine when they are the only one being used but they do not seem to play well across language boundaries any ideas edit we are doing the communication over soap and have also tried converting the binary data to base to no avail also it is more that the encryption decryption is almost but not exactly the same between the two the lengths differ by one or there is extra garbage characters on the end of the decrypted string
basically what hugh said above check the iv key sizes and the chaining modes to make sure everything is identical test both sides independantly encode some information and check that ruby and python endoded it identically you are assuming that the problem has to do with encryption but it may just be something as simple as sending the encrypted data with puts which throws random newlines into the data once you are sure they encrypt the data correctly check that you receive exactly what you think you sent keep going step by step until you find the stage that corrupts the data also would suggest using the openssl library that is included in ruby standard library instead of using an external gem
QA
which aes library to use in ruby python need to be able to send encrypted data between ruby client and python server and vice versa and have been having trouble with the ruby aes gem library the library is very easy to use but we have been having trouble passing data between it and the pycrypto aes library for python these libraries seem to be fine when they are the only one being used but they do not seem to play well across language boundaries any ideas edit we are doing the communication over soap and have also tried converting the binary data to base to no avail also it is more that the encryption decryption is almost but not exactly the same between the two the lengths differ by one or there is extra garbage characters on the end of the decrypted string
the lengths differ by one or there is extra garbage characters on the end of the decrypted string missed that bit there is nothing wrong with your encryption decryption it sounds like padding problem aes always encodes data in blocks of bits if the length of your data is not multiple of bits the data should be padded before encryption and the padding needs to be removed ignored after encryption
QA
docstrings for data is there way to describe the module data in similar way that docstring describes module or funcion class myclass object def my function this docstring works return true my list this docstring does not work
it is possible to make documentation of module data with use of epydoc syntax epydoc is one of the most frequently used documentation tools for python the syntax for documenting is above the variable initialization line like this module py very important data use with caution type str data important data now when you generate your documentation data will be described as module variable with given description and type str you can omit the type line
QA
running web app in grails vs django am currently in the planning stage for web application and find myself trying to decide on using grails or django from an operation perspective which ecosystem is easier to maintain migrations backup disaster recovery etc if using grails it will probably be typical tomcat mysql on linux if django it will be apache mysql on linux does django or grails have better choice of cheap and flexible hosting initially it will probably be low bandwidth requirements am not sure about the exact specs required but from what have been reading it seems like django would require far less server resources even mb server is ok than grails
think from an operations perspective things are going to be close enough that you can base your decision on other criteria if you can afford virtual private server with at least mb ram you will be able to deploy grails applications if the cost seems like lot check out sun they are really pushing hosting solutions based on their product stack and there are some greats deals available have free hosting from layered tech for year through ostatic
QA
dealing with string containing multiple character encodings am not exactly sure how to ask this question really and am no where close to finding an answer so hope someone can help me am writing python app that connects to remote host and receives back byte data which unpack using python built in struct module my problem is with the strings as they include multiple character encodings here is an example of such string lthis is an example gstring with multiple jcharacter encodings where the different encoding starts and ends is marked using special escape chars latin central europe turkish baltic japanese cyrillic greek and so on need way to convert this sort of string into unicode but am really not sure how to do it have read up on python codecs and string encode decode but am none the wiser really should mention as well that have no control over how the strings are outputted by the host hope someone can help me with how to get started on this
would write codec that incrementally scanned the string and decoded the bytes as they came along essentially you would have to separate strings into chunks with consistent encoding and decode those and append them to the strings that followed them
QA
what are the advantages of packaging your python library application as an egg file have read some about egg files and have noticed them in my lib directory but what are the advantages disadvantages of using then as developer
one egg by itself is not better than proper source release the good part is the dependency handling like debian or rpm packages you can say you depend on other eggs and they will be installed automatically through pypi python org second comment the egg format itself is binary packaged format normal python packages that consist of just python code are best distributed as source releases so python setup py sdist which result in tar gz these are also commonly called eggs when uploaded to pypi where you need binary eggs when you are bundling some code extension you will need several binary eggs bit unix one windows one etc then
QA
dealing with string containing multiple character encodings am not exactly sure how to ask this question really and am no where close to finding an answer so hope someone can help me am writing python app that connects to remote host and receives back byte data which unpack using python built in struct module my problem is with the strings as they include multiple character encodings here is an example of such string lthis is an example gstring with multiple jcharacter encodings where the different encoding starts and ends is marked using special escape chars latin central europe turkish baltic japanese cyrillic greek and so on need way to convert this sort of string into unicode but am really not sure how to do it have read up on python codecs and string encode decode but am none the wiser really should mention as well that have no control over how the strings are outputted by the host hope someone can help me with how to get started on this
there is no built in functionality for decoding string like this since it is really its own custom codec you simply need to split up the string on those control characters and decode it accordingly here is very slow example of such function that handles latin and shift jis latin latin japanese shift jis control control encodingmap control latin control japanese def funkydecode initialcodec latin output you accum currentcodec initialcodec for ch in if ch in encodingmap output accum decode currentcodec currentcodec encodingmap ch accum else accum ch output accum decode currentcodec return output faster version might use str split or regular expressions also as you can see in this example is the control character for newline so your input data is going to have some interesting restrictions
QA
dealing with string containing multiple character encodings am not exactly sure how to ask this question really and am no where close to finding an answer so hope someone can help me am writing python app that connects to remote host and receives back byte data which unpack using python built in struct module my problem is with the strings as they include multiple character encodings here is an example of such string lthis is an example gstring with multiple jcharacter encodings where the different encoding starts and ends is marked using special escape chars latin central europe turkish baltic japanese cyrillic greek and so on need way to convert this sort of string into unicode but am really not sure how to do it have read up on python codecs and string encode decode but am none the wiser really should mention as well that have no control over how the strings are outputted by the host hope someone can help me with how to get started on this
do not suppose you have any way of convincing the person who hosts the other machine to switch to unicode this is one of the reasons unicode was invented after all
QA
how to ensure user submit only english text am building project involving natural language processing since the nlp module currently only deal with english text so have to make sure the user submitted content not long only several words is in english are there established ways to achieve this python or javascript way preferred
google has javascript api that has an implementation of language detection have only play tested with it never used it in production http code google com apis ajaxlanguage documentation detect
QA
dealing with string containing multiple character encodings am not exactly sure how to ask this question really and am no where close to finding an answer so hope someone can help me am writing python app that connects to remote host and receives back byte data which unpack using python built in struct module my problem is with the strings as they include multiple character encodings here is an example of such string lthis is an example gstring with multiple jcharacter encodings where the different encoding starts and ends is marked using special escape chars latin central europe turkish baltic japanese cyrillic greek and so on need way to convert this sort of string into unicode but am really not sure how to do it have read up on python codecs and string encode decode but am none the wiser really should mention as well that have no control over how the strings are outputted by the host hope someone can help me with how to get started on this
you definitely have to split the string first into the substrings wih different encodings and decode each one separately just for fun the obligatory one line version import re encs latin iso decoded join substr decode encs substr for substr in re findall join encs keys st no error checking and also you will want to decide how to handle characters in substrings
QA
dealing with string containing multiple character encodings am not exactly sure how to ask this question really and am no where close to finding an answer so hope someone can help me am writing python app that connects to remote host and receives back byte data which unpack using python built in struct module my problem is with the strings as they include multiple character encodings here is an example of such string lthis is an example gstring with multiple jcharacter encodings where the different encoding starts and ends is marked using special escape chars latin central europe turkish baltic japanese cyrillic greek and so on need way to convert this sort of string into unicode but am really not sure how to do it have read up on python codecs and string encode decode but am none the wiser really should mention as well that have no control over how the strings are outputted by the host hope someone can help me with how to get started on this
here is relatively simple example of how do it coding utf import re test data encoding raw data latin you hello latin iso you dobr ve er central europe iso you yi ak amlar turkish iso you sveikat baltic shift jis you japanese iso you cyrillic iso you greek code to encoding dict chr ord code encoding for encoding code text in encoding raw data expected result you join line for line in encoding raw data encoded data join chr ord code text encode encoding for encoding code text in encoding raw data find re re compile def decode single bytes return bytes decode code to encoding bytes result you join decode single bytes for bytes in find re findall encoded data assert result expected result you expected but got expected result result
QA
how to check if string in python is in ascii want to check whether string is in ascii or not am aware of ord however when try ord have typeerror ord expected character but string of length found understood it is caused by the way built python as explained in ord documentation is there another way to check
how about doing this import string def isascii for in if not in string ascii letters return false return true
QA
how do you get output parameters from stored procedure in python have googled around bit but maybe did not put the correct magik incantation into the search box does anyone know how to get output parameters from stored procedure in python am using pymssql to call stored procedure and am not sure of the correct syntax to get the output parameter back do not think can use any other db modules since am running this from linux box to connect to mssql database on ms server import pymssql con pymssql connect host xxxxx user xxxx password xxxxx database xxxxx cur con cursor query execute blah blah blah cur execute query con commit con close
you might also look at using select rather than execute execute is iirc basically select that does not actually fetch anything just makes side effects happen
QA
python web application framework for tight db gui coupling am firm believer of the heretic thought of tight coupling between the backend and frontend want existing implied knowledge about backend to be automatically made use of when generating user interfaces if varchar column has maximum with of characters there guis should automatically constrain the user from typing more than characters in related form field and have strong antipathy to orms which want to define my database tables or are based on some hack where every table needs to have extra numeric id columns because of the orm have looked bit into python database frameworks and think can conclude the sqlalchemy fits best to my mentality now need to find web application framework which fits naturally with sqlalchemy or an equivalent and perhaps even with my appetite for coupling with web application framework mean products project such as pyhons django turbogears web py etc it should ideally be able to automatically select suitable form widget for data entering given column if told to do so if the column has foreign key to column with different values widget should display the possible values as dropdown auto generate javascript form validation code which gives the end user quick error feedback if string is entered into field which is about to end up in an integer column etc auto generate calendar widget for data which will end up in date column hint not null constraints as javascript which complains about empty or whitespace only data in related input field generate javascript validation code which matches relevant simple check constraints make it easy to avoid sql injection by using prepared statements and or validation of externally derived data make it easy to avoid cross site scripting by automatically escape outgoing strings when appropriate make use of constraint names to generate somewhat user friendly error messages in case constrataint is violated all this should happen dynamically so table adjustments are automatically reflected on the frontend probably with caching mechanism so that all the model introspection would not kill performance in other words do not want to repeat my model definition in an xml file or alike when it has already been carefully been defined in my database does such framework exist for python or for any language for that matter if not which of the several python web application frameworks will be least in the way if were to add parts of the above features myself
web py does most of what you ask based on field type and its validators it will render the field with the appropriate widget you can override with db table field widget and use third party widget web py has js to blocks the user from entering non integer in integer field or non double in double field time date and datetime fields have their own pickers these js validation work with not instead of server side validation there is is empty or validator the dal prevents sql injections since everthing is escaped when goes in the db web py prevents xss because in variable variable is escaped unless specified otherwise xml variable or xml variable sanitize true error messages are arguments of validators for example db table field requires is not empty error message hey write something in here is for internationalization
QA
how do you get output parameters from stored procedure in python have googled around bit but maybe did not put the correct magik incantation into the search box does anyone know how to get output parameters from stored procedure in python am using pymssql to call stored procedure and am not sure of the correct syntax to get the output parameter back do not think can use any other db modules since am running this from linux box to connect to mssql database on ms server import pymssql con pymssql connect host xxxxx user xxxx password xxxxx database xxxxx cur con cursor query execute blah blah blah cur execute query con commit con close
if you make your procedure produce table you can use that result as substitute for out params so instead of create procedure foo bar int out baz int out as begin stuff happens here return end do create procedure foo bar int baz int as begin stuff happens here select bar bar baz baz return end
QA
pylons with elixir would like to use pylons with elixir however am not sure what is the best way to get about doing this there are several blog posts cleverdevil beachcoder adam hoscilo and even an entire new framework about how to go about doing this however am not certain about the differences between them which one is the best to use am going to run into issues using one over the other would prefer not to have to use sqlalchemy directly because of its verbosity and repetitiveness
personally would go with beachcoder recipe as updated here that said with the possible exception of tesla which am not familiar with they are all lightweight enough that it should be easy to switch between them if you have any kind of trouble all the hard work is in your model
QA
get file object used by csv reader writer object is there any way to access the file object used by csv writer reader object after it has been instantiated openned up the csv module and it appears it is contest are builtin also tried setting the file object as property but get the following error attributeerror csv writer object has no attribute fileobj
csv writer is builtin function that is it is written in compiled code rather than python so its internal variables cannot be accessed from python code that being said am not sure why you would need to inspect the csv writer object to find out the file object that object is specified when creating the object csv writer fileobj dialect so if you need to access that object later just save it in another variable
QA
can pickle python dictionary into sqlite text field any gotchas should be aware of can store it in text field or do need to use blob am not overly familiar with either pickle or sqlite so wanted to make sure am barking up the right tree with some of my high level design ideas
if you want to store pickled object you will need to use blob since it is binary data however you can say base encode the pickled object to get string that can be stored in text field generally though doing this sort of thing is indicative of bad design since you are storing opaque data you lose the ability to use sql to do any useful manipulation on that data although without knowing what you are actually doing cannot really make moral call on it
QA
can pickle python dictionary into sqlite text field any gotchas should be aware of can store it in text field or do need to use blob am not overly familiar with either pickle or sqlite so wanted to make sure am barking up the right tree with some of my high level design ideas
since pickle can dump your object graph to string it should be possible be aware though that text fields in sqlite uses database encoding so you might need to convert it to simple string before you un pickle
QA
can pickle python dictionary into sqlite text field any gotchas should be aware of can store it in text field or do need to use blob am not overly familiar with either pickle or sqlite so wanted to make sure am barking up the right tree with some of my high level design ideas
pickle has both text and binary output formats if you use the text based format you can store it in text field but it will have to be blob if you use the more efficient binary format
QA
can pickle python dictionary into sqlite text field any gotchas should be aware of can store it in text field or do need to use blob am not overly familiar with either pickle or sqlite so wanted to make sure am barking up the right tree with some of my high level design ideas
if dictionary can be pickled it can be stored in text blob field as well just be aware of the dictionaries that cannot be pickled aka that contain unpickable objects
QA
how do emulate python named printf parameters in ruby in python you can do this print hi am name and am age years old name brian age what is the closest simplest ruby idiom to replicate this behavior no monkeypatching the string class please edit one of the really excellent benefits of this is that you can store the pre processed string in variable and use it as template like so template hi am name and am age years old def greet template name age print template name name age age this is obviously trivial example but there is lot of utility in being able to store such string for later use ruby hi am name convention is cursorily similar but the immediate evaluation makes it less versatile please do not downvote answers suggesting the var technique as they came from before this edit random idea kernel perhaps answers should be protected from votes if question author marks them as outdated
class template def hi am name and am age years old end end then call it with template new name peter age this is not exactly what you asked for but could give you hint
QA
standalone python applications in linux how can distribute standalone python application in linux think can take for granted the presence of recent python interpreter in any modern distribution the problem is dealing with those libraries that do not belong to the standard library wxpython scipy python cryptographic toolkit reportlab and so on is there working linux counterpart to say py exe which by the way have never tried is there free opensource one
the standard python way is to create python egg you could have look at this tutorial or this page about setuptools
QA
can pickle python dictionary into sqlite text field any gotchas should be aware of can store it in text field or do need to use blob am not overly familiar with either pickle or sqlite so wanted to make sure am barking up the right tree with some of my high level design ideas
yes you can store pickled object in text or blob field in an sqlite database as others have explained just be aware that some object cannot be pickled the built in container types can dict set list tuple etc but some objects such as file handles refer to state that is external to their own data structures and other extension types have similar problems since dictionary can contain arbitrary nested data structures it might not be pickle able
QA
python regex vs php regex no not competition it is instead me trying to find why certain regex works in one but not the other that is my regex and am trying to run it on using pythons regex get nothing using php match it below are the two calls am making just incase it is something to do with that essentially am trying to work out why it works in php but not python re findall regex string preg match all regex string matches solution found it was due to the way that was iterating through the results this regex turned them into groups and then it did not want to print them out in the same way etc etc thank you all for your help it is really appreciated
just because you can do it with regex does not mean you should it would be much better to write instructions like split the string on the period make sure each group is numeric and within certain range of numbers if you want to use regex just verify that it kind of looks like an ip address as with greg regex
QA
am looking for pythonic way to insert space before capital letters have got file whose format am altering via python script have several camel cased strings in this file where just want to insert single space before the capital letter so wordwordword becomes word word word my limited regex experience just stalled out on me can someone think of decent regex to do this or better yet is there more pythonic way to do this that am missing
you could try re sub wordwordword word word word
QA
am looking for pythonic way to insert space before capital letters have got file whose format am altering via python script have several camel cased strings in this file where just want to insert single space before the capital letter so wordwordword becomes word word word my limited regex experience just stalled out on me can someone think of decent regex to do this or better yet is there more pythonic way to do this that am missing
with regexes you can do this re sub str of course that will only work for ascii characters if you want to do unicode it is whole new can of worms
QA
am looking for pythonic way to insert space before capital letters have got file whose format am altering via python script have several camel cased strings in this file where just want to insert single space before the capital letter so wordwordword becomes word word word my limited regex experience just stalled out on me can someone think of decent regex to do this or better yet is there more pythonic way to do this that am missing
if there are consecutive capitals then gregs result could not be what you look for since the consumes the caracter in front of the captial letter to be replaced re sub wordwordwwwwwwword word word ww ww ww word look behind would solve this re sub wordwordwwwwwwword word word word
QA
am looking for pythonic way to insert space before capital letters have got file whose format am altering via python script have several camel cased strings in this file where just want to insert single space before the capital letter so wordwordword becomes word word word my limited regex experience just stalled out on me can someone think of decent regex to do this or better yet is there more pythonic way to do this that am missing
have look at my answer on net how can you split caps delimited string into an array edit maybe better to include it here re sub text for example simplehttpserver simple http server
QA
glade or no glade what is the best way to use pygtk have been learning python for while now with some success even managed to create one or two simple programs using pygtk glade the thing is am not sure if the best way to use gtk with python is by building the interfaces using glade was wondering if the more experienced ones among us remember am just beginner could point out the benefits and caveats of using glade as opposed to creating everything in the code itself assuming that learning the correct gtk bindings would not exactly be problem
for quick and simple screens use glade but for anything that needs finer levels of control create custom classes for what actually need this is important because it is too easy to get carried away with generalisations with skinny applications specific classes can rapidly change the look and feel application wide from single place rather like using css to mantain consistency for web sites
QA
docstrings for data is there way to describe the module data in similar way that docstring describes module or funcion class myclass object def my function this docstring works return true my list this docstring does not work
as codeape explains it is not possible to document general data members however it is possible to document property data members class foo def get foo self def set foo self val def del foo self foo property get foo set foo del foo doc string here this will give docstring to the foo attribute obviously
QA
can pickle python dictionary into sqlite text field any gotchas should be aware of can store it in text field or do need to use blob am not overly familiar with either pickle or sqlite so wanted to make sure am barking up the right tree with some of my high level design ideas
spoonmeiser is correct you need to have strong reason to pickle into database it is not difficult to write python objects that implement persistence with sqlite then you can use the sqlite cli to fiddle with the data as well which in my experience is worth the extra bit of work since many debug and admin functions can be simply performed from the cli rather than writing specific python code in the early stages of project did what you propose and ended up re writing with python class for each business object note did not say for each table this way the body of the application can focus on what needs to be done rather than how it is done