prefix
stringclasses 1
value | input_text
stringlengths 19
27.3k
⌀ | target_text
stringlengths 2
24.8k
⌀ |
---|---|---|
QA
|
making beta code for public django site am about to put beta version of the site am working on up on the web it needs to have beta code to restrict access the site is written in django do not want to change the fundamental auth system to accommodate beta code and do not care particularly that the security of the beta code is iron clad just that it is significant stumbling block how should do this it is fairly large project so adding code to every view is far from ideal that solution works well the middleware class ended up with this this from django http import httpresponseredirect class betamiddleware object require beta code session key in order to view any page def process request self request if request path beta and not request session get in beta return httpresponseredirect next beta request path
|
start with this django snippet but modify it to check request session has beta access if they do not have it then have it return redirect to enter beta code page that when posted to with the right code sets that session variable to true making it public beta then just consists of removing that middleware from your middleware classes setting
|
QA
|
anyone used dabo for medium big project we are at the beginning of new erp ish client server application developed as python rich client we are currently evaluating dabo as our main framework and it looks quite nice and easy to use but was wondering has anyone used it for medium to big sized projects thanks for your time
|
am one of the authors of the dabo framework one of our users pointed out to me the extremely negative answer you received and so thought had better chime in and clear up some of the incorrect assumptions in the first reply dabo is indeed well known in the python community have presented it at of the last us pycons and we have several hundred users who subscribe to our email lists our website http dabodev com has not had any service interruptions do not know why the first responder claimed to have trouble support is through our email lists and we pride ourselves on helping people quickly and efficiently many of the newbie questions help us to identify places where our docs are lacking so we strongly encourage newcomers to ask questions dabo has been around for years the fact that it is still few days away from release is more of reflection of the rather conservative version numbering of my partner paul mcnett than any instabilities in the framework know of dabo apps that have been in production since have used it for my own projects since whatever importance you attach to release numbers we are at revision with consistent work being done to add more and more stuff to the framework refactor and streamline some of the older code and yes clean up some bugs please sign up for our free email support list http leafe com mailman listinfo dabo users and ask any questions you may have about dabo there not many people have discovered stack overflow yet so would not expect very informed answers here yet there are several regular contributors there who use dabo on daily basis and are usually more than happy to offer their opinions and their help
|
QA
|
what is thread local storage in python and why do need it in python specifically how do variables get shared between threads although have used threading thread before never really understood or saw examples of how variables got shared are they shared between the main thread and the children or only among the children when would need to use thread local storage to avoid this sharing have seen many warnings about synchronizing access to shared data among threads by using locks but have yet to see really good example of the problem thanks in advance
|
you can create thread local storage using threading local tls threading local tls tls data stored to the tls will be unique to each thread which will help ensure that unintentional sharing does not occur
|
QA
|
why unicode uses str on my object only with no encoding given start by creating string variable with some non ascii utf encoded data on it text text xc xa text decode utf you xe using unicode on it raises errors unicode text traceback most recent call last file stdin line in module unicodedecodeerror ascii codec cannot decode byte xc in position ordinal not in range but if know the encoding can use it as second parameter unicode text utf you xe unicode text utf text decode utf true now if have class that returns this text in the str method class returnsencoded object def str self return text are returnsencoded str xc xa unicode seems to use str on it since it raises the same error as unicode text above unicode traceback most recent call last file stdin line in module unicodedecodeerror ascii codec cannot decode byte xc in position ordinal not in range until now everything is as planned but as no one would ever expect unicode utf will not even try unicode utf traceback most recent call last file stdin line in module typeerror coercing to unicode need string or buffer returnsencoded found why why this inconsistent behavior is it bug is it intended very awkward
|
unicode does not guess the encoding of your text if your object can print itself as unicode define the unicode method that returns unicode string the secret is that unicode is not actually calling str itself instead it is looking for unicode method the default implementation of unicode will call str and then attempt to decode it using the ascii charset when you pass the encoding unicode expects the first object to be something that can be decoded that is an instance of basestring behavior is weird because it tries to decode as ascii if do not pass utf but if pass utf it gives different error that is because when you specify utf it treats the first parameter as string like object to be decoded without it it treats the parameter as an object to be coerced to unicode do not understand the confusion if you know that the object text attribute will always be utf encoded just define unicode and then everything will work fine
|
QA
|
why unicode uses str on my object only with no encoding given start by creating string variable with some non ascii utf encoded data on it text text xc xa text decode utf you xe using unicode on it raises errors unicode text traceback most recent call last file stdin line in module unicodedecodeerror ascii codec cannot decode byte xc in position ordinal not in range but if know the encoding can use it as second parameter unicode text utf you xe unicode text utf text decode utf true now if have class that returns this text in the str method class returnsencoded object def str self return text are returnsencoded str xc xa unicode seems to use str on it since it raises the same error as unicode text above unicode traceback most recent call last file stdin line in module unicodedecodeerror ascii codec cannot decode byte xc in position ordinal not in range until now everything is as planned but as no one would ever expect unicode utf will not even try unicode utf traceback most recent call last file stdin line in module typeerror coercing to unicode need string or buffer returnsencoded found why why this inconsistent behavior is it bug is it intended very awkward
|
the behaviour does seem confusing but intensional reproduce here the entirety of the unicode documentation from the python built in functions documentation for version as write this unicode object encoding errors return the unicode string version of object using one of the following modes if encoding and or errors are given unicode will decode the object which can either be an bit string or character buffer using the codec for encoding the encoding parameter is string giving the name of an encoding if the encoding is not known lookuperror is raised error handling is done according to errors this specifies the treatment of characters which are invalid in the input encoding if errors is strict the default valueerror is raised on errors while value of ignore causes errors to be silently ignored and value of replace causes the official unicode replacement character you fffd to be used to replace input characters which cannot be decoded see also the codecs module if no optional parameters are given unicode will mimic the behaviour of str except that it returns unicode strings instead of bit strings more precisely if object is unicode string or subclass it will return that unicode string without any additional decoding applied for objects which provide unicode method it will call this method without arguments to create unicode string for all other objects the bit string version or representation is requested and then converted to unicode string using the codec for the default encoding in strict mode new in version changed in version support for unicode added so when you call unicode utf it requires an bit string or character buffer as the first argument so it coerces your object using the str method and attempts to decode that using the utf codec without the utf the unicode function looks for for unicode method on your object and not finding it calls the str method as you suggested attempting to use the default codec to convert to unicode
|
QA
|
how to bundle python application including dependencies need to package my python application its dependencies and python into single msi installer the end result should desirably be python is installed in the standard location the package and its dependencies are installed in separate directory possibly site packages the installation directory should contain the python uncompressed and standalone executable is not required
|
kind of dup of this question about how to make python into an executable it boils down to py exe on windows freeze on linux and py app on mac
|
QA
|
how to bundle python application including dependencies need to package my python application its dependencies and python into single msi installer the end result should desirably be python is installed in the standard location the package and its dependencies are installed in separate directory possibly site packages the installation directory should contain the python uncompressed and standalone executable is not required
|
py exe is the best way to do this it is bit of pita to use but the end result works very well
|
QA
|
how to bundle python application including dependencies need to package my python application its dependencies and python into single msi installer the end result should desirably be python is installed in the standard location the package and its dependencies are installed in separate directory possibly site packages the installation directory should contain the python uncompressed and standalone executable is not required
|
py exe will make windows executables with python bundled in
|
QA
|
how to bundle python application including dependencies need to package my python application its dependencies and python into single msi installer the end result should desirably be python is installed in the standard location the package and its dependencies are installed in separate directory possibly site packages the installation directory should contain the python uncompressed and standalone executable is not required
|
use pyinstaller the svn version to create stand alone version of my program that includes python and all the dependencies it takes little fiddling to get it to work right and include everything as does py exe and other similar programs see this question but then it works very well you then need to create an installer nsis works great for that and is free but it creates exe files not msi if msi is not necessary highly recommend it otherwise check out the answers to this question for other options
|
QA
|
unit testing file modifications common task in programs have been working on lately is modifying text file in some way hey am on linux everything file and do large scale system admin but the file the code modifies may not exist on my desktop box and probably do not want to modify it if it is on my desktop have read about unit testing in dive into python and it is pretty clear what want to do when testing an app that converts decimal to roman numerals the example in dintop the testing is nicely self contained you do not need to verify that the program prints the right thing you just need to verify that the functions are returning the right output to given input in my case however we need to test that the program is modifying its environment correctly here is what have come up with create the original file in standard location perhaps tmp run the function that modifies the file passing it the path to the file in tmp verify that the file in tmp was changed correctly pass fail unit test accordingly this seems kludgy to me gets even kludgier if you want to verify that backup copies of the file are created properly etc has anyone come up with better way
|
when touch files in my code tend to prefer to mock the actual reading and writing of the file so then can give my classes exact contents want in the test and then assert that the test is writing back the contents expect have done this in java and imagine it is quite simple in python but it may require designing your classes functions in such way that it is easy to mock the use of an actual file for this you can try passing in streams and then just pass in simple string input output stream which will not write to file or have function that does the actual write this string to file or read this string from file and then replace that function in your tests
|
QA
|
unit testing file modifications common task in programs have been working on lately is modifying text file in some way hey am on linux everything file and do large scale system admin but the file the code modifies may not exist on my desktop box and probably do not want to modify it if it is on my desktop have read about unit testing in dive into python and it is pretty clear what want to do when testing an app that converts decimal to roman numerals the example in dintop the testing is nicely self contained you do not need to verify that the program prints the right thing you just need to verify that the functions are returning the right output to given input in my case however we need to test that the program is modifying its environment correctly here is what have come up with create the original file in standard location perhaps tmp run the function that modifies the file passing it the path to the file in tmp verify that the file in tmp was changed correctly pass fail unit test accordingly this seems kludgy to me gets even kludgier if you want to verify that backup copies of the file are created properly etc has anyone come up with better way
|
think you are on the right track depending on what you need to do chroot may help you set up an environment for your scrpits that looks real but is not if that does not work then you could write your scripts to take root path as an argument in production run the root path is just for testing you create shadow environment under tmp test and then run your scripts with root path of tmp test
|
QA
|
unit testing file modifications common task in programs have been working on lately is modifying text file in some way hey am on linux everything file and do large scale system admin but the file the code modifies may not exist on my desktop box and probably do not want to modify it if it is on my desktop have read about unit testing in dive into python and it is pretty clear what want to do when testing an app that converts decimal to roman numerals the example in dintop the testing is nicely self contained you do not need to verify that the program prints the right thing you just need to verify that the functions are returning the right output to given input in my case however we need to test that the program is modifying its environment correctly here is what have come up with create the original file in standard location perhaps tmp run the function that modifies the file passing it the path to the file in tmp verify that the file in tmp was changed correctly pass fail unit test accordingly this seems kludgy to me gets even kludgier if you want to verify that backup copies of the file are created properly etc has anyone come up with better way
|
you have two levels of testing filtering and modifying content these are low level operations that do not really require physical file these are the tests decision making alternatives etc the logic of the application file system operations create copy rename delete backup sorry but those are proper file system operations that well require proper file system for testing for this kind of testing we often use mock object you can design filesystemoperations class that embodies the various file system operations you test this to be sure it does basic read write copy rename etc there is no real logic in this just methods that invoke file system operations you can then create mockfilesystem which dummies out the various operations you can use this mock object to test your other classes in some cases all of your file system operations are in the os module if that is the case you can create mockos module with mock version of the operations you actually use put your mockos module on the pythonpath and you can conceal the real os module for production operations you use your well tested logic classes plus your filesystemoperations class or the real os module
|
QA
|
unit testing file modifications common task in programs have been working on lately is modifying text file in some way hey am on linux everything file and do large scale system admin but the file the code modifies may not exist on my desktop box and probably do not want to modify it if it is on my desktop have read about unit testing in dive into python and it is pretty clear what want to do when testing an app that converts decimal to roman numerals the example in dintop the testing is nicely self contained you do not need to verify that the program prints the right thing you just need to verify that the functions are returning the right output to given input in my case however we need to test that the program is modifying its environment correctly here is what have come up with create the original file in standard location perhaps tmp run the function that modifies the file passing it the path to the file in tmp verify that the file in tmp was changed correctly pass fail unit test accordingly this seems kludgy to me gets even kludgier if you want to verify that backup copies of the file are created properly etc has anyone come up with better way
|
you might want to setup the test so that it runs inside chroot jail so you have all the environment the test needs even if paths and file locations are hardcoded in the code not really good practice but sometimes one gets the file locations from other places and then check the results via the exit code
|
QA
|
how best to draw in the console am trying to write console as in terminal not gaming console pong game in python and am having trouble figuring how best to re draw the game was thinking of having an array as sort of bitmap editing the array to reflect the ball paddles new positions and then casting each row to string and printing it however that means that the old frames will remain and if the dimensions of the game are smaller than the console window old frames will still be visible is there way to delete characters from the console have heard is unreliable or is there an easier alternative route to outputting to the console for this sort of app
|
it looks like there is curses port library for python https docs python org library curses html
|
QA
|
how best to draw in the console am trying to write console as in terminal not gaming console pong game in python and am having trouble figuring how best to re draw the game was thinking of having an array as sort of bitmap editing the array to reflect the ball paddles new positions and then casting each row to string and printing it however that means that the old frames will remain and if the dimensions of the game are smaller than the console window old frames will still be visible is there way to delete characters from the console have heard is unreliable or is there an easier alternative route to outputting to the console for this sort of app
|
would investigate using the curses module it will take care of lot of the details and let you focus on the higher level stuff
|
QA
|
how best to draw in the console am trying to write console as in terminal not gaming console pong game in python and am having trouble figuring how best to re draw the game was thinking of having an array as sort of bitmap editing the array to reflect the ball paddles new positions and then casting each row to string and printing it however that means that the old frames will remain and if the dimensions of the game are smaller than the console window old frames will still be visible is there way to delete characters from the console have heard is unreliable or is there an easier alternative route to outputting to the console for this sort of app
|
this previous stackoverflow question should give you some more useful information
|
QA
|
glade or no glade what is the best way to use pygtk have been learning python for while now with some success even managed to create one or two simple programs using pygtk glade the thing is am not sure if the best way to use gtk with python is by building the interfaces using glade was wondering if the more experienced ones among us remember am just beginner could point out the benefits and caveats of using glade as opposed to creating everything in the code itself assuming that learning the correct gtk bindings would not exactly be problem
|
started out using glade but soon moved to just doing everything in code glade is nice for simple things and it is good when you are learning how gtk organizes the widgets how things are packed etc constructing everything in code however you have much more flexibility plus you do not have the glade dependency
|
QA
|
resources for lexing tokenising and parsing in python can people point me to resources on lexing parsing and tokenising with python am doing little hacking on an open source project hotwire and wanted to do few changes to the code that lexes parses and tokenises the commands entered into it as it is real working code it is fairly complex and bit hard to work out have not worked on code to lex parse tokenise before so was thinking one approach would be to work through tutorial or two on this aspect would hope to learn enough to navigate around the code actually want to alter is there anything suitable out there ideally it could be done in an afternoon without having to buy and read the dragon book first edit oct none of the below answers quite give what want with them could generate parsers from scratch but want to learn how to write my own basic parser from scratch not using lex and yacc or similar tools having done that can then understand the existing code better so could someone point me to tutorial where can build basic parser from scratch using just python
|
am happy user of ply it is pure python implementation of lex yacc with lots of small niceties that make it quite pythonic and easy to use since lex yacc are the most popular lexing parsing tools and are used for the most projects ply has the advantage of standing on giants shoulders lot of knowledge exists online on lex yacc and you can freely apply it to ply ply also has good documentation page with some simple examples to get you started for listing of lots of python parsing tools see this
|
QA
|
resources for lexing tokenising and parsing in python can people point me to resources on lexing parsing and tokenising with python am doing little hacking on an open source project hotwire and wanted to do few changes to the code that lexes parses and tokenises the commands entered into it as it is real working code it is fairly complex and bit hard to work out have not worked on code to lex parse tokenise before so was thinking one approach would be to work through tutorial or two on this aspect would hope to learn enough to navigate around the code actually want to alter is there anything suitable out there ideally it could be done in an afternoon without having to buy and read the dragon book first edit oct none of the below answers quite give what want with them could generate parsers from scratch but want to learn how to write my own basic parser from scratch not using lex and yacc or similar tools having done that can then understand the existing code better so could someone point me to tutorial where can build basic parser from scratch using just python
|
pygments is source code syntax highlighter written in python it has lexers and formatters and may be interesting to peek at the source
|
QA
|
how do you send head http request in python what am trying to do here is get the headers of given url so can determine the mime type want to be able to see if http somedomain foo will return an html document or jpeg image for example thus need to figure out how to send head request so that can read the mime type without having to download the content does anyone know of an easy way of doing this
|
edit this answer works but nowadays you should just use the requests library as mentioned by other answers below use httplib import httplib conn httplib httpconnection www google com conn request head index html res conn getresponse print res status res reason ok print res getheaders content length expires server gws cache control private max age date sat sep gmt content type text html charset iso there is also getheader name to get specific header
|
QA
|
xml rpc best way to handle bit values so the official xml rpc standard does not support bit values but in these modern times bit values are increasingly common how do you handle these what xml rpc extensions are the most common what language bindings are there am especially interested in python and but all information is appreciated
|
do not know anything about how xmlrpc could be extended but did find this mail about the subject in xml rpc everything is transmitted as string so do not think that choice is really that bad except of course for the additional clumsiness for invoking explicit conversion functions but no xml rpc does not have data type that can represent integers above if you can accept losing precision you can use doubles but you still would have to convert explicitly on the sender
|
QA
|
how best to draw in the console am trying to write console as in terminal not gaming console pong game in python and am having trouble figuring how best to re draw the game was thinking of having an array as sort of bitmap editing the array to reflect the ball paddles new positions and then casting each row to string and printing it however that means that the old frames will remain and if the dimensions of the game are smaller than the console window old frames will still be visible is there way to delete characters from the console have heard is unreliable or is there an easier alternative route to outputting to the console for this sort of app
|
you can use curses it has windows port and unix port and plenty of documentation you can also use some helper libs
|
QA
|
disable output buffering is output buffering enabled by default in python interpreter for sys stdout if the answer is positive what are all the ways to disable it suggestions so far use the you command line switch wrap sys stdout in an object that flushes after every write set pythonunbuffered env var sys stdout os fdopen sys stdout fileno is there any other way to set some global flag in sys sys stdout programmatically during execution
|
from magnus lycka answer on mailing list you can skip buffering for whole python process using python you or usr bin env python you etc or by setting the environment variable pythonunbuffered you could also replace sys stdout with some other stream like wrapper which does flush after every call class unbuffered object def init self stream self stream stream def write self data self stream write data self stream flush def getattr self attr return getattr self stream attr import sys sys stdout unbuffered sys stdout print hello
|
QA
|
disable output buffering is output buffering enabled by default in python interpreter for sys stdout if the answer is positive what are all the ways to disable it suggestions so far use the you command line switch wrap sys stdout in an object that flushes after every write set pythonunbuffered env var sys stdout os fdopen sys stdout fileno is there any other way to set some global flag in sys sys stdout programmatically during execution
|
yes it is you can disable it on the commandline with the you switch alternatively you could call flush on sys stdout on every write or wrap it with an object that does this automatically
|
QA
|
disable output buffering is output buffering enabled by default in python interpreter for sys stdout if the answer is positive what are all the ways to disable it suggestions so far use the you command line switch wrap sys stdout in an object that flushes after every write set pythonunbuffered env var sys stdout os fdopen sys stdout fileno is there any other way to set some global flag in sys sys stdout programmatically during execution
|
yes it is enabled by default you can disable it by using the you option on the command line when calling python
|
QA
|
disable output buffering is output buffering enabled by default in python interpreter for sys stdout if the answer is positive what are all the ways to disable it suggestions so far use the you command line switch wrap sys stdout in an object that flushes after every write set pythonunbuffered env var sys stdout os fdopen sys stdout fileno is there any other way to set some global flag in sys sys stdout programmatically during execution
|
one way to get unbuffered output would be to use sys stderr instead of sys stdout or to simply call sys stdout flush to explicitly force write to occur you could easily redirect everything printed by doing import sys sys stdout sys stderr print hello world or to redirect just for particular print statement print sys stderr hello world to reset stdout you can just do sys stdout sys stdout
|
QA
|
how can unit test responses from the webapp wsgi application in google app engine would like to unit test responses from the google app engine webapp wsgiapplication for example request the url and test that the responses status code is using gaeunit how can do this would like to use the webapp framework and gaeunit which runs within the app engine sandbox unfortunately webtest does not work within the sandbox
|
actually webtest does work within the sandbox as long as you comment out import webbrowser in webtest init py
|
QA
|
how does one decrypt pdf with an owner password but no user password although the pdf specification is available from adobe it is not exactly the simplest document to read through pdf allows documents to be encrypted so that either user password and or an owner password is required to do various things with the document display print etc common use is to lock pdf so that end users can read it without entering any password but password is required to do anything else am trying to parse pdfs that are locked in this way to get the same privileges as you would get opening them in any reader using an empty string as the user password does not work but it seems section of the spec that there has to be user password to create the hash for the admin password what would like is either an explanation of how to do this or any code that can read ideally python or but anything readable will do that does this so that can understand what am meant to be doing standalone code rather than reading through the gsview source would be best
|
if remember correctly there is fixed padding string of bytes to apply to any password all passwords need to be bytes at the start of computing the encryption key either by truncating or adding some of those padding bytes if no user password was set you simply have to pad with all bytes of the string use the padding bytes as the starting point for computing the encryption key have to admit it is been while since have done this do remember that the encryption part of the pdf is an absolute mess as it got changed significantly in nearly every revision requiring you to cope with lot of cases to handle all pdf good luck
|
QA
|
disable output buffering is output buffering enabled by default in python interpreter for sys stdout if the answer is positive what are all the ways to disable it suggestions so far use the you command line switch wrap sys stdout in an object that flushes after every write set pythonunbuffered env var sys stdout os fdopen sys stdout fileno is there any other way to set some global flag in sys sys stdout programmatically during execution
|
you can create an unbuffered file and assign this file to sys stdout import sys myfile open log sys stdout myfile you cannot magically change the system supplied stdout since it is supplied to your python program by the os
|
QA
|
glade or no glade what is the best way to use pygtk have been learning python for while now with some success even managed to create one or two simple programs using pygtk glade the thing is am not sure if the best way to use gtk with python is by building the interfaces using glade was wondering if the more experienced ones among us remember am just beginner could point out the benefits and caveats of using glade as opposed to creating everything in the code itself assuming that learning the correct gtk bindings would not exactly be problem
|
usually start with glade until come to point where it does not have the features need creating wizard as long as am using the standard widgets that glade provides there is really no reason to hand code the gui the more comfortable become with how glade formats the code the better my hand coding becomes not to mention it is real easy to use glade to make the underlying framework so you do not have to worry about all the initializations
|
QA
|
how can represent an enum in python am mainly developer but am currently working on project in python how can represent the equivalent of an enum in python
|
def add class attribs attribs def foo name bases dict for in attribs dict return type name bases dict return foo def enum names class foo object metaclass add class attribs enumerate names def setattr self name value this makes it read only raise notimplementederror return foo use it like this animal enum dog cat animal dog returns animal cat returns animal dog raises notimplementederror if you just want unique symbols and do not care about the values replace this line metaclass add class attribs enumerate names with this metaclass add class attribs object name for name in names
|
QA
|
xml rpc best way to handle bit values so the official xml rpc standard does not support bit values but in these modern times bit values are increasingly common how do you handle these what xml rpc extensions are the most common what language bindings are there am especially interested in python and but all information is appreciated
|
some libraries support bits extensions indeed but there does not seem to be standard xmlrpc for example has so called but it does not work with python at least not by default would recommend to either convert the integer to string by hand and send it as such xmlrpc will convert it to string anyway so would say this is reasonable break it in two bits integers and send it as such
|
QA
|
ply token shifting problem in parser am writing parser using ply and recently ran into problem this code typedef int my type my type is correct code because my type is defined as type previously to being used as such handle it by filling type symbol table in the parser that gets used by the lexer to differentiate between types and simple identifiers however while the type declaration rule ends with semi the token ply shifts the token my type from the second line before deciding it is done with the first one because of this have no chance to pass the update in the type symbol table to the lexer and it sees my type as an identifier and not type any ideas for fix the full code is at http code google com pycparser source browse trunk src parser py not sure how can create smaller example out of this edit problem solved see my solution below
|
think you need to move the check for whether an id is typeid from lexer py to parser py as you said since the parser is looking ahead token you cannot make that decision in the lexer instead alter your parser to check id to see if they are typeid in declarations and if they are not generate an error as pax diablo said in his excellent answer the lexer tokenizer job is not to make those kinds of decisions about tokens that is the parser job
|
QA
|
ply token shifting problem in parser am writing parser using ply and recently ran into problem this code typedef int my type my type is correct code because my type is defined as type previously to being used as such handle it by filling type symbol table in the parser that gets used by the lexer to differentiate between types and simple identifiers however while the type declaration rule ends with semi the token ply shifts the token my type from the second line before deciding it is done with the first one because of this have no chance to pass the update in the type symbol table to the lexer and it sees my type as an identifier and not type any ideas for fix the full code is at http code google com pycparser source browse trunk src parser py not sure how can create smaller example out of this edit problem solved see my solution below
|
not sure why you are doing that level of analysis in your lexer lexical analysis should probably be used to separate the input stream into lexical tokens number line change keyword and so on it is the parsing phase that should be doing that level of analysis including table lookups for typedefs and such that is the way have always separated the duties between lexx and yacc my tools of choice
|
QA
|
how to apply bold style to specific word in excel file using python am using pyexcelerator python module to generate excel files want to apply bold style to part of cell text but not to the whole cell how to do it
|
this is an example from excel documentation with worksheets sheet range value new title characters font bold true end with so the characters property of the cell you want to manipulate is the answer to your question it is used as characters start length ps have never used the module in question but have used excel com automation in python scripts the characters property is available using win com
|
QA
|
union and intersect in django class tag models model name models charfield maxlength class blog models model name models charfield maxlength tags models manytomanyfield tag simple models just to ask my question wonder how can query blogs using tags in two different ways blog entries that are tagged with tag or tag blog objects filter tags in distinct blog objects that are tagged with tag and tag blog objects that are tagged with exactly tag and tag and nothing else tag and blog is just used for an example
|
you could use objects for blogs who have either hockey or django tags from django db models import blog objects filter tags name iexact hockey tags name iexact django unions and intersections believe are bit outside the scope of the django orm but its possible to to these the following examples are from django application called called django tagging that provides the functionality line of models py for part two you are looking for union of two queries basically def get union by model self queryset or model tags create queryset containing instances of the specified model associated with any of the given list of tags tags get tag list tags tag count len tags queryset model get queryset and model queryset or model if not tag count return model default manager none model table qn model meta db table this query selects the ids of all objects which have any of the given tags query select model pk from model tagged item where tagged item content type id content type id and tagged item tag id in tag id placeholders and model pk tagged item object id group by model pk model pk model table qn model meta pk column model model table tagged item qn self model meta db table content type id contenttype objects get for model model pk tag id placeholders join tag count cursor connection cursor cursor execute query tag pk for tag in tags object ids row for row in cursor fetchall if len object ids return queryset filter pk in object ids else return model default manager none for part believe you are looking for an intersection see line of models py def get intersection by model self queryset or model tags create queryset containing instances of the specified model associated with all of the given list of tags tags get tag list tags tag count len tags queryset model get queryset and model queryset or model if not tag count return model default manager none model table qn model meta db table this query selects the ids of all objects which have all the given tags query select model pk from model tagged item where tagged item content type id content type id and tagged item tag id in tag id placeholders and model pk tagged item object id group by model pk having count model pk tag count model pk model table qn model meta pk column model model table tagged item qn self model meta db table content type id contenttype objects get for model model pk tag id placeholders join tag count tag count tag count cursor connection cursor cursor execute query tag pk for tag in tags object ids row for row in cursor fetchall if len object ids return queryset filter pk in object ids else return model default manager none
|
QA
|
ply token shifting problem in parser am writing parser using ply and recently ran into problem this code typedef int my type my type is correct code because my type is defined as type previously to being used as such handle it by filling type symbol table in the parser that gets used by the lexer to differentiate between types and simple identifiers however while the type declaration rule ends with semi the token ply shifts the token my type from the second line before deciding it is done with the first one because of this have no chance to pass the update in the type symbol table to the lexer and it sees my type as an identifier and not type any ideas for fix the full code is at http code google com pycparser source browse trunk src parser py not sure how can create smaller example out of this edit problem solved see my solution below
|
with some help from dave beazley ply creator my problem was solved the idea is to use special sub rules and do the actions in them in my case split the declaration rule to def decl body self decl body declaration specifiers init declarator list opt handle the declaration here def declaration self declaration decl body semi decl body is always reduced before the token after semi is shifted in so my action gets executed at the correct time
|
QA
|
union and intersect in django class tag models model name models charfield maxlength class blog models model name models charfield maxlength tags models manytomanyfield tag simple models just to ask my question wonder how can query blogs using tags in two different ways blog entries that are tagged with tag or tag blog objects filter tags in distinct blog objects that are tagged with tag and tag blog objects that are tagged with exactly tag and tag and nothing else tag and blog is just used for an example
|
have tested these out with django the or queries blog objects filter tags name in tag tag distinct or you could use the class blog objects filter tags name tag tags name tag distinct the and query blog objects filter tags name tag filter tags name tag am not sure about the third one you will probably need to drop to sql to do it
|
QA
|
how do you configure django for simple development and deployment tend to use sqlite when doing django development but on live server something more robust is often needed mysql postgresql for example invariably there are other changes to make to the django settings as well different logging locations intensities media paths etc how do you manage all these changes to make deployment simple automated process
|
think it depends on the size of the site as to whether you need to step up from using sqlite have successfully used sqlite on several smaller live sites and it runs great
|
QA
|
how should best emulate and or avoid enum in python have been using small class to emulate enums in some python projects is there better way or does this make the most sense for some situations class code here class enum object simple enum class example usage codes enum foo bar baz codes baz will be and so on def init self names for number name in enumerate names split setattr self name number
|
enums have been proposed for inclusion into the language before but were rejected see http www python org dev peps pep though there are existing packages you could use instead of writing your own implementation enum http pypi python org pypi enum symboltype not quite the same as enums but still useful http pypi python org pypi symboltype or just do search
|
QA
|
how should best emulate and or avoid enum in python have been using small class to emulate enums in some python projects is there better way or does this make the most sense for some situations class code here class enum object simple enum class example usage codes enum foo bar baz codes baz will be and so on def init self names for number name in enumerate names split setattr self name number
|
the builtin way to do enums is foo bar baz range which works fine for small sets but has some drawbacks you need to count the number of elements by hand you cannot skip values if you add one name you also need to update the range number for complete enum implementation in python see http code activestate com recipes
|
QA
|
how should best emulate and or avoid enum in python have been using small class to emulate enums in some python projects is there better way or does this make the most sense for some situations class code here class enum object simple enum class example usage codes enum foo bar baz codes baz will be and so on def init self names for number name in enumerate names split setattr self name number
|
what see more often is this in top level module context foo bar foo bar foo baz foo baz foo qux foo qux and later if something is foo bar pass do something here elif something is foo baz pass do something else elif something is foo qux pass do something else else raise exception invalid value for something note that the use of is rather than is taking risk here it assumes that folks are using your module foo bar rather than the string foo bar which will normally be interned such that is will match but that certainly cannot be counted on and so may not be appropriate depending on context one advantage of doing it this way is that by looking anywhere reference to that string is being stored it is immediately obvious where it came from foo baz is much less ambiguous than besides that the other thing that offends my pythonic sensibilities re the class you propose is the use of split why not just pass in tuple list or other enumerable to start with
|
QA
|
how should best emulate and or avoid enum in python have been using small class to emulate enums in some python projects is there better way or does this make the most sense for some situations class code here class enum object simple enum class example usage codes enum foo bar baz codes baz will be and so on def init self names for number name in enumerate names split setattr self name number
|
there is lot of good discussion here
|
QA
|
what is the simplest way to find the difference between times in python have time values which have the type datetime time want to find their difference the obvious thing to do is but this does not work it works for objects of type datetime datetime but not for datetime time so what is the best way to do this
|
python has pytz http pytz sourceforge net module which can be used for arithmetic of time objects it takes care of dst offsets as well the above page has number of examples that illustrate the usage of pytz
|
QA
|
topological sort recursive using generators data dependency list already verified to be acyclic so here depends on depends on etc dict dict would dict dict would like to have top down recursive solution to let us say find the chain starting at so right now non generator solution def get all def get append for ii in get get ii get return obviously this is pretty weak have been banging my head about how to how to get yields inside there and would appreciate any py foo you all can bring to this
|
try this usr bin env python def get all yield for ii in get for jj in get all ii yield jj dict dict would dict dict for ii in get all print ii gives me steve rei code tmp python recur py
|
QA
|
how to generate all permutations of list in python how do you generate all the permutations of list in python independently of the type of elements in that list for example permutations permutations permutations permutations edit eliben pointed to solution that is similar to mine although simpler so am choosing it as the accepted answer although python has builtin solution in the itertools module import itertools itertools permutations
|
the following code is an in place permutation of given list implemented as generator since it only returns references to the list the list should not be modified outside the generator the solution is non recursive so uses low memory work well also with multiple copies of elements in the input list def permute in place sort yield list if len return first last len while last while if last while not swap the values are last reverse last yield list break if first reverse return if name main for in range for in permute in place range print print for in permute in place print print
|
QA
|
how should best emulate and or avoid enum in python have been using small class to emulate enums in some python projects is there better way or does this make the most sense for some situations class code here class enum object simple enum class example usage codes enum foo bar baz codes baz will be and so on def init self names for number name in enumerate names split setattr self name number
|
the most common enum case is enumerated values that are part of state or strategy design pattern the enums are specific states or specific optional strategies to be used in this case they are almost always part and parcel of some class definition class dotheneedful object one choice another choice yet another def init self aselection assert aselection in self one choice self another choice self yet another self selection aselection then in client of this class dtn dotheneeful dotheneeful one choice
|
QA
|
topological sort recursive using generators data dependency list already verified to be acyclic so here depends on depends on etc dict dict would dict dict would like to have top down recursive solution to let us say find the chain starting at so right now non generator solution def get all def get append for ii in get get ii get return obviously this is pretty weak have been banging my head about how to how to get yields inside there and would appreciate any py foo you all can bring to this
|
both answers give the same result but if my reading of the question is correct give the wrong answer to simple alteration to the given graph if you add dependency on from which does not introduce cycle as the graph is directed the output is which is not totally helpful try this small variation which keeps track of which nodes of the graph have already been visited def get all seen none if not seen seen set if not in seen seen add yield for ii in get for jj in get all ii seen yield jj
|
QA
|
python music library am looking at writing little drum machine in python for fun have googled some and found the python pages on music and basic audio as well as stackoverflow question on generating audio files but what am looking for is decent library for music creation has anyone on here tried to do something like this before if so what was your solution what either of the ones have found or something have not found would be decent library for audio manipulation minimally would like to be able to do something similar to audacity scope within python but if anyone knows of library that can do more am all ears
|
there is variety of python music software you can find catalog here if you scroll down the linked page you find section on music programming in python describing several music creation packages including musickit and pysndobj
|
QA
|
is there something like autotest for python unittests basically growl notifications or other callbacks when tests break or pass does anything like this exist if not it should be pretty easy to write easiest way would be to run python autotest myfile py myfile py etc py check if files to be monitored have been modified possibly just if they have been saved run any tests in those files if test fails but in the previous run it passed generate growl alert same with tests that fail then pass wait and repeat steps the problem can see there is if the tests are in different file the simple solution would be to run all the tests after each save but with slower tests this might take longer than the time between saves and or could use lot of cpu power etc the best way to do it would be to actually see what bits of code have changed if function abc has changed only run tests that interact with this while this would be great think it would be extremely complex to implement to summarise is there anything like the ruby tool autotest part of the zentest package but for python code how do you check which functions have changed between two revisions of script is it possible to determine which functions command will call somewhat like reverse traceback
|
maybe buildbot would be useful http buildbot net trac
|
QA
|
is there something like autotest for python unittests basically growl notifications or other callbacks when tests break or pass does anything like this exist if not it should be pretty easy to write easiest way would be to run python autotest myfile py myfile py etc py check if files to be monitored have been modified possibly just if they have been saved run any tests in those files if test fails but in the previous run it passed generate growl alert same with tests that fail then pass wait and repeat steps the problem can see there is if the tests are in different file the simple solution would be to run all the tests after each save but with slower tests this might take longer than the time between saves and or could use lot of cpu power etc the best way to do it would be to actually see what bits of code have changed if function abc has changed only run tests that interact with this while this would be great think it would be extremely complex to implement to summarise is there anything like the ruby tool autotest part of the zentest package but for python code how do you check which functions have changed between two revisions of script is it possible to determine which functions command will call somewhat like reverse traceback
|
for your third question maybe the trace module is what you need def return def return import trace tracer trace trace countfuncs tracer runfunc res tracer results res calledfuncs stdin stdin stdin stdin res calledfuncs contains the functions that were called if you specify countcallers when creating the tracer you can get caller callee relationships see the docs of the trace module for more information you can also try to get the calls via static analysis but this can be dangerous due to the dynamic nature of python
|
QA
|
python music library am looking at writing little drum machine in python for fun have googled some and found the python pages on music and basic audio as well as stackoverflow question on generating audio files but what am looking for is decent library for music creation has anyone on here tried to do something like this before if so what was your solution what either of the ones have found or something have not found would be decent library for audio manipulation minimally would like to be able to do something similar to audacity scope within python but if anyone knows of library that can do more am all ears
|
had to do this years ago used pymedia am not sure if it is still around any way here is some test code wrote when was playing with it it is about years old though edit the sample code plays an mp file import pymedia import time demuxer pymedia muxer demuxer mp this thing decodes the multipart file call it demucker open path to song mp rb spot read frames demuxer parse spot print read it has frames len frames decoder pymedia audio acodec decoder demuxer streams this thing does the actual decoding frame decoder decode spot print dir frame sys exit sound pymedia audio sound print frame bitrate frame sample rate song sound output frame sample rate frame channels this thing handles playing the song while len spot try if frame song play frame data spot read frame decoder decode spot except pass while song isplaying time sleep print well done
|
QA
|
delete all data for kind in google app engine would like to wipe out all data for specific kind in google app engine what is the best way to do this wrote delete script hack but since there is so much data is timeout out after few hundred records
|
presumably your hack was something like this deleting all messages older than earliest date db gqlquery select from message where create date earliest date results fetch while results db delete results results fetch len results as you say if there is sufficient data you are going to hit the request timeout before it gets through all the records you would have to re invoke this request multiple times from outside to ensure all the data was erased easy enough to do but hardly ideal the admin console does not seem to offer any help as from my own experience with it it seems to only allow entities of given type to be listed and then deleted on page by page basis when testing have had to purge my database on startup to get rid of existing data would infer from this that google operates on the principle that disk is cheap and so data is typically orphaned indexes to redundant data replaced rather than deleted given there is fixed amount of data available to each app at the moment gb that is not much help for non google app engine users
|
QA
|
is there something like autotest for python unittests basically growl notifications or other callbacks when tests break or pass does anything like this exist if not it should be pretty easy to write easiest way would be to run python autotest myfile py myfile py etc py check if files to be monitored have been modified possibly just if they have been saved run any tests in those files if test fails but in the previous run it passed generate growl alert same with tests that fail then pass wait and repeat steps the problem can see there is if the tests are in different file the simple solution would be to run all the tests after each save but with slower tests this might take longer than the time between saves and or could use lot of cpu power etc the best way to do it would be to actually see what bits of code have changed if function abc has changed only run tests that interact with this while this would be great think it would be extremely complex to implement to summarise is there anything like the ruby tool autotest part of the zentest package but for python code how do you check which functions have changed between two revisions of script is it possible to determine which functions command will call somewhat like reverse traceback
|
django development server has file change monitor that watches for modifications and automatically reloads itself you could re use this code to launch unit tests on file modification
|
QA
|
is there something like autotest for python unittests basically growl notifications or other callbacks when tests break or pass does anything like this exist if not it should be pretty easy to write easiest way would be to run python autotest myfile py myfile py etc py check if files to be monitored have been modified possibly just if they have been saved run any tests in those files if test fails but in the previous run it passed generate growl alert same with tests that fail then pass wait and repeat steps the problem can see there is if the tests are in different file the simple solution would be to run all the tests after each save but with slower tests this might take longer than the time between saves and or could use lot of cpu power etc the best way to do it would be to actually see what bits of code have changed if function abc has changed only run tests that interact with this while this would be great think it would be extremely complex to implement to summarise is there anything like the ruby tool autotest part of the zentest package but for python code how do you check which functions have changed between two revisions of script is it possible to determine which functions command will call somewhat like reverse traceback
|
maybe nose http somethingaboutorange com mrl projects nose has plugin http somethingaboutorange com mrl projects nose doc writing plugins html found this http jeffwinkler net keeping your nose green
|
QA
|
delete all data for kind in google app engine would like to wipe out all data for specific kind in google app engine what is the best way to do this wrote delete script hack but since there is so much data is timeout out after few hundred records
|
unfortunately there is no way to easily do bulk delete your best bet is to write script that deletes reasonable number of entries per invocation and then call it repeatedly for example by having your delete script return redirect whenever there is more data to delete then fetching it with wget max redirect or some other large number
|
QA
|
how to get instance variables in python is there built in method in python to get an array of all class instance variables for example if have this code class hi def init self self ii foo self okay bar is there way for me to do this mystery method hi ii okay thanks guys edit originally had asked for class variables erroneously thanks to all who brought this to my attention
|
every object has dict variable containing all the variables and its values in it try this hi obj hi hi obj dict keys
|
QA
|
how to get instance variables in python is there built in method in python to get an array of all class instance variables for example if have this code class hi def init self self ii foo self okay bar is there way for me to do this mystery method hi ii okay thanks guys edit originally had asked for class variables erroneously thanks to all who brought this to my attention
|
you normally cannot get instance attributes given just class at least not without instantiating the class you can get instance attributes given an instance though or class attributes given class see the inspect module you cannot get list of instance attributes because instances really can have anything as attribute and as in your example the normal way to create them is to just assign to them in the init method an exception is if your class uses slots which is fixed list of attributes that the class allows instances to have slots are explained in http www python org descrintro html but there are various pitfalls with slots they affect memory layout so multiple inheritance may be problematic and inheritance in general has to take slots into account too
|
QA
|
how to get instance variables in python is there built in method in python to get an array of all class instance variables for example if have this code class hi def init self self ii foo self okay bar is there way for me to do this mystery method hi ii okay thanks guys edit originally had asked for class variables erroneously thanks to all who brought this to my attention
|
you can also test if an object has specific variable with hi obj hi hasattr hi obj some attribute
|
QA
|
how to get instance variables in python is there built in method in python to get an array of all class instance variables for example if have this code class hi def init self self ii foo self okay bar is there way for me to do this mystery method hi ii okay thanks guys edit originally had asked for class variables erroneously thanks to all who brought this to my attention
|
your example shows instance variables not really class variables look in hi obj class dict items for the class variables along with other other class members like member functions and the containing module class hi object class var skidoo class variable def init self self ii foo instance variable self jj bar class variables are shared by all instances of the class
|
QA
|
python music library am looking at writing little drum machine in python for fun have googled some and found the python pages on music and basic audio as well as stackoverflow question on generating audio files but what am looking for is decent library for music creation has anyone on here tried to do something like this before if so what was your solution what either of the ones have found or something have not found would be decent library for audio manipulation minimally would like to be able to do something similar to audacity scope within python but if anyone knows of library that can do more am all ears
|
take close look at csounds there are python bindings allow you to do pretty flexible digital synthesis there are some pretty complete packages available too see http www csounds com node for package see http www csounds com journal issue pythonopcodes html for information on python scripting within csounds
|
QA
|
how to get instance variables in python is there built in method in python to get an array of all class instance variables for example if have this code class hi def init self self ii foo self okay bar is there way for me to do this mystery method hi ii okay thanks guys edit originally had asked for class variables erroneously thanks to all who brought this to my attention
|
use vars class foo object def init self self self vars foo vars foo keys
|
QA
|
how to get instance variables in python is there built in method in python to get an array of all class instance variables for example if have this code class hi def init self self ii foo self okay bar is there way for me to do this mystery method hi ii okay thanks guys edit originally had asked for class variables erroneously thanks to all who brought this to my attention
|
suggest print vars doc vars object dictionary without arguments equivalent to locals with an argument equivalent to object dict in otherwords it essentially just wraps dict
|
QA
|
replacements for switch statement in python want to write function in python that returns different fixed values based on the value of an input index in other languages would use switch or case statement but python does not appear to have switch statement what are the recommended python solutions in this scenario
|
true switch case in python is going to be more difficult than dictionary method or if elif else methods because the simple versions do not support fall through another downfall of the if elif else method is the need for repeated comparisons the implementation of switch case has performance benefit over if else if else in that only single comparison is needed the result of that comparison is used as an offset into jump table in the underlying asm generated mimicking the true functionality in python would be pain does any one have an implementation that would allow for fall through while only using single comparison
|
QA
|
how do use django templates without the rest of django want to use the django template engine in my python code but am not building django based web site how do use it without having settings py file and others and having to set the django settings module environment variable if run the following code import django template from django template import template context template my name is my name get importerror settings cannot be imported because environment variable django settings module is undefined
|
would also recommend jinja there is nice article on django vs jinja that gives some in detail information on why you should prefere the later
|
QA
|
how do persist to disk temporary file using python am attempting to use the tempfile module for manipulating and creating text files once the file is ready want to save it to disk thought it would be as simple as using shutil copy however get permission denied ioerror import tempfile shutil tempfile temporaryfile mode write foo shutil copy name bar txt traceback most recent call last file pyshell line in module shutil copy name bar txt file python lib shutil py line in copy copyfile src dst file python lib shutil py line in copyfile fsrc open src rb ioerror errno permission denied docume me locals temp tmpvqq go is this not intended when using the tempfile library is there better way to do this maybe am overlooking something very trivial
|
starting from python you can also use namedtemporaryfile with the delete option set to false this way the temporary file will be accessible even after you close it note that on windows nt and later you cannot access the file second time while it is still open you have to close it before you can copy it this is not true on unix systems
|
QA
|
python music library am looking at writing little drum machine in python for fun have googled some and found the python pages on music and basic audio as well as stackoverflow question on generating audio files but what am looking for is decent library for music creation has anyone on here tried to do something like this before if so what was your solution what either of the ones have found or something have not found would be decent library for audio manipulation minimally would like to be able to do something similar to audacity scope within python but if anyone knows of library that can do more am all ears
|
in addition to what has been mentioned previously wrote simple python audio editor http code google com yaalp source browse svn trunk see main py it also has audio manipulation and some effects code gpl so this could be starting point for you
|
QA
|
how to apply bold style to specific word in excel file using python am using pyexcelerator python module to generate excel files want to apply bold style to part of cell text but not to the whole cell how to do it
|
found example here generate an excel formatted file right in python notice that you make font object and then give it to style object and then provide that style object when writing to the sheet import pyexcelerator as xl def save in excel headers values open new workbook mydoc xl workbook add worksheet mysheet mydoc add sheet test write headers header font xl font make font object header font bold true header font underline true font needs to be style actually header style xl xfstyle header style font header font for col value in enumerate headers mysheet write col value header style write values and highlight those that match my criteria highlighted row font xl font no real highlighting available highlighted row font bold true highlighted row font colour index is red highlighted row style xl xfstyle highlighted row style font highlighted row font for row num row values in enumerate values row num start at row if row values manatee for col value in enumerate row values make manatee sp red mysheet write row num col value highlighted row style else for col value in enumerate row values normal row mysheet write row num col value save file mydoc save testpyexel xlt headers date name localatity data june greg san jose june greg san jose june greg san jose june greg san jose june manatee san jose june greg san jose june manatee san jose save in excel headers data
|
QA
|
python signal woes sigquit handler delays execution if sigquit recieved during execution of another signal handler the following program is very simple it outputs single dot each half second if it recieves sigquit it proceeds to output ten qs if it recieves sigtstp ctrl it outputs ten zs if it recieves sigtstp while printing qs it will print ten zs after it is done with the ten qs this is good thing however if it recieves sigquit while printing zs it fails to print qs after them instead it prints them out only after manually terminate execution via keyboardinterrupt want the qs to be printed immediately after the zs this happens using python hope have made silly easily correctable mistake somewhere what am doing wrong muchas gracias usr bin python from signal import from time import sleep from sys import stdout def write text stdout write text stdout flush def process quit signum frame for in range write sleep def process tstp signum frame for in range write sleep signal sigquit process quit signal sigtstp process tstp while write sleep
|
your larger problem is blocking in signal handlers this is usually discouraged since it can lead to strange timing conditions but it is not quite the because of your problem since the timing condition you are vulnerable to exists because of your choice of signal handlers anyway here is how to at least minimize the timing condition by only setting flags in your handlers and leaving the main while loop to do the actual work the explanation for why your code is behaving strangely is described after the code usr bin python from signal import from time import sleep from sys import stdout print qs print zs def write text stdout write text stdout flush def process quit signum frame global print qs print qs def process tstp signum frame global print zs print zs signal sigquit process quit signal sigtstp process tstp while if print zs print zs elif print qs print qs else write sleep anyway here is what is going on sigtstp is more special than sigquit sigtstp masks the other signals from being delivered while its signal handler is running when the kernel goes to deliver sigquit and sees that sigtstp handler is still running it simply saves it for later once another signal comes through for delivery such as sigint when you ctrl aka keyboardinterrupt the kernel remembers that it never delivered sigquit and delivers it now you will notice if you change while to for in range in the main loop and do your test case again the program will exit without running the sigtstp handler since exit does not re trigger the kernel signal delivery mechanism good luck
|
QA
|
python signal woes sigquit handler delays execution if sigquit recieved during execution of another signal handler the following program is very simple it outputs single dot each half second if it recieves sigquit it proceeds to output ten qs if it recieves sigtstp ctrl it outputs ten zs if it recieves sigtstp while printing qs it will print ten zs after it is done with the ten qs this is good thing however if it recieves sigquit while printing zs it fails to print qs after them instead it prints them out only after manually terminate execution via keyboardinterrupt want the qs to be printed immediately after the zs this happens using python hope have made silly easily correctable mistake somewhere what am doing wrong muchas gracias usr bin python from signal import from time import sleep from sys import stdout def write text stdout write text stdout flush def process quit signum frame for in range write sleep def process tstp signum frame for in range write sleep signal sigquit process quit signal sigtstp process tstp while write sleep
|
on python on linux your code works exactly as you describe your desired results if signal is received while still processing previous signal the new signal is processed immediately after the first one is finished on python on linux see the problem behavior you describe do not know whether this is due to change in python or in the linux kernel
|
QA
|
how does one decrypt pdf with an owner password but no user password although the pdf specification is available from adobe it is not exactly the simplest document to read through pdf allows documents to be encrypted so that either user password and or an owner password is required to do various things with the document display print etc common use is to lock pdf so that end users can read it without entering any password but password is required to do anything else am trying to parse pdfs that are locked in this way to get the same privileges as you would get opening them in any reader using an empty string as the user password does not work but it seems section of the spec that there has to be user password to create the hash for the admin password what would like is either an explanation of how to do this or any code that can read ideally python or but anything readable will do that does this so that can understand what am meant to be doing standalone code rather than reading through the gsview source would be best
|
xpdf is probably good reference implementation for this sort of problem have successfully used them to open encrypted pdfs before
|
QA
|
change the width of form elements created with modelform in django how can change the width of textarea form element if used modelform to create it here is my product class class productform modelform long desc forms charfield widget forms textarea short desc forms charfield widget forms textarea class meta model product and the template code for in form name endfor is the actual form element
|
the easiest way for your use case is to use css it is language meant for defining presentation look at the code generated by form take note of the ids for fields that interest you and change appearance of these fields through css example for long desc field in your productform when your form does not have custom prefix id long desc width px height px second approach is to pass the attrs keyword to your widget constructor class productform modelform long desc forms charfield widget forms textarea attrs cols rows short desc forms charfield widget forms textarea class meta model product it is described in django documentation third approach is to leave the nice declarative interface of newforms for while and set your widget attributes in custom constructor class productform modelform long desc forms charfield widget forms textarea short desc forms charfield widget forms textarea class meta model product edit by bryan def init self args kwargs super productform self init args kwargs call to modelform constructor self fields long desc widget attrs cols self fields long desc widget attrs rows this approach has the following advantages you can define widget attributes for fields that are generated automatically from your model without redefining whole fields it does not depend on the prefix of your form
|
QA
|
union and intersect in django class tag models model name models charfield maxlength class blog models model name models charfield maxlength tags models manytomanyfield tag simple models just to ask my question wonder how can query blogs using tags in two different ways blog entries that are tagged with tag or tag blog objects filter tags in distinct blog objects that are tagged with tag and tag blog objects that are tagged with exactly tag and tag and nothing else tag and blog is just used for an example
|
please do not reinvent the wheel and use django tagging application which was made exactly for your use case it can do all queries you describe and much more if you need to add custom fields to your tag model you can also take look at my branch of django tagging
|
QA
|
is there an easy way to request url in python and not follow redirects looking at the source of urllib it looks like the easiest way to do it would be to subclass httpredirecthandler and then use build opener to override the default httpredirecthandler but this seems like lot of relatively complicated work to do what seems like it should be pretty simple
|
dive into python has good chapter on handling redirects with urllib another solution is httplib import httplib conn httplib httpconnection www bogosoft com conn request get conn getresponse print status reason moved permanently print getheader location http www bogosoft com new location
|
QA
|
how do you load an embedded icon from an exe file with pywin have an exe file generated with py exe in the setup py specify an icon to be embedded in the exe windows script my script py icon resources my icon ico tried loading the icon using hinst win api getmodulehandle none hicon win gui loadimage hinst win con image icon win con lr defaultsize but this produces an very unspecific error pywintypes error loadimage no error message is available if try specifying as string hicon win gui loadimage hinst win con image icon win con lr defaultsize then get the error pywintypes error loadimage the specified resource type cannot be found in the image file so what is the correct method syntax to load the icon also please notice that do not use any gui toolkit just the windows api via pywin
|
efotinis you are right here is workaround until py exe gets fixed and you do not want to include the same icon twice hicon win gui createiconfromresource win api loadresource none win con rt icon true be aware that is not the id you gave the icon in setup py which is the icon group id but the resource id automatically assigned by py exe to each icon in each icon group at least that is how understand it if you want to create an icon with specified size as createiconfromresource uses the system default icon size you need to use createiconfromresourceex which is not available via pywin icon res win api loadresource none win con rt icon hicon ctypes windll user createiconfromresourceex icon res len icon res true win con lr defaultcolor
|
QA
|
re ordering entries in model using drag and drop say have blogging app in django how can re order the posts using draggable table in the default admin it would be best if did not have to add any extra fields to the model but if really have to can
|
in model class you would probably have to add order field to maintain specific order eg item with order is the last one and order is the first one then you can add js code in admin change list template see this to maintain drag drop feature finally change ordering in meta of model to something like order
|
QA
|
is there an easy way to request url in python and not follow redirects looking at the source of urllib it looks like the easiest way to do it would be to subclass httpredirecthandler and then use build opener to override the default httpredirecthandler but this seems like lot of relatively complicated work to do what seems like it should be pretty simple
|
second olt pointer to dive into python here is an implementation using urllib redirect handlers more work than it should be maybe shrug import sys import urllib class redirecthandler urllib httpredirecthandler def http error self req fp code message headers result urllib httpredirecthandler http error self req fp code message headers result status code raise exception permanent redirect def http error self req fp code message headers result urllib httpredirecthandler http error self req fp code message headers result status code raise exception temporary redirect def main script name url opener urllib build opener redirecthandler urllib install opener opener print urllib urlopen url read if name main main sys argv
|
QA
|
report generation am writing web app using turbogears and in that app the users must be able to generate different reports the data the reports need is stored in database mysql the reports must be returned either as easily printable html document or pdf file have previously used jasper and ireport for creating the documents but if can avoid having to fire up java to create the report would be happy ideally would like to specify reports in easily readable markup language and then just feed the template data with some kind of library that produces the report gladly accept any kind of hints on how should go about generating these reports
|
partial answer the easily readable format you are looking for might be docbook from there it is very easy to go to pdf html rtf etc etc
|
QA
|
dirty fields in django in my app need to save changed values old and new when model gets saved any examples or working code need this for premoderation of content for example if user changes something in model then administrator can see all changes in separate table and then decide to apply them or not
|
if you are using your own transactions not the default admin application you can save the before and after versions of your object you can save the before version in the session or you can put it in hidden fields in the form hidden fields is security nightmare therefore use the session to retain history of what is happening with this user additionally of course you do have to fetch the previous object so you can make changes to it so you have several ways to monitor the differences def updatesomething request object id object model objects get id object id if request method get request session before object form somethingform instance object else request method post form somethingform request post if form is valid you have before in the session you have the old object you have after in the form cleaned data log the changes apply the changes to the object object save
|
QA
|
re ordering entries in model using drag and drop say have blogging app in django how can re order the posts using draggable table in the default admin it would be best if did not have to add any extra fields to the model but if really have to can
|
note on the it would be best if did not have to add any extra fields to the model but if really have to can sorry but order of information in database is determined by the information itself you always have to add column for ordering there is really no choice about that further to retrieve things in this order you will need to specifically add order by to your queries or add ordering to your model class inorder models model position models integerfield data models textfield class meta ordering position without the additional field ordering cannot happen it is one of the rules of relational databases
|
QA
|
how can do line break line continuation in python have long line of code that want to break up among multiple lines what do use and what is the syntax for example adding bunch of strings would and have it like this would
|
you can break lines in between parenthesises and braces additionally you can append the backslash character to line to explicitly break it tuples first value second value
|
QA
|
close tkinter window how do end tkinter program let us say have this code from tkinter import def quit code to exit root tk button root text quit command quit pack root mainloop how should define the quit function
|
we can use def quit root quit or def quit root destroy
|
QA
|
report generation am writing web app using turbogears and in that app the users must be able to generate different reports the data the reports need is stored in database mysql the reports must be returned either as easily printable html document or pdf file have previously used jasper and ireport for creating the documents but if can avoid having to fire up java to create the report would be happy ideally would like to specify reports in easily readable markup language and then just feed the template data with some kind of library that produces the report gladly accept any kind of hints on how should go about generating these reports
|
you can build some fancy pdfs from python with the reportlab toolkit
|
QA
|
close tkinter window how do end tkinter program let us say have this code from tkinter import def quit code to exit root tk button root text quit command quit pack root mainloop how should define the quit function
|
the usual method to exit python program sys exit to which you can also pass an exit status or raise systemexit will work fine in tkinter program
|
QA
|
is there an easy way to request url in python and not follow redirects looking at the source of urllib it looks like the easiest way to do it would be to subclass httpredirecthandler and then use build opener to override the default httpredirecthandler but this seems like lot of relatively complicated work to do what seems like it should be pretty simple
|
suppose this would help from httplib import http def get html uri num redirections put it as for not to follow redirects conn http return conn request uri redirections num redirections
|
QA
|
re ordering entries in model using drag and drop say have blogging app in django how can re order the posts using draggable table in the default admin it would be best if did not have to add any extra fields to the model but if really have to can
|
for working code to do this check out snippet at djangosnippets org
|
QA
|
dirty fields in django in my app need to save changed values old and new when model gets saved any examples or working code need this for premoderation of content for example if user changes something in model then administrator can see all changes in separate table and then decide to apply them or not
|
you have not said very much about your specific use case or needs in particular it would be helpful to know what you need to do with the change information how long do you need to store it if you only need to store it for transient purposes lott session solution may be best if you want full audit trail of all changes to your objects stored in the db try this audittrail solution update the audittrail code linked to above is the closest have seen to full solution that would work for your case though it has some limitations does not work at all for manytomany fields it will store all previous versions of your objects in the db so the admin could roll back to any previous version you would have to work with it bit if you want the change to not take effect until approved you could also build custom solution based on something like armin ronacher diffingmixin you would store the different dictionary maybe pickled in table for the admin to review later and apply if desired you would need to write the code to take the different dictionary and apply it to an instance
|
QA
|
report generation am writing web app using turbogears and in that app the users must be able to generate different reports the data the reports need is stored in database mysql the reports must be returned either as easily printable html document or pdf file have previously used jasper and ireport for creating the documents but if can avoid having to fire up java to create the report would be happy ideally would like to specify reports in easily readable markup language and then just feed the template data with some kind of library that produces the report gladly accept any kind of hints on how should go about generating these reports
|
pod is my favorite solution to your problem
|
QA
|
how do handle the window close event in tkinter how do handle the window close event user clicking the button in python tkinter program
|
tkinter supports mechanism called protocol handlers here the term protocol refers to the interaction between the application and the window manager the most commonly used protocol is called wm delete window and is used to define what happens when the user explicitly closes window using the window manager you can use the protocol method to install handler for this protocol the widget must be tk or toplevel widget here you have concrete example import tkinter as tk from tkinter import messagebox root tk tk def on closing if messagebox askokcancel quit do you want to quit root destroy root protocol wm delete window on closing root mainloop
|
QA
|
unit testing file modifications common task in programs have been working on lately is modifying text file in some way hey am on linux everything file and do large scale system admin but the file the code modifies may not exist on my desktop box and probably do not want to modify it if it is on my desktop have read about unit testing in dive into python and it is pretty clear what want to do when testing an app that converts decimal to roman numerals the example in dintop the testing is nicely self contained you do not need to verify that the program prints the right thing you just need to verify that the functions are returning the right output to given input in my case however we need to test that the program is modifying its environment correctly here is what have come up with create the original file in standard location perhaps tmp run the function that modifies the file passing it the path to the file in tmp verify that the file in tmp was changed correctly pass fail unit test accordingly this seems kludgy to me gets even kludgier if you want to verify that backup copies of the file are created properly etc has anyone come up with better way
|
you are talking about testing too much at once if you start trying to attack testing problem by saying let us verify that it modifies its environment correctly you are doomed to failure environments have dozens maybe even millions of potential variations instead look at the pieces units of your program for example are you going to have function that determines where the files are that have to be written what are the inputs to that function perhaps an environment variable perhaps some values read from config file test that function and do not actually do anything that modifies the filesystem do not pass it realistic values pass it values that are easy to verify against make temporary directory populate it with files in your test setup method then test the code that writes the files just make sure it is writing the right contents file contents do not even write to real filesystem you do not need to make fake file objects for this just use python handy stringio modules they are real implementations of the file interface they are just not the ones that your program is actually going to be writing to ultimately you will have to test the final everything is actually hooked up for real top level function that passes the real environment variable and the real config file and puts everything together but do not worry about that to get started for one thing you will start picking up tricks as you write individual tests for smaller functions and creating test mocks fakes and stubs will become second nature to you for another even if you cannot quite figure out how to test that one function call you will have very high level of confidence that everything which it is calling works perfectly also you will notice that test driven development forces you to make your apis clearer and more flexible for example it is much easier to test something that calls an open method on an object that came from somewhere abstract than to test something that calls os open on string that you pass it the open method is flexible it can be faked it can be implemented differently but string is string and os open does not give you any leeway to catch what methods are called on it you can also build testing tools to make repetitive tasks easy for example twisted provides facilities for creating temporary files for testing built right into its testing tool it is not uncommon for testing tools or larger projects with their own test libraries to have functionality like this
|
QA
|
python on windows how to wait for multiple child processes how to wait for multiple child processes in python on windows without active wait polling something like this almost works for me proc subprocess popen python mytest py proc subprocess popen python mytest py proc wait print finished proc wait print finished the problem is that when proc finishes before proc the parent process will still wait for proc on unix one would use waitpid in loop to get the child processes return codes as they finish how to achieve something like this in python on windows
|
twisted has an asynchronous process spawning api which works on windows there are actually several different implementations many of which are not so great but you can switch between them without changing your code
|
QA
|
what is callable in python now that it is clear what metaclass is there is an associated concept that use all the time without knowing what it really means suppose everybody made once mistake with parenthesis resulting in an object is not callable exception what is more using init and new lead to wonder what this bloody call can be used for could you give me some explanations including examples with the magic method
|
callable is an object that has the call method this means you can fake callable functions or do neat things like partial function application where you take function and add something that enhances it or fills in some of the parameters returning something that can be called in turn known as currying in functional programming circles certain typographic errors will have the interpreter attempting to call something you did not intend such as for example string this can produce errors where the interpreter attempts to execute non callable application you can see this happening in python interpreter by doing something like the transcript below nigel python python nov gcc red hat on linux type help copyright credits or license for more information aaa here we attempt to call string traceback most recent call last file stdin line in module typeerror str object is not callable
|
QA
|
what is callable in python now that it is clear what metaclass is there is an associated concept that use all the time without knowing what it really means suppose everybody made once mistake with parenthesis resulting in an object is not callable exception what is more using init and new lead to wonder what this bloody call can be used for could you give me some explanations including examples with the magic method
|
quite simply callable is something that can be called like method the built in function callable will tell you whether something appears to be callable as will checking for call property functions are callable as are classes class instances can be callable see more about this here and here
|
QA
|
what is callable in python now that it is clear what metaclass is there is an associated concept that use all the time without knowing what it really means suppose everybody made once mistake with parenthesis resulting in an object is not callable exception what is more using init and new lead to wonder what this bloody call can be used for could you give me some explanations including examples with the magic method
|
it is something you can put args after and expect it to work callable is usually method or class methods get called classes get instantiated
|
QA
|
what is callable in python now that it is clear what metaclass is there is an associated concept that use all the time without knowing what it really means suppose everybody made once mistake with parenthesis resulting in an object is not callable exception what is more using init and new lead to wonder what this bloody call can be used for could you give me some explanations including examples with the magic method
|
callable is anything that can be called the built in callable pycallable check in objects checks if the argument is either an instance of class with call method or is of type that has non null tp call struct member which indicates callability otherwise such as in functions methods etc the method named call is according to the documentation called when the instance is called as function example class foo def call self print called foo instance foo foo instance this is calling the call method
|
QA
|
what is callable in python now that it is clear what metaclass is there is an associated concept that use all the time without knowing what it really means suppose everybody made once mistake with parenthesis resulting in an object is not callable exception what is more using init and new lead to wonder what this bloody call can be used for could you give me some explanations including examples with the magic method
|
call makes any object be callable as function this example will output class adder object def init self val self val val def call self val return self val val func adder print func
|
QA
|
distributed python what is the best python framework to create distributed applications for example to build app
|
you probably want twisted there is framework for twisted called vertex while not actively maintained it does allow you to tunnel through nats and make connections directly between users in very abstract way if there were more interest in this sort of thing am sure it would be more actively maintained
|
QA
|
how do split string into list if have this string what is the most efficient approach for creating this list
|
it just so happens that the tokens you want split are already python tokens so you can use the built in tokenize module it is almost one liner from cstringio import stringio from tokenize import generate tokens string list token string for token in generate tokens stringio readline if token string
|
QA
|
dirty fields in django in my app need to save changed values old and new when model gets saved any examples or working code need this for premoderation of content for example if user changes something in model then administrator can see all changes in separate table and then decide to apply them or not
|
django is currently sending all columns to the database even if you just changed one to change this some changes in the database system would be necessary this could be easily implemented on the existing code by adding set of dirty fields to the model and adding column names to it each time you set column value if you need that feature would suggest you look at the django orm implement it and put patch into the django trac it should be very easy to add that and it would help other users too when you do that add hook that is called each time column is set if you do not want to hack on django itself you could copy the dict on object creation and different it maybe with mixin like this class diffingmixin object def init self args kwargs super diffingmixin self init args kwargs self original state dict self dict def get changed columns self missing object result for key value in self original state iteritems if key self dict get key missing result key value return result class mymodel diffingmixin models model pass this code is untested but should work when you call model get changed columns you get dict of all changed values this of course will not work for mutable objects in columns because the original state is flat copy of the dict
|
QA
|
what is callable in python now that it is clear what metaclass is there is an associated concept that use all the time without knowing what it really means suppose everybody made once mistake with parenthesis resulting in an object is not callable exception what is more using init and new lead to wonder what this bloody call can be used for could you give me some explanations including examples with the magic method
|
in python callable is an object which type has call method class foo pass class bar object pass type foo call foo main foo instance at type bar call bar main bar object at def foo bar return bar type foo call foo as simple as that this of course can be overloaded class foo object def call self return foo
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.