prefix
stringclasses 1
value | input_text
stringlengths 19
27.3k
⌀ | target_text
stringlengths 2
24.8k
⌀ |
---|---|---|
QA
|
send file using post from python script is there way to send file using post from python script
|
you may also want to have look at httplib with examples find using httplib is more concise than using the built in http modules
|
QA
|
send file using post from python script is there way to send file using post from python script
|
blatant self promotion check out my poster module for python it handles the multipart form data encoding as well as supporting streaming uploads so you do not have to load the entire file into memory before submitting the http post request
|
QA
|
random in python not working am trying to use the import random statement in python but it does not appear to have any methods in it to use am missing something
|
works for me python jun gcc red hat on linux type help copyright credits or license for more information import random brothers larry curly moe random choice brothers moe random choice brothers curly
|
QA
|
is there common way to check in python if an object is any function type have function in python which is iterating over the attributes returned from dir obj and want to check to see if any of the objects contained within is function method built in function etc normally you could use callable for this but do not want to include classes the best have come up with so far is isinstance obj types builtinfunctiontype types functiontype types methodtype is there more future proof way to do this check edit misspoke before when said normally you could use callable for this but do not want to disqualify classes actually do want to disqualify classes want to match only functions not classes
|
depending on what you mean by class callable obj and not inspect isclass obj or callable obj and not isinstance obj types classtype for example results are different for dict callable dict and not inspect isclass dict false callable dict and not isinstance dict types classtype true
|
QA
|
random in python not working am trying to use the import random statement in python but it does not appear to have any methods in it to use am missing something
|
you probably have file named random py or random pyc in your working directory that is shadowing the built in random module you need to rename random py to something like my random py and or remove the random pyc file to tell for sure what is going on do this import random print random file that will show you exactly which file is being imported
|
QA
|
how do get the name of python class as string what method do call to get the name of class
|
it is not method it is field the field is called name class name will give the name of the class as string object class name will give the name of the class of an object
|
QA
|
how do get the name of python class as string what method do call to get the name of class
|
in class test object pass in test name out test
|
QA
|
is there common way to check in python if an object is any function type have function in python which is iterating over the attributes returned from dir obj and want to check to see if any of the objects contained within is function method built in function etc normally you could use callable for this but do not want to include classes the best have come up with so far is isinstance obj types builtinfunctiontype types functiontype types methodtype is there more future proof way to do this check edit misspoke before when said normally you could use callable for this but do not want to disqualify classes actually do want to disqualify classes want to match only functions not classes
|
the inspect module has exactly what you want inspect isroutine obj fyi the code is def isroutine object return true if the object is any kind of function or method return isbuiltin object or isfunction object or ismethod object or ismethoddescriptor object
|
QA
|
how to use form values from an unbound form have web report that uses django form new forms for fields that control the query used to generate the report start date end date the issue am having is that the page should work using the form initial values unbound but cannot access the cleaned data field unless call is valid but is valid always fails on unbound forms it seems like django forms were designed with the use case of editing data such that an unbound form is not really useful for anything other than displaying html for example if have if request method get form myform else form myform request method post if form is valid do query form cleaned data start date form cleaned data end date is valid will fail if this is get since it is unbound and if do if request method get form myform do query form cleaned data start date form cleaned data end date else form myform request method post if form is valid do query form cleaned data start date form cleaned data end date the first call to do query triggers exceptions on form cleaned data which is not valid field because is valid has not been called it seems like have to do something like if request method get form myform do query form start date field initial form end date field initial else form myform request method post if form is valid do query form cleaned data start date form cleaned data end date that is there is not common interface for retrieving the form values between bound form and an unbound one does anyone see cleaner way to do this
|
you can pass dictionary of initial values to your form if request method get calculate my start date and my end date here form myform start date my start date end date my end date see the official forms api documentation where they demonstrate this edit based on answers from other users maybe this is the cleanest solution if request method get form myform form start date form start date field initial form end date form end date field initial else form myform request method post if form is valid do query form cleaned data start date form cleaned data end date have not tried this though can someone confirm that this works think this is better than creating new method because this approach does not require other code possibly not written by you to know about your new magic accessor
|
QA
|
how to use form values from an unbound form have web report that uses django form new forms for fields that control the query used to generate the report start date end date the issue am having is that the page should work using the form initial values unbound but cannot access the cleaned data field unless call is valid but is valid always fails on unbound forms it seems like django forms were designed with the use case of editing data such that an unbound form is not really useful for anything other than displaying html for example if have if request method get form myform else form myform request method post if form is valid do query form cleaned data start date form cleaned data end date is valid will fail if this is get since it is unbound and if do if request method get form myform do query form cleaned data start date form cleaned data end date else form myform request method post if form is valid do query form cleaned data start date form cleaned data end date the first call to do query triggers exceptions on form cleaned data which is not valid field because is valid has not been called it seems like have to do something like if request method get form myform do query form start date field initial form end date field initial else form myform request method post if form is valid do query form cleaned data start date form cleaned data end date that is there is not common interface for retrieving the form values between bound form and an unbound one does anyone see cleaner way to do this
|
if you add this method to your form class def get cleaned or initial self fieldname if hasattr self cleaned data return self cleaned data get fieldname else return self fieldname field initial you could then re write your code as if request method get form myform else form myform request method post form is valid do query form get cleaned or initial start date form get cleaned or initial end date
|
QA
|
django vs grails vs am wondering if there is such thing as django like ease of web app development combined with good deployment debugging and other tools django is very productive framework for building content heavy sites the best have tried and breath of fresh air compared to some of the java monstrosities out there however it is written in python which means there is little real support in the way of deployment packaging debugging profilers and other tools that make building and maintaining applications much easier ruby has similar issues and although do like ruby much better than like python get the impression that rails is roughly in the same boat at django when it comes to managing supporting the app has anyone here tried both django and grails or other web frameworks for non trivial projects how did they compare
|
cakephp org cakephp is really good really close to ruby on rails it is in php works very well on shared hosts and is easy to implement the only downside is that the documentation is somewhat lacking but you quickly get it and quickly start doing cool stuff totally recommend cakephp
|
QA
|
how to create triple join table with django using django built in models how would one create triple join between three models for example users roles and events are the models users have many roles and roles many users manytomany events have many users and users many events manytomany but for any given event any user may have only one role how can this be represented in the model
|
would model role as an association class between users and roles thus class user models model class event models model class role models model user models foreignkey user event models foreignkey event and enforce the one role per user per event in either manager or sql constraints
|
QA
|
terminating python script am aware of the die command in php which stops script early how can do this in python
|
while you should generally prefer sys exit because it is more friendly to other code all it actually does is raise an exception if you are sure that you need to exit process immediately and you might be inside of some exception handler which would catch systemexit there is another function os exit which terminates immediately at the level and does not perform any of the normal tear down of the interpreter for example hooks registered with the atexit module are not executed
|
QA
|
random in python not working am trying to use the import random statement in python but it does not appear to have any methods in it to use am missing something
|
is it possible that the script you run is called random py itself
|
QA
|
undo with gtk textview am trying to keep dependencies to minimum for program contribute to it is small text editor gtk textview does not seem to come with built in undo function is there any reference implementation have been missing on so far is everyone writing their own undo function for their textview widgets will be happy about any sample code most happy about python sample code as our project is in python
|
as far as know gtk textview does not include an undo function so while am not familiar with python gtk library would think it does not have one the ruby gnome project has sample text editor that has undo redo functionality basically they are connecting to the insert text and delete range signals of the textview widget and recording the events and associated data in list
|
QA
|
best python supported server client protocol am looking for good server client protocol supported in python for making data requests file transfers between one server and many clients security is also an issue so secure login would be plus have been looking into xml rpc but it looks to be pretty old and possibly unused these days protocol
|
if you are looking to do file transfers xmlrpc is likely bad choice it will require that you encode all of your data as xml and load it into memory data requests and file transfers sounds lot like plain old http to me but your statement of the problem does not make your requirements clear what kind of information needs to be encoded in the request would url like http yourserver example com service request color yellow flavor banana be good enough there are lots of http clients and servers in python none of which are especially great but all of which am sure will get the job done for basic file transfers you can do security the normal web way which is to use https and passwords which will probably be sufficient if you want two way communication then http falls down and protocol like twisted perspective broker pb or asynchronous messaging protocol amp might suit you better these protocols are certainly well supported by twisted
|
QA
|
which is faster python webpages or php webpages does anyone know how the speed of pylons or any of the other frameworks compares to similar website made with php know that serving python base webpage via cgi is slower than php because of its long start up every time enjoy using pylons and would still use it if it was slower than php but if pylons was faster than php could maybe hopefully eventually convince my employer to allow me to convert the site over to pylons
|
if it are not broke do not fix it just write quick test but bear in mind that each language will be faster with certain functions then the other
|
QA
|
which is faster python webpages or php webpages does anyone know how the speed of pylons or any of the other frameworks compares to similar website made with php know that serving python base webpage via cgi is slower than php because of its long start up every time enjoy using pylons and would still use it if it was slower than php but if pylons was faster than php could maybe hopefully eventually convince my employer to allow me to convert the site over to pylons
|
the only right answer is it depends there is lot of variables that can affect the performance and you can optimize many things in either situation
|
QA
|
libxml on os needs sudo when trying to use libxml as myself get an error saying the package cannot be found if run as as super user am able to import fine have installed python and all libxml and libxml py related libraries via fink and own the entire path including the library any ideas why would still need to sudo
|
the path was the mistake thanks was looking at everything else to be wrong
|
QA
|
which is faster python webpages or php webpages does anyone know how the speed of pylons or any of the other frameworks compares to similar website made with php know that serving python base webpage via cgi is slower than php because of its long start up every time enjoy using pylons and would still use it if it was slower than php but if pylons was faster than php could maybe hopefully eventually convince my employer to allow me to convert the site over to pylons
|
check out the programming languages shootout http dada perl it shootout
|
QA
|
where do the python unit tests go if you are writing library or an app where do the unit test files go it is nice to separate the test files from the main app code but it is awkward to put them into tests subdirectory inside of the app root directory because it makes it harder to import the modules that you will be testing is there best practice here
|
if the tests are simple simply put them in the docstring most of the test frameworks for python will be able to use that import module module method test testresult for other more involved tests would put them either in tests test module py or in tests test module py
|
QA
|
which is faster python webpages or php webpages does anyone know how the speed of pylons or any of the other frameworks compares to similar website made with php know that serving python base webpage via cgi is slower than php because of its long start up every time enjoy using pylons and would still use it if it was slower than php but if pylons was faster than php could maybe hopefully eventually convince my employer to allow me to convert the site over to pylons
|
you need to be able to make business case for switching not just that it is faster if site built on technology costs more in developer time for maintenance over set period say years it would likely be cheaper to add another webserver to the system running technology to bridge the performance gap just saying we should switch to technology because technology is faster does not really work since python is far less ubiquitous than php would not be surprised if hosting developer and other maintenance costs for it long term would have it fit this scenario
|
QA
|
which is faster python webpages or php webpages does anyone know how the speed of pylons or any of the other frameworks compares to similar website made with php know that serving python base webpage via cgi is slower than php because of its long start up every time enjoy using pylons and would still use it if it was slower than php but if pylons was faster than php could maybe hopefully eventually convince my employer to allow me to convert the site over to pylons
|
it is about the same the difference should not be large enough to be the reason to pick one or the other do not try to compare them by writing your own tiny benchmarks hello world because you will probably not have results that are representative of real web site generating more complex page
|
QA
|
which is faster python webpages or php webpages does anyone know how the speed of pylons or any of the other frameworks compares to similar website made with php know that serving python base webpage via cgi is slower than php because of its long start up every time enjoy using pylons and would still use it if it was slower than php but if pylons was faster than php could maybe hopefully eventually convince my employer to allow me to convert the site over to pylons
|
php and python are similiar enough to not warrent any kind of switching any performance improvement you might get from switching from one language to another would be vastly outgunned by simply not spending the money on converting the code you do not code for free right and just buy more hardware
|
QA
|
how do get the name of python class as string what method do call to get the name of class
|
in str class out type str in str len class out type builtin function or method in str class out type float or as was pointed out before in class name out float
|
QA
|
which is faster python webpages or php webpages does anyone know how the speed of pylons or any of the other frameworks compares to similar website made with php know that serving python base webpage via cgi is slower than php because of its long start up every time enjoy using pylons and would still use it if it was slower than php but if pylons was faster than php could maybe hopefully eventually convince my employer to allow me to convert the site over to pylons
|
there is no point in attempting to convince your employer to port from php to python especially not for an existing system which is what think you implied in your question the reason for this is that you already have presumably working system with an existing investment of time and effort and experience to discard this in favour of trivial performance gain not that am claiming there would be one would be foolish and no manager worth his salt ought to endorse it it may also create problem with maintainability depending on who else has to work with the system and their experience with python
|
QA
|
what does blazeds livecycle data services do that something like pyamf or rubyamf not do am doing tech review and looking at amf integration with various backends rails python grails etc lots of options are out there question is what do the adobe products do blazeds etc that something like rubyamf pyamf do not
|
good question am not ruby guy use java with flex but what believe differentiates blazeds vs commercial livecycle ds is streaming protocol support rtmp competition for comet and such delivering video some advanced stuff for hibernate detached objects and large resultset caching that do not fully understand or need support might be others but those are the ones know off the top of my head
|
QA
|
id is bad variable name in python why is it bad to name variable id in python
|
because it is the name of builtin function
|
QA
|
id is bad variable name in python why is it bad to name variable id in python
|
it is bad to name any variable after built in function one of the reasons is because it can be confusing to reader that does not know the name is overridden
|
QA
|
id is bad variable name in python why is it bad to name variable id in python
|
id is built in method in python assigning value to id will overwrite the method it is best to use either an identifier before as in some id or use it in different capitalization method the built in method takes single parameter and returns an integer for the memory address of the object that you passed id id
|
QA
|
id is bad variable name in python why is it bad to name variable id in python
|
id is fundamental built in help on built in function id in module builtin id id object integer return the identity of an object this is guaranteed to be unique among simultaneously existing objects hint it is the object memory address in general using variable names that eclipse keyword or built in function in any language is bad idea even if it is allowed
|
QA
|
django vs grails vs am wondering if there is such thing as django like ease of web app development combined with good deployment debugging and other tools django is very productive framework for building content heavy sites the best have tried and breath of fresh air compared to some of the java monstrosities out there however it is written in python which means there is little real support in the way of deployment packaging debugging profilers and other tools that make building and maintaining applications much easier ruby has similar issues and although do like ruby much better than like python get the impression that rails is roughly in the same boat at django when it comes to managing supporting the app has anyone here tried both django and grails or other web frameworks for non trivial projects how did they compare
|
however it is written in python which means there is little real support in the way of deployment packaging debugging profilers and other tools that make building and maintaining applications much easier python has great interactive debugger which makes very good use of python repl easy install anv virtualenv for dependency management packaging and deployment profiling features comparable to other languages so imho you should not worry about this things use python and django and live happily lucky for you newest version of django runs on jython so you do not need to leave your whole java ecosystem behind speaking of frameworks evaluated this year pylons python webpy python symfony php cakephp php none of this frameworks comes close to the power of django or ruby on rails based on my collegue opinion could recommend you kohana framework the downside is it is written in php and as far as know php does not have superb tools for debugging profiling and packaging of apps edit here is very good article about packaging and deployment of python apps specifically django apps it is hot topic in django community now
|
QA
|
ibatis for python at my current gig we use ibatis through java to crud our databases like the abstract qualities of the tool especially when working with legacy databases as it does not impose its own syntax on you am looking for python analogue to this library since the website only has java net ruby versions available do not want to have to switch to jython if do not need to are there any other projects similar to ibatis functionality out there for python
|
perhaps sqlalchemy sql expression support is suitable see the documentation
|
QA
|
how to create triple join table with django using django built in models how would one create triple join between three models for example users roles and events are the models users have many roles and roles many users manytomany events have many users and users many events manytomany but for any given event any user may have only one role how can this be represented in the model
|
zacherates writes would model role as an association class between users and roles would also reccomed this solution but you can also make use of some syntactical sugar provided by django manytomany relation with extra fields example class user models model name models charfield max length class event models model name models charfield max length members models manytomanyfield user through role def unicode self return self name class role models model person models foreignkey user group models foreignkey event date joined models datefield invite reason models charfield max length
|
QA
|
id is bad variable name in python why is it bad to name variable id in python
|
might say something unpopular here id is rather specialized built in function that is rarely used in business logic therefore do not see problem in using it as variable name in tight and well written function where it is clear that id does not mean the built in function
|
QA
|
best way to access table instances when using sqlalchemy declarative syntax all the docs for sqlalchemy give insert and update examples using the local table instance tablename update doing this seems difficult with the declarative syntax need to reference base metadata tables tablename to get the table reference am supposed to do this another way is there different syntax for insert and update recommended when using the declarative syntax should just switch to the old way
|
via the table attribute on your declarative class
|
QA
|
what is the best way to calculate or centroid as part of project at work have to calculate the centroid of set of points in space right now am doing it in way that seems simple but naive by taking the average of each set of points as in centroid average average average where and are arrays of floating point numbers seem to recall that there is way to get more accurate centroid but have not found simple algorithm for doing so anyone have any ideas or suggestions am using python for this but can adapt examples from other languages
|
nope that is the only formula for the centroid of collection of points see wikipedia http en wikipedia org wiki centroid
|
QA
|
what is the best way to calculate or centroid as part of project at work have to calculate the centroid of set of points in space right now am doing it in way that seems simple but naive by taking the average of each set of points as in centroid average average average where and are arrays of floating point numbers seem to recall that there is way to get more accurate centroid but have not found simple algorithm for doing so anyone have any ideas or suggestions am using python for this but can adapt examples from other languages
|
you can use increase accuracy summation kahan summation was that what you had in mind
|
QA
|
what is the best way to calculate or centroid as part of project at work have to calculate the centroid of set of points in space right now am doing it in way that seems simple but naive by taking the average of each set of points as in centroid average average average where and are arrays of floating point numbers seem to recall that there is way to get more accurate centroid but have not found simple algorithm for doing so anyone have any ideas or suggestions am using python for this but can adapt examples from other languages
|
yes that is the correct formula if you have large number of points you can exploit the symmetry of the problem be it cylindrical spherical mirror otherwise you can borrow from statistics and average random number of the points and just have bit of error
|
QA
|
python and re tutorial have on regex in python explains how to use the re module in python wanted to grab the url out of an tag so knowing regex wrote the correct expression and tested it in my regex testing app of choice and ensured it worked when placed into python it failed after much head scratching found out the issue it automatically expects your pattern to be at the start of the string have found fix but would like to know how to change regex regex of pure awesomeness into regex regex of pure awesomeness okay it is standard url regex but wanted to avoid any potential confusion about what wanted to get rid of and possibly pretend to be funny
|
from beautifulsoup import beautifulsoup soup beautifulsoup your html for in soup findall href true do something with href attribute print href
|
QA
|
ibatis for python at my current gig we use ibatis through java to crud our databases like the abstract qualities of the tool especially when working with legacy databases as it does not impose its own syntax on you am looking for python analogue to this library since the website only has java net ruby versions available do not want to have to switch to jython if do not need to are there any other projects similar to ibatis functionality out there for python
|
ibatis sequesters the sql dml or the definitions of the sql in an xml file it specifically focuses on the mapping between the sql and some object model defined elsewhere sql alchemy can do this but it is not really very complete solution like ibatis you can merely have sql table definitions and mapping between the tables and python class definitions what is more complete is to have class definition that is also the sql database definition if the class definition generates the sql table ddl as well as the query and processing dml that is much more complete flip flop between sqlalchemy and the django orm sqlalchemy can be used in an ibatis like manner but prefer to make the object design central and leave the sql implementation be derived from the objects by the toolset use sqlalchemy for large batch stand alone projects db loads schema conversions dw reporting and the like work out well in these projects the focus is on the relational view of the data not the object model the sql that is generated may be moved into pl sql stored procedures for example use django for web applications exploiting its built in orm capabilities you can with little work segregate the django orm from the rest of the django environment you can provide global settings to bind your app to specific database without using separate settings module django includes number of common relationships foreign key many to many one to one for which it can manage the sql implementation it generates key and index definitions for the attached database if your problem is largely object oriented with the database being used for persistence then the nearly transparent orm layer of django has advantages if your problem is largely relational with the sql processing central then the capability of seeing the generated sql in sqlalchemy has advantages
|
QA
|
random in python not working am trying to use the import random statement in python but it does not appear to have any methods in it to use am missing something
|
this is happening because you have random py file in the python search path most likely the current directory python is searching for modules using sys path which normally includes the current directory before the standard site packages which contains the expected random py this is expected to be fixed in python so that you cannot import modules from the current directory without using special import syntax just remove the random py random pyc in the directory you are running python from and it will work fine
|
QA
|
opengl user interface programming am developing graphical application to present data not game but real workhorse app it needs to be cross platform so have chosen python opengl need blending textures etc pyopengl wx pywx windowing dialogs etc the last component wx raises the question can put together very nice looking app the prototypes look slick but when need to interact with the user to ask questions get input have to use wx it makes the app look inconsistent to have traditional ui with traditional dialogs and combos and text entry on top of full screen app with blending smooth motion textures etc has anyone developed gui using opengl and python can you share with me the toolkits and or tricks you used need combos text entry buttons radios option buttons tree view there are some toolkits out there but they are either incomplete or old and unmaintained great example is pyui http pyui sourceforge net looks slick but untouched for years
|
you might want to look at clutter it looks pretty cool have not used it yet but intend to in an upcoming personal project
|
QA
|
opengl user interface programming am developing graphical application to present data not game but real workhorse app it needs to be cross platform so have chosen python opengl need blending textures etc pyopengl wx pywx windowing dialogs etc the last component wx raises the question can put together very nice looking app the prototypes look slick but when need to interact with the user to ask questions get input have to use wx it makes the app look inconsistent to have traditional ui with traditional dialogs and combos and text entry on top of full screen app with blending smooth motion textures etc has anyone developed gui using opengl and python can you share with me the toolkits and or tricks you used need combos text entry buttons radios option buttons tree view there are some toolkits out there but they are either incomplete or old and unmaintained great example is pyui http pyui sourceforge net looks slick but untouched for years
|
this is not an answer more of plea please do not do that your reimplemented widgets will lack all sorts of functionality that users will miss will your text entry boxes support drag drop copy paste right to left scripts drag select double click select will all these mechanisms follow the native conventions of each platform you support with wx your widgets might look inconsistant with the app but at least they will look consistant with the os which is just as important and more importantly they will do what users expect edit three posts and points screw this den of karma whores original poster have implemented basic set of widgets in opengl for game ui and it was an endless nightmare of job
|
QA
|
django vs grails vs am wondering if there is such thing as django like ease of web app development combined with good deployment debugging and other tools django is very productive framework for building content heavy sites the best have tried and breath of fresh air compared to some of the java monstrosities out there however it is written in python which means there is little real support in the way of deployment packaging debugging profilers and other tools that make building and maintaining applications much easier ruby has similar issues and although do like ruby much better than like python get the impression that rails is roughly in the same boat at django when it comes to managing supporting the app has anyone here tried both django and grails or other web frameworks for non trivial projects how did they compare
|
have two friends who originally started writing an application using ruby on rails but ran into number of issues and limitations after about weeks of working on it they decided to investigate other alternatives they settled on the catalyst framework and perl that was about months ago now and they have repeatedly talked about how much better the application is going and how much more flexibility they have with perl you have all of cpan available to you along with the large quantity of tools included would suggest taking look at it at least
|
QA
|
redirect command to input of another in python would like to replicate this in python gvimdiff hg cat file txt file txt hg cat file txt outputs the most recently committed version of file txt know how to pipe the file to gvimdiff but it will not accept another file hg cat file txt gvimdiff file txt too many edit arguments getting to the python part hgdiff py import subprocess import sys file sys argv subprocess call gvimdiff hg cat file file when subprocess is called it merely passes hg cat file onto gvimdiff as filename so is there any way to redirect command as bash does for simplicity sake just cat file and redirect it to different different cat file txt file txt
|
there is also the commands module import commands status output commands getstatusoutput gvimdiff hg cat file txt file txt there is also the popen set of functions if you want to actually grok the data from command as it is running
|
QA
|
redirect command to input of another in python would like to replicate this in python gvimdiff hg cat file txt file txt hg cat file txt outputs the most recently committed version of file txt know how to pipe the file to gvimdiff but it will not accept another file hg cat file txt gvimdiff file txt too many edit arguments getting to the python part hgdiff py import subprocess import sys file sys argv subprocess call gvimdiff hg cat file file when subprocess is called it merely passes hg cat file onto gvimdiff as filename so is there any way to redirect command as bash does for simplicity sake just cat file and redirect it to different different cat file txt file txt
|
it can be done as of python however this mechanism is linux specific and not portable import subprocess import sys file sys argv subprocess popen hg cat file stdout subprocess pipe subprocess popen gvimdiff proc self fd stdout fileno file wait that said in the specific case of different you can simply take one of the files from stdin and remove the need to use the bash alike functionality in question file sys argv subprocess popen hg cat file stdout subprocess pipe subprocess popen different file stdin stdout diff text communicate
|
QA
|
opengl user interface programming am developing graphical application to present data not game but real workhorse app it needs to be cross platform so have chosen python opengl need blending textures etc pyopengl wx pywx windowing dialogs etc the last component wx raises the question can put together very nice looking app the prototypes look slick but when need to interact with the user to ask questions get input have to use wx it makes the app look inconsistent to have traditional ui with traditional dialogs and combos and text entry on top of full screen app with blending smooth motion textures etc has anyone developed gui using opengl and python can you share with me the toolkits and or tricks you used need combos text entry buttons radios option buttons tree view there are some toolkits out there but they are either incomplete or old and unmaintained great example is pyui http pyui sourceforge net looks slick but untouched for years
|
try qt instead of wx qt is cross platform and you can style things alot using css it is extremely well documented and has excellent python bindings in point of fact use the documentation and not the pyqt documentation
|
QA
|
opengl user interface programming am developing graphical application to present data not game but real workhorse app it needs to be cross platform so have chosen python opengl need blending textures etc pyopengl wx pywx windowing dialogs etc the last component wx raises the question can put together very nice looking app the prototypes look slick but when need to interact with the user to ask questions get input have to use wx it makes the app look inconsistent to have traditional ui with traditional dialogs and combos and text entry on top of full screen app with blending smooth motion textures etc has anyone developed gui using opengl and python can you share with me the toolkits and or tricks you used need combos text entry buttons radios option buttons tree view there are some toolkits out there but they are either incomplete or old and unmaintained great example is pyui http pyui sourceforge net looks slick but untouched for years
|
python qt opengl surely believe any application can be written faster and better using python qt is cross platform beautifull implements everything you need from widgets acessibility etc and it integrates with opengl that means you can simply have widget that is viewport to opengl stuff you render in your code another capable solution that would cover most things but not so nioce on user interface is to extend blender with python script it has the capabilities and rendering you script it in python all of the same and it would be cross platform and you get higher level tools for woriking with the things than opengl alone there are obvious drawbacks mainly from the ui standpoint when compared with pyqt but it could be done
|
QA
|
python reportlab use of splitfirst splitlast am trying to use python with reportlab to create pdf report according to the user guide special tablestyle indeces sic in any style command the first row index may be set to one of the special strings splitlast or splitfirst to indicate that the style should be used only for the last row of split table or the first row of continuation this allows splitting tables with nicer effects around the split have tried using several style elements including textcolor splitfirst splitfirst colors black textcolor splitfirst colors black textcolor splitfirst colors black and none of these seems to work the first generates typeerror with the message typeerror cannot concatenate str and int objects and the latter two generate typeerrors with the message typeerror an integer is required is this functionality simply broken or am doing something wrong if the latter what am doing wrong
|
in any style command the first row index may be set to one of the special strings in your first example you are setting the second row index to special string as well not sure why the other two do not work are you sure this is where the exception is coming from
|
QA
|
is there benefit to defining class inside another class in python what am talking about here are nested classes essentially have two classes that am modeling downloadmanager class and downloadthread class the obvious oop concept here is composition however composition does not necessarily mean nesting right have code that looks something like this class downloadthread def foo self pass class downloadmanager def init self dwld threads def create new thread dwld threads append downloadthread but now am wondering if there is situation where nesting would be better something like class downloadmanager class downloadthread def foo self pass def init self dwld threads def create new thread dwld threads append downloadmanager downloadthread
|
no composition does not mean nesting it would make sense to have nested class if you want to hide it more in the namespace of the outer class anyway do not see any practical use for nesting in your case it would make the code harder to read understand and it would also increase the indentation which would make the lines shorter and more prone to splitting
|
QA
|
is there benefit to defining class inside another class in python what am talking about here are nested classes essentially have two classes that am modeling downloadmanager class and downloadthread class the obvious oop concept here is composition however composition does not necessarily mean nesting right have code that looks something like this class downloadthread def foo self pass class downloadmanager def init self dwld threads def create new thread dwld threads append downloadthread but now am wondering if there is situation where nesting would be better something like class downloadmanager class downloadthread def foo self pass def init self dwld threads def create new thread dwld threads append downloadmanager downloadthread
|
you might want to do this when the inner class is one off which will never be used outside the definition of the outer class for example to use metaclass it is sometimes handy to do class foo object class metaclass type instead of defining metaclass separately if you are only using it once the only other time have used nested classes like that used the outer class only as namespace to group bunch of closely related classes together class group object class cls object class cls object then from another module you can import group and refer to these as group cls group cls etc however one might argue that you can accomplish exactly the same perhaps in less confusing way by using module
|
QA
|
is there benefit to defining class inside another class in python what am talking about here are nested classes essentially have two classes that am modeling downloadmanager class and downloadthread class the obvious oop concept here is composition however composition does not necessarily mean nesting right have code that looks something like this class downloadthread def foo self pass class downloadmanager def init self dwld threads def create new thread dwld threads append downloadthread but now am wondering if there is situation where nesting would be better something like class downloadmanager class downloadthread def foo self pass def init self dwld threads def create new thread dwld threads append downloadmanager downloadthread
|
do not know python but your question seems very general ignore me if it is specific to python class nesting is all about scope if you think that one class will only make sense in the context of another one then the former is probably good candidate to become nested class it is common pattern make helper classes as private nested classes
|
QA
|
redirect command to input of another in python would like to replicate this in python gvimdiff hg cat file txt file txt hg cat file txt outputs the most recently committed version of file txt know how to pipe the file to gvimdiff but it will not accept another file hg cat file txt gvimdiff file txt too many edit arguments getting to the python part hgdiff py import subprocess import sys file sys argv subprocess call gvimdiff hg cat file file when subprocess is called it merely passes hg cat file onto gvimdiff as filename so is there any way to redirect command as bash does for simplicity sake just cat file and redirect it to different different cat file txt file txt
|
this is actually an example in the docs popen dmesg stdout pipe popen grep hda stdin stdout stdout pipe output communicate which means for you import subprocess import sys file sys argv popen hg cat file stdout pipe popen gvimdiff file txt stdin stdout stdout pipe output communicate this removes the use of the linux specific proc self fd bits making it probably work on other unices like solaris and the bsds including macos and maybe even work on windows
|
QA
|
is there benefit to defining class inside another class in python what am talking about here are nested classes essentially have two classes that am modeling downloadmanager class and downloadthread class the obvious oop concept here is composition however composition does not necessarily mean nesting right have code that looks something like this class downloadthread def foo self pass class downloadmanager def init self dwld threads def create new thread dwld threads append downloadthread but now am wondering if there is situation where nesting would be better something like class downloadmanager class downloadthread def foo self pass def init self dwld threads def create new thread dwld threads append downloadmanager downloadthread
|
you could be using class as class generator like in some off the cuff code class gen object class base object pass class base object pass def init self def mk cls self type makes class based on the type passed in the current state of the class and the other inputs to the method feel like when you need this functionality it will be very clear to you if you do not need to be doing something similar than it probably is not good use case
|
QA
|
how to check for memory leaks in guile extension modules develop an extension module for guile written in this extension module embeds python interpreter since this extension module invokes the python interpreter need to verify that it properly manages the memory occupied by python objects found that the python interpreter is well behaved in its own memory handling so that by running valgrind can find memory leaks due to bugs in my own python interpreter embedding code if there are no other interfering factors however when run guile under valgrind valgrind reports memory leaks such memory leaks obscure any memory leaks due to my own code the question is what can do to separate memory leaks due to bugs in my code from memory leaks reported by valgrind as due to guile another tool instead of valgrind special valgrind options give up and rely upon manual code walkthrough
|
you have got couple options one is to write supressions file for valgrind that turns off reporting of stuff that you are not working on python has such file for example http svn python org projects python trunk misc valgrind python supp if valgrind does not like your setup another possibility is using libmudflap you compile your program with gcc fmudflap lmudflap and the resulting code is instrumented for pointer debugging described in the gcc docs and here http gcc gnu org wiki mudflap pointer debugging
|
QA
|
is there benefit to defining class inside another class in python what am talking about here are nested classes essentially have two classes that am modeling downloadmanager class and downloadthread class the obvious oop concept here is composition however composition does not necessarily mean nesting right have code that looks something like this class downloadthread def foo self pass class downloadmanager def init self dwld threads def create new thread dwld threads append downloadthread but now am wondering if there is situation where nesting would be better something like class downloadmanager class downloadthread def foo self pass def init self dwld threads def create new thread dwld threads append downloadmanager downloadthread
|
there is really no benefit to doing this except if you are dealing with metaclasses the class suite really is not what you think it is it is weird scope and it does strange things it really does not even make class it is just way of collecting some variables the name of the class the bases little dictionary of attributes and metaclass the name the dictionary and the bases are all passed to the function that is the metaclass and then it is assigned to the variable name in the scope where the class suite was what you can gain by messing with metaclasses and indeed by nesting classes within your stock standard classes is harder to read code harder to understand code and odd errors that are terribly difficult to understand without being intimately familiar with why the class scope is entirely different to any other python scope
|
QA
|
id is bad variable name in python why is it bad to name variable id in python
|
id is built in function that gives the memory address of an object if you name one of your functions id you will have to say builtins id to get the original renaming id globally is confusing in anything but small script however reusing built in names as variables is not all that bad as long as the use is local python has lot of built in functions that have common names and you will not use much anyway using these as local variables or as members of an object is ok because it is obvious from context what you are doing example def numbered filename file open filename for input in enumerate file print input file close some built ins with tempting names id file list map all any complex dir input slice buffer
|
QA
|
how do get started processing email related to website activity am writing web application that requires user interaction via email am curious if there is best practice or recommended source for learning about processing email am writing my application in python but am not sure what mail server to use or how to format the message or subject line to account for automated processing am also looking for guidance on processing bouncebacks thanks
|
there are some pretty serious concerns here for how to send email automatically and here are few use an email library python includes one called email this is your friend it will stop you from doing anything tragically wrong read an example from the python manual some points that will stop you from getting blocked by spam filters always send from valid email address you must be able to send email to this address and have it received it can go into dev null after it is received but it must be possible to deliver there this will stop spam filters that do sender address verification from blocking your mail the email address you send from on the server sendmail fromaddr toaddr line will be where bounces go the from line in the email is totally different address and that is where mail will go when the user hits reply use this to your advantage bounces can go to one place while reply goes to another send email to local mail server recommend postfix this local server will receive your mail and be responsible for sending it to your upstream server once it has been delivered to the local server treat it as sent from programmatic point of view if you have site that is on static ip in datacenter of good reputation do not be afraid to simply relay the mail directly to the internet if you are in datacenter full of script kiddies and spammers you will need to relay this mail via public mta of good reputation hopefully you will be able to work this out without hassle do not send an email in only html always send it in plain and html or just plain be nice use text only email client and you do not want to annoy me verify that you are not running spf on your email domain or get it configured to allow your server to send the mail do this by doing txt lookup on your domain dig google com txt snip answer section google com in txt spf include netblocks google com all as you can see from that result there is an spf record there if you do not have spf there will not be txt record read more about spf on wikipedia hope that helps
|
QA
|
how do get started processing email related to website activity am writing web application that requires user interaction via email am curious if there is best practice or recommended source for learning about processing email am writing my application in python but am not sure what mail server to use or how to format the message or subject line to account for automated processing am also looking for guidance on processing bouncebacks thanks
|
some general information with regards to automated mail processing first the mail server brand itself is not that important for broadcasting or receiving emails all of them support the standard smtp pop communications protocol most even have imap support and have some level of spam filtering that said try to use current generation email server second be aware that in an effort to reduce spam lot of the receiving mail servers out there will simply throw message away instead of responding back that mail account does not exist which means you may not receive those bear in mind that getting past spam filters is an art number of isp watch for duplicate messages messages that look like spam based on keywords or other content etc this is sometimes independent of the quantity of messages sent have seen messages with as few as copies get blocked by aol even though they were legitimate emails so testing is your friend and look into this article on wikipedia on anti spam techniques then make sure your not doing that crap as far as processing the messages just remember it is queued system connect to the server via pop to retrieve messages open it do some action delete the message or archive it and move on with regards to bouncebacks let the mail server do most of the work you should be able to configure it to notify certain email account on the server in the event that it is unable to deliver message you can check that account periodically and process the non delivery reports as necessary
|
QA
|
which is faster python webpages or php webpages does anyone know how the speed of pylons or any of the other frameworks compares to similar website made with php know that serving python base webpage via cgi is slower than php because of its long start up every time enjoy using pylons and would still use it if it was slower than php but if pylons was faster than php could maybe hopefully eventually convince my employer to allow me to convert the site over to pylons
|
it sounds like you do not want to compare the two languages but that you want to compare two web systems this is tricky because there are many variables involved for example python web applications can take advantage of mod wsgi to talk to web servers which is faster than any of the typical ways that php talks to web servers even mod php ends up being slower if you are using apache because apache can only use the prefork mpm with mod php rather than multi threaded mpm like worker there is also the issue of code compilation as you know python is compiled just in time to byte code pyc files when file is run each time the file changes therefore after the first run of python file the compilation step is skipped and the python interpreter simply fetches the precompiled pyc file because of this one could argue that python has native advantage over php however optimizers and caching systems can be installed for php websites my favorite is eaccelerator to much the same effect in general enough tools exist such that one can pretty much do everything that the other can do of course as others have mentioned there is more than just speed involved in the business case to switch languages we have an app written in ocaml at my current employer which turned out to be mistake because the original author left the company and nobody else wants to touch it similarly the php web community is much larger than the python web community website hosting services are more likely to offer php support than python support etc but back to speed you must recognize that the question of speed here involves many moving parts fortunately many of these parts can be independently optimized affording you various avenues to seek performance gains
|
QA
|
how do convert local time to utc in python how do convert datetime string in local time to string in utc time am sure have done this before but cannot find it and so will hopefully help me and others do that in future clarification for example if have in my local timezone would like to generate string with the equivalent utc time also from http lucumr pocoo org eppur si muove note that in general this is not possible as with dst and other issues there is no unique conversion from local time to utc time
|
def local to utc secs time mktime return time gmtime secs def utc to local secs calendar timegm return time localtime secs source http feihonghsu blogspot com converting from local time to utc html example usage from bd if your source is datetime datetime object call as local to utc timetuple
|
QA
|
unittest causing sys exit no matter what do sys exit is called by unittest even the most trivial examples cannot tell if my install is messed up or what is going on idle no subprocess import unittest class test unittest testcase def testa self self assertequal unittest main option not recognized usage idle pyw options test options help show this message verbose verbose output quiet minimal output examples idle pyw run default set of tests idle pyw mytestsuite run suite mytestsuite idle pyw mytestcase testsomething run mytestcase testsomething idle pyw mytestcase run all test test methods in mytestcase traceback most recent call last file pyshell line in module unittest main file python lib unittest py line in init self parseargs argv file python lib unittest py line in parseargs self usageexit message file python lib unittest py line in usageexit sys exit systemexit
|
do not try to run unittest main from idle it is trying to access sys argv and it is getting the args that idle was started with either run your tests in different way from idle or call unittest main in its own python process
|
QA
|
unittest causing sys exit no matter what do sys exit is called by unittest even the most trivial examples cannot tell if my install is messed up or what is going on idle no subprocess import unittest class test unittest testcase def testa self self assertequal unittest main option not recognized usage idle pyw options test options help show this message verbose verbose output quiet minimal output examples idle pyw run default set of tests idle pyw mytestsuite run suite mytestsuite idle pyw mytestcase testsomething run mytestcase testsomething idle pyw mytestcase run all test test methods in mytestcase traceback most recent call last file pyshell line in module unittest main file python lib unittest py line in init self parseargs argv file python lib unittest py line in parseargs self usageexit message file python lib unittest py line in usageexit sys exit systemexit
|
your example is exiting on my install too can make it execute the tests and stay within python by changing unittest main to unittest texttestrunner run unittest testloader loadtestsfromtestcase test more information is available here in the python library reference
|
QA
|
static class variables in python is it possible to have static class variables or methods in python what syntax is required to do this
|
to avoid any potential confusion would like to contrast static variables and immutable objects some primitive object types like integers floats strings and touples are immutable in python this means that the object that is referred to by given name cannot change if it is of one of the aforementioned object types the name can be reassigned to different object but the object itself may not be changed making variable static takes this step further by disallowing the variable name to point to any object but that to which it currently points note this is general software concept and not specific to python please see others posts for information about implementing statics in python
|
QA
|
how do convert local time to utc in python how do convert datetime string in local time to string in utc time am sure have done this before but cannot find it and so will hopefully help me and others do that in future clarification for example if have in my local timezone would like to generate string with the equivalent utc time also from http lucumr pocoo org eppur si muove note that in general this is not possible as with dst and other issues there is no unique conversion from local time to utc time
|
first parse the string into naive datetime object this is an instance of datetime datetime with no attached timezone information see documentation for datetime strptime for information on parsing the date string use the pytz module which comes with full list of time zones utc figure out what the local timezone is construct timezone object from it and manipulate and attach it to the naive datetime finally use datetime astimezone method to convert the datetime to utc source code using local timezone america los angeles for the string import pytz datetime local pytz timezone america los angeles naive datetime datetime strptime local dt local localize naive is dst none utc dt local dt astimezone pytz utc from there you can use the strftime method to format the utc datetime as needed utc dt strftime
|
QA
|
how do convert local time to utc in python how do convert datetime string in local time to string in utc time am sure have done this before but cannot find it and so will hopefully help me and others do that in future clarification for example if have in my local timezone would like to generate string with the equivalent utc time also from http lucumr pocoo org eppur si muove note that in general this is not possible as with dst and other issues there is no unique conversion from local time to utc time
|
thanks rofly the full conversion from string to string is as follows time strftime time gmtime time mktime time strptime my summary of the time calendar functions time strptime string tuple no timezone applied so matches string time mktime local time tuple seconds since epoch always local time time gmtime seconds since epoch tuple in utc and calendar timegm tuple in utc seconds since epoch time localtime seconds since epoch tuple in local timezone
|
QA
|
unittest causing sys exit no matter what do sys exit is called by unittest even the most trivial examples cannot tell if my install is messed up or what is going on idle no subprocess import unittest class test unittest testcase def testa self self assertequal unittest main option not recognized usage idle pyw options test options help show this message verbose verbose output quiet minimal output examples idle pyw run default set of tests idle pyw mytestsuite run suite mytestsuite idle pyw mytestcase testsomething run mytestcase testsomething idle pyw mytestcase run all test test methods in mytestcase traceback most recent call last file pyshell line in module unittest main file python lib unittest py line in init self parseargs argv file python lib unittest py line in parseargs self usageexit message file python lib unittest py line in usageexit sys exit systemexit
|
pop open the source code to unittest py unittest main is hard coded to call sys exit after running all tests use texttestrunner to run test suites from the prompt
|
QA
|
split string by spaces preserving quoted substrings in python have string which is like this this is test am trying to write something in python to split it up by space while ignoring spaces within quotes the result am looking for is this is test ps know you are going to ask what happens if there are quotes within the quotes well in my application that will never happen
|
you want split from the shlex module import shlex shlex split this is test this is test this should do exactly what you want
|
QA
|
split string by spaces preserving quoted substrings in python have string which is like this this is test am trying to write something in python to split it up by space while ignoring spaces within quotes the result am looking for is this is test ps know you are going to ask what happens if there are quotes within the quotes well in my application that will never happen
|
have look at the shlex module particularly shlex split import shlex shlex split this is test this is test
|
QA
|
why are python private methods not actually private python gives us the ability to create private methods and variables within class by prepending double underscores to the name like this myprivatemethod how then can one explain this class myclass def mypublicmethod self print public method def myprivatemethod self print this is private obj myclass obj mypublicmethod public method obj myprivatemethod traceback most recent call last file line in attributeerror myclass instance has no attribute myprivatemethod dir obj myclass myprivatemethod doc module mypublicmethod obj myclass myprivatemethod this is private what is the deal will explain this little for those who did not quite get that class myclass def mypublicmethod self print public method def myprivatemethod self print this is private obj myclass what did there is create class with public method and private method and instantiate it next call its public method obj mypublicmethod public method next try and call its private method obj myprivatemethod traceback most recent call last file line in attributeerror myclass instance has no attribute myprivatemethod everything looks good here we are unable to call it it is in fact private well actually it is not running dir on the object reveals new magical method that python creates magically for all of your private methods dir obj myclass myprivatemethod doc module mypublicmethod this new method name is always an underscore followed by the class name followed by the method name obj myclass myprivatemethod this is private so much for encapsulation eh in any case would always heard python does not support encapsulation so why even try what gives
|
similar behavior exists when module attribute names begin with single underscore foo module attributes named as such will not be copied into an importing module when using the from method from bar import however this is convention and not language constraint these are not private attributes they can be referenced and manipulated by any importer some argue that because of this python can not implement true encapsulation
|
QA
|
python authentication api am looking for python library that will help me to create an authentication method for desktop app am writing have found several method in web framework such as django or turbogears just want kind of username password association stored into local file can write it by myself but am really it already exists and will be better solution am not very fluent with encryption
|
dbr said def hash password password returns the hashed version of string return hasher new str password hexdigest this is really insecure way to hash passwords you do not want to do this if you want to know why read the bycrypt paper by the guys who did the password hashing system for openbsd additionally if want good discussion on how passwords are broken check out this interview with the author of jack the ripper the popular unix password cracker now crypt is great but have to admit do not use this system because did not have the eks blowfish algorithm available and did not want to implement it my self use slightly updated version of the freebsd system which will post below the gist is this do not just hash the password salt the password then hash the password and repeat or so times if that did not make sense here is the code note am using the python cryptography toolkit from crypto hash import sha hash reps def saltedhash string salt sha sha new sha update string sha update salt for in xrange hash reps sha update sha digest if sha update salt return sha def saltedhash bin string salt returns the hash in binary format return saltedhash string salt digest def saltedhash hex string salt returns the hash in hex format return saltedhash string salt hexdigest for deploying system like this the key thing to consider is the hash reps constant this is the scalable cost factor in this system you will need to do testing to determine what is the exceptable amount of time you want to wait for each hash to be computed versus the risk of an offline dictionary based attack on your password file security is hard and the method present is not the best way to do this but it is significantly better than simple hash additionally it is dead simple to implement so even you do not choose more complex solution this is not the worst out there hope this helps tim
|
QA
|
testing gui code should use mocking library recently have been experimenting with tdd while developing gui application in python find it very reassuring to have tests that verify the functionality of my code but it is been tricky to follow some of the recommened practices of tdd namely writing tests first has been hard and am finding it difficult to make my tests readable due to extensive use of mocking library chose mocking library called mocker use it lot since much of the code am testing makes calls to other methods in my application that depend on system state or objc cocoa objects that cannot exist without an event loop etc anyway have got lot of tests that look like this def test current window controller def test config ac appcontroller mocker ac iter window controllers iwc replace ac iter window controllers expect iwc result iter config with result ac current window controller assert result config if config else none yield test yield test yield test notice that this is actually three tests all use the same parameterized test function here is the code that is being tested def current window controller self try iter window controllers iterates in order starting with the controller of the top most window assumption the top most window is the current one wc self iter window controllers next except stopiteration return none return wc one of the things have noticed with using mocker is that it is easier to write the application code first and then go back and write the tests second since most of the time am mocking many method calls and the syntax to write the mocked calls is much more verbose thus harder to write than the application code it is easier to write the app code and then model the test code off of that find that with this testing method and bit of discipline can easily write code with test coverage am wondering if these tests are good tests will regret doing it this way down the road when finally discover the secret to writing good tests am violating the core principles of tdd so much that my testing is in vain
|
if you are writing your tests after you have written your code and making them pass you are not doing tdd nor are you getting any benefits of test first or test driven development check out so questions for definitive books on tdd one of the things have noticed with using mocker is that it is easier to write the application code first and then go back and write the tests second since most of the time am mocking many method calls and the syntax to write the mocked calls is much more verbose thus harder to write than the application code it is easier to write the app code and then model the test code off of that of course its easier because you are just testing that the sky is orange after you made it orange by painting it with specific kind of brush this is retrofitting tests for self assurance mocks are good but you should know how and when to use them like the saying goes when you have hammer everything looks like nail it is also easy to write whole load of unreadable and not as helpful as can be tests the time spent understanding what the test is about is time lost that can be used to fix broken ones and the point is read mocks are not stubs martin fowler if you have not already google out some documented instances of good modelviewpresenter patterned guis fake mock out the uis if necessary study your options and choose wisely will play the guy with the halo on your left shoulder in white saying do not do it read this question as to my reasons st justin is on your right shoulder believe he has also something to say
|
QA
|
pubsub lib for is there library which provides similar functionality to the python pubsub library think it is kind of an observer pattern which allows me to subscribe for messages of given topic instead of using events
|
these may be bit heavy for you depending on your needs but http www nservicebus com http blog phatboyg com masstransit
|
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
|
designing bigtable schema is an open process and basically requires you to think about the access patterns you will be using and how often each will be used the relationships between your types what indices you are going to need the write patterns you will be using in order to effectively spread load gae datastore automatically denormalizes your data that is each index contains mostly complete copy of the data and thus every index adds significantly to time taken to perform write and the storage space used if this were not the case designing datastore schema would be lot more work you would have to think carefully about the primary key for each type and consider the effect of your decision on the locality of data for example when rendering blog post you would probably need to display the comments to go along with it so each comment key would probably begin with the associated post key with datastore this is not such big deal the query you use will look something like select from comment where post id if you want to page the comments you would also have limit clause and possible suffix of and comment id last comment id once you add such query datastore will build the index for you and your reads will be magically fast something to keep in mind is that each additional index creates some additional cost it is best if you can use as few access patterns as possible since it will reduce the number of indices gae will construct and thus the total storage required by your data reading over this answer find it little vague maybe hands on design question would help to scope this down
|
QA
|
split string by spaces preserving quoted substrings in python have string which is like this this is test am trying to write something in python to split it up by space while ignoring spaces within quotes the result am looking for is this is test ps know you are going to ask what happens if there are quotes within the quotes well in my application that will never happen
|
since this question is tagged with regex decided to try regex approach first replace all the spaces in the quotes parts with then split by spaces then replace the back to spaces in each part both versions do the same thing but splitter is bit more readable then splitter import re this is test some text another test def splitter def replacer return group replace parts re sub replacer split parts replace for in parts return parts def splitter return replace for in re sub lambda group replace split print splitter
|
QA
|
btrieve without pervasive is there any library available to query btrieve databases without buying something from pervasive am looking to code in or python
|
as far as know that is not possible it is not an open source database so writing drivers for it is really hard
|
QA
|
can parallel traversals be done in matlab just as in python using the zip function python allows for loops to traverse multiple sequences in parallel for in zip list list does matlab have an equivalent syntax if not what is the best way to iterate over two parallel arrays at the same time using matlab
|
second mattiast answer but to dig little deeper is there no way to vectorize what you are trying to accomplish and avoid the iterative for loop perhaps with more details about what goes on inside the loop we could help vectorize the solution
|
QA
|
pubsub lib for is there library which provides similar functionality to the python pubsub library think it is kind of an observer pattern which allows me to subscribe for messages of given topic instead of using events
|
again my be overkill but the ose library allows thins kind of thing
|
QA
|
undo with gtk textview am trying to keep dependencies to minimum for program contribute to it is small text editor gtk textview does not seem to come with built in undo function is there any reference implementation have been missing on so far is everyone writing their own undo function for their textview widgets will be happy about any sample code most happy about python sample code as our project is in python
|
depending on just how dependency averse you are and what kind of text editor you are building gtksourceview adds undo redo among many other things very worth looking at if you want some of the other features it offers
|
QA
|
static class variables in python is it possible to have static class variables or methods in python what syntax is required to do this
|
you can also add class variables to classes on the fly class pass bar bar foo traceback most recent call last file interactive input line in module attributeerror instance has no attribute foo foo foo and class instances can change class variables class def init self self append print print python test py
|
QA
|
how to skip sys exitfunc when unhandled exceptions occur as you can see even after the program should have died it speaks from the grave is there way to deregister the exitfunction in case of exceptions import atexit def helloworld print hello world atexit register helloworld raise exception good bye cruel world outputs traceback most recent call last file test py line in module raise exception good bye cruel world exception good bye cruel world hello world
|
if you call import os os exit the exit handlers will not be called yours or those registered by other modules in the application
|
QA
|
how to skip sys exitfunc when unhandled exceptions occur as you can see even after the program should have died it speaks from the grave is there way to deregister the exitfunction in case of exceptions import atexit def helloworld print hello world atexit register helloworld raise exception good bye cruel world outputs traceback most recent call last file test py line in module raise exception good bye cruel world exception good bye cruel world hello world
|
do not really know why you want to do that but you can install an excepthook that will be called by python whenever an uncatched exception is raised and in it clear the array of registered function in the atexit module something like that import sys import atexit def clear atexit excepthook exctype value traceback atexit exithandlers sys excepthook exctype value traceback def helloworld print hello world sys excepthook clear atexit excepthook atexit register helloworld raise exception good bye cruel world beware that it may behave incorrectly if the exception is raised from an atexit registered function but then the behaviour would have been strange even if this hook was not used
|
QA
|
asychronous programming in python twisted am having trouble developing reverse proxy in twisted it works but it seems overly complex and convoluted so much of it feels like voodoo are there any simple solid examples of asynchronous program structure on the web or in books sort of best practices guide when complete my program would like to be able to still see the structure in some way not be looking at bowl of spaghetti
|
if you are not looking to use twisted there was great guide used while back here is the link to it
|
QA
|
how to skip sys exitfunc when unhandled exceptions occur as you can see even after the program should have died it speaks from the grave is there way to deregister the exitfunction in case of exceptions import atexit def helloworld print hello world atexit register helloworld raise exception good bye cruel world outputs traceback most recent call last file test py line in module raise exception good bye cruel world exception good bye cruel world hello world
|
in addition to calling os exit to avoid the registered exit handler you also need to catch the unhandled exception import atexit import os def helloworld print hello world atexit register helloworld try raise exception good bye cruel world except exception print caught unhandled exception str os exit
|
QA
|
pythonwin python interactive she will calling constructors twice while answering http stackoverflow com questions python static variable noticed that pythonwin pywin build interpreter seems to evaluate twice pythonwin mar msc bit intel on win portions copyright mark hammond see help about pythonwin for further copyright information class def init self self class append while the python interpreter does the right thing python activepython activestate software inc based on python mar msc bit intel on win type help copyright credits or license for more information class def init self self class append
|
my guess is as follows the pythonwin editor offers autocomplete for an object when you type myobject it offers little popup of all the availble method names so think when you type it is creating an instance of in the background and doing dir or similar to find out the attributes of the object so the constructor is only being run once for each object but to give you the interactivity it is creating objects silently in the background without telling you about it
|
QA
|
how to use form values from an unbound form have web report that uses django form new forms for fields that control the query used to generate the report start date end date the issue am having is that the page should work using the form initial values unbound but cannot access the cleaned data field unless call is valid but is valid always fails on unbound forms it seems like django forms were designed with the use case of editing data such that an unbound form is not really useful for anything other than displaying html for example if have if request method get form myform else form myform request method post if form is valid do query form cleaned data start date form cleaned data end date is valid will fail if this is get since it is unbound and if do if request method get form myform do query form cleaned data start date form cleaned data end date else form myform request method post if form is valid do query form cleaned data start date form cleaned data end date the first call to do query triggers exceptions on form cleaned data which is not valid field because is valid has not been called it seems like have to do something like if request method get form myform do query form start date field initial form end date field initial else form myform request method post if form is valid do query form cleaned data start date form cleaned data end date that is there is not common interface for retrieving the form values between bound form and an unbound one does anyone see cleaner way to do this
|
unbound means there is no data associated with form either initial or provided later so the validation may fail as mentioned in other answers and in your own conclusion you have to provide initial values and check for both bound data and initial values the use case for forms is form processing and validation so you must have some data to validate before you accessing cleaned data
|
QA
|
asychronous programming in python twisted am having trouble developing reverse proxy in twisted it works but it seems overly complex and convoluted so much of it feels like voodoo are there any simple solid examples of asynchronous program structure on the web or in books sort of best practices guide when complete my program would like to be able to still see the structure in some way not be looking at bowl of spaghetti
|
twisted contains large number of examples one in particular the evolution of finger tutorial contains thorough explanation of how an asynchronous program grows from very small kernel up to complex system with lots of moving parts another one that might be of interest to you is the tutorial about simply writing servers the key thing to keep in mind about twisted or even other asynchronous networking libraries such as asyncore mina or ace is that your code only gets invoked when something happens the part that have heard most often sound like voodoo is the management of callbacks for example deferred if you are used to writing code that runs in straight line and only calls functions which return immediately with results the idea of waiting for something to call you back might be confusing but there is nothing magical no voodoo about callbacks at the lowest level the reactor is just sitting around and waiting for one of small number of things to happen data arrives on connection it will call datareceived on protocol time has passed it will call function registered with calllater connection has been accepted it will call buildprotocol on factory registered with listenxxx or connectxxx function connection has been dropped it will call connectionlost on the appropriate protocol every asynchronous program starts by hooking up few of these events and then kicking off the reactor to wait for them to happen of course events that happen lead to more events that get hooked up or disconnected and so your program goes on its merry way beyond that there is nothing special about asynchronous program structure that are interesting or special event handlers and callbacks are just objects and your code is run in the usual way here is simple event driven engine that shows you just how simple this process is engine import time class simplestreactor object def init self self events self stopped false def do self something self events append something def run self while not self stopped time sleep if self events thisturn self events pop thisturn def stop self self stopped true reactor simplestreactor application def thing print doing thing reactor do thing reactor do thing def thing print doing thing def thing print doing thing and stopping reactor stop reactor do thing print running reactor run print done at the core of libraries like twisted the function in the main loop is not sleep but an operating system call like select or poll as exposed by module like the python select module say like select because this is an api that varies lot between platforms and almost every gui toolkit has its own version twisted currently provides an abstract interface to different variations on this theme the common thing that such an api provides is provide way to say here are list of events that am waiting for go to sleep until one of them happens then wake up and tell me which one of them it was
|
QA
|
upload files in google app engine am planning to create web app that allows users to downgrade their visual studio project files however it seems google app engine accepts files uploading and flat file storing on the google server through db textproperty and db blobproperty will be glad anyone can provide code sample both the client and the server side on how this can be done
|
you can not store files as there is not traditional file system you can only store them in their own datastore in field defined as blobproperty there is an example in the previous link class mymodel db model blob db blobproperty obj mymodel obj blob db blob file contents
|
QA
|
upload files in google app engine am planning to create web app that allows users to downgrade their visual studio project files however it seems google app engine accepts files uploading and flat file storing on the google server through db textproperty and db blobproperty will be glad anyone can provide code sample both the client and the server side on how this can be done
|
there is no flat file storing in google app engine everything has to go in to the datastore which is bit like relational database but not quite you could store the files as textproperty or blobproperty attributes there is mb limit on datastore entries which may or may not be problem
|
QA
|
django vs grails vs am wondering if there is such thing as django like ease of web app development combined with good deployment debugging and other tools django is very productive framework for building content heavy sites the best have tried and breath of fresh air compared to some of the java monstrosities out there however it is written in python which means there is little real support in the way of deployment packaging debugging profilers and other tools that make building and maintaining applications much easier ruby has similar issues and although do like ruby much better than like python get the impression that rails is roughly in the same boat at django when it comes to managing supporting the app has anyone here tried both django and grails or other web frameworks for non trivial projects how did they compare
|
personally made some rather big projects with django but can compare only with said montrosities spring ejb and really low level stuff like twisted web frameworks using interpreted languages are mostly in its infancy and all of them actively maintained that is are getting better with every day
|
QA
|
pythonwin python interactive she will calling constructors twice while answering http stackoverflow com questions python static variable noticed that pythonwin pywin build interpreter seems to evaluate twice pythonwin mar msc bit intel on win portions copyright mark hammond see help about pythonwin for further copyright information class def init self self class append while the python interpreter does the right thing python activepython activestate software inc based on python mar msc bit intel on win type help copyright credits or license for more information class def init self self class append
|
two small additional points first self class append is not really sensible just say self append python searches the instance before it searches the class for the reference more importantly class level variables are rarely useful class level constants are sometimes sensible but even then they are hard to justify in and java class level static variables seem handy but do not do much of value they are hard to teach to bz often wasting lots of classroom time on minutia and they are not very practical if you want to know all instances of an that was created it is probably better to create an xfactory class that does not rely on class variables class xfactory object def init self self listofx def makex self args kw newx args kw self listofx append newx return newx no class level variable anomalies and it does not conflate the with the collection of in the long run find it confusing when class is both some thing and also some collection of things simpler is better than complex
|
QA
|
html parser in python using the python documentation found the html parser but have no idea which library to import to use it how do find this out bearing in mind it does not say on the page
|
you may be interested in lxml it is separate package and has components but is the fastest it has also very nice api allowing you to easily list links in html documents or list forms sanitize html and more it also has capabilities to parse not well formed html it is configurable
|
QA
|
pyqt and pycairo know it is possible to place pycairo surface inside gtk drawing area but think qt is lot better to work with so have been wondering if there is anyway to place pycairo surface inside some qt component
|
qt own opengl based surfaces using qpainter are known to be much faster than cairo might you explain why you want specifically cairo in qt for the basics of using qpainter see this excerpt from the book gui programming with qt and while it is code the pyqt implementation will be parallel as for joining cairo with qt this article in arstechnica sheds some light it seems nothing that could help you exists currently iow nobody tried such marriage
|
QA
|
is there any list of blog engines written in django is there any list of blog engines written in django
|
byteflow is blog engine written on python using django
|
QA
|
is there any list of blog engines written in django is there any list of blog engines written in django
|
james bennett has an interesting take on this question where can find good django powered blogging application is probably at the top of the frequently asked questions list both on django users and in the irc part of this is simply that right now there is no definitive django blogging application there are bunch of them available if you go looking but you re not likely to get anyone to recommend one of them as the django blogging app unless the person doing the recommending happens to be the author of one of them the blog entry also has list
|
QA
|
is there any list of blog engines written in django is there any list of blog engines written in django
|
edit original link went dead so here is an updated link with extracts of the list sorted with the most recently updated source at the top eleven django blog engines you should know by monty lounge industries biblion django article flother basic blog hello newman banjo djangotechblog django yaba shifting bits this is now just biblion blog mighty lemon coltrane
|
QA
|
is there any list of blog engines written in django is there any list of blog engines written in django
|
django powerful admin interface and easy orm makes it minute job to build blog that propably fits your needs why look for rd party product when you can make it yourself very quickly
|
QA
|
how do check whether file exists using python how do check whether file exists without using the try statement
|
import os path if os path isfile filename
|
QA
|
how do check whether file exists using python how do check whether file exists without using the try statement
|
import os os path exists filename
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.