prefix
stringclasses 1
value | input_text
stringlengths 19
27.3k
⌀ | target_text
stringlengths 2
24.8k
⌀ |
---|---|---|
QA
|
what is the difference between staticmethod and classmethod in python what is the difference between function decorated with staticmethod and one decorated with classmethod
|
staticmethod is method that knows nothing about the class or instance it was called on it just gets the arguments that were passed no implicit first argument it is basically useless in python you can just use module function instead of staticmethod classmethod on the other hand is method that gets passed the class it was called on or the class of the instance it was called on as first argument this is useful when you want the method to be factory for the class since it gets the actual class it was called on as first argument you can always instantiate the right class even when subclasses are involved observe for instance how dict fromkeys classmethod returns an instance of the subclass when called on subclass class dictsubclass dict def repr self return dictsubclass dict fromkeys abc none none none dictsubclass fromkeys abc dictsubclass
|
QA
|
what is the difference between staticmethod and classmethod in python what is the difference between function decorated with staticmethod and one decorated with classmethod
|
basically classmethod makes method whose first argument is the class it is called from rather than the class instance staticmethod does not have any implicit arguments
|
QA
|
python web development with or without framework am planning on porting php application over to python the application is mostly about data collection and processing the main application runs as stand alone command line application there is web interface to the application which is basically very light weight reporting interface did not use framework in the php version but being new to python am wondering if it would be advantageous to use something like django or at the very least genshi the caveat is do not want my application distribution to be overwhelmed by the framework parts would need to distribute with the application is using only the cgi import in python the best way to go in this circumstance would tend to think framework is too much overhead but perhaps am not thinking in very python way about them what suggestions do you have in this scenario
|
depends on the size of the project if you had only few previous php scripts which called your stand alone application then would probably go for cgi app if you have use for databases url rewriting templating user management and such then using framework is good idea and of course before you port it consider if it is worth it just to switch the language or if there are specific python features you need good luck
|
QA
|
python web development with or without framework am planning on porting php application over to python the application is mostly about data collection and processing the main application runs as stand alone command line application there is web interface to the application which is basically very light weight reporting interface did not use framework in the php version but being new to python am wondering if it would be advantageous to use something like django or at the very least genshi the caveat is do not want my application distribution to be overwhelmed by the framework parts would need to distribute with the application is using only the cgi import in python the best way to go in this circumstance would tend to think framework is too much overhead but perhaps am not thinking in very python way about them what suggestions do you have in this scenario
|
it depends on the way you are going to distribute your application if it will only be used internally go for django it is joy to work with it however django really falls short at the distribution task django applications are pain to set up
|
QA
|
python web development with or without framework am planning on porting php application over to python the application is mostly about data collection and processing the main application runs as stand alone command line application there is web interface to the application which is basically very light weight reporting interface did not use framework in the php version but being new to python am wondering if it would be advantageous to use something like django or at the very least genshi the caveat is do not want my application distribution to be overwhelmed by the framework parts would need to distribute with the application is using only the cgi import in python the best way to go in this circumstance would tend to think framework is too much overhead but perhaps am not thinking in very python way about them what suggestions do you have in this scenario
|
the command line python am going to definitely comes first get that to work since that is the core of what you are doing the issue is that using web framework orm from command line application is not obvious django provides specific instructions for using their orm from command line app those are annoying at first but think they are life saver in the long run use it heavily for giant uploads of customer supplied files do not use bare cgi it is not impossible but too many things can go wrong and they have all been solved by the frameworks why reinvent something just use someone else code frameworks involve learning but no real overhead they are not slow they are code you do not have to write or debug learn some python do the django tutorial start to build web app start django project build small application in that project build your new model using the django orm create django unit test for the model be sure that it works you will be able to use the default admin pages and do lot of playing around just do not build the entire web site yet get your command line app to work using django orm essentially you have to finesse the settings file for this app to work nicely see the settings configuration section once you have got your command line and the default admin running you can finish the web app here is the golden rule of frameworks it is code you do not have to write debug or maintain use them
|
QA
|
find out number of capture groups in python regular expressions is there way to determine how many capture groups there are in given regular expression would like to be able to do the follwing def groups regexp returns the first result of re findall or an empty default groups groups abc import re re search regexp if return groups return num of groups regexp this allows me to do stuff like first last phone groups john doe however do not know how to implement num of groups currently just work around it edit following the advice from rslite replaced re findall with re search sre parse seems like the most robust and comprehensive solution but requires tree traversal and appears to be bit heavy mizardx regular expression seems to cover all bases so am going to go with that
|
def num groups regex return re compile regex groups
|
QA
|
python swig vs ctypes in python under what circumstances is swig better choice than ctypes for calling entry points in shared libraries let us assume you do not already have the swig interface file what are the performance metrics of the two
|
ctypes is great but does not handle classes have also found ctypes is about slower than direct binding but that will highly depend on what you are calling if you are going to go with ctypes definitely check out the pyglet and pyopengl projects that have massive examples of ctype bindings
|
QA
|
python web development with or without framework am planning on porting php application over to python the application is mostly about data collection and processing the main application runs as stand alone command line application there is web interface to the application which is basically very light weight reporting interface did not use framework in the php version but being new to python am wondering if it would be advantageous to use something like django or at the very least genshi the caveat is do not want my application distribution to be overwhelmed by the framework parts would need to distribute with the application is using only the cgi import in python the best way to go in this circumstance would tend to think framework is too much overhead but perhaps am not thinking in very python way about them what suggestions do you have in this scenario
|
recently ported php app to python using web py as frameworks go it is extremely lightweight with minimal dependencies and it tends to stay out of your way so it might be the compromise you are looking for it all depends on your initial application though because with large application the advantages of having full featured framework handling the plumbing tend to outweigh the disadvantages involved in having to drag around all the framework code
|
QA
|
what is the difference between staticmethod and classmethod in python what is the difference between function decorated with staticmethod and one decorated with classmethod
|
staticmethod just disables the default function as method descriptor classmethod wraps your function in container callable that passes reference to the owning class as first argument class object pass def pass staticmethod get none function at cf classmethod get none bound method type of class main as matter of fact classmethod has runtime overhead but makes it possible to access the owning class alternatively recommend using metaclass and putting the class methods on that metaclass class cmeta type def foo cls print cls class object metaclass cmeta foo class main
|
QA
|
get last lines of file with python similar to tail am writing log file viewer for web application and for that want to paginate through the lines of the log file the items in the file are line based with the newest item on the bottom so need tail method that can read lines from the bottom and supports an offset what came up with looks like this def tail offset reads lines from with an offset of offset lines avg line length to read offset while try seek avg line length to read except ioerror woops apparently file is smaller than what we want to step back go to the beginning instead seek pos tell lines read splitlines if len lines to read or pos return lines to read offset and offset or none avg line length is this reasonable approach what is the recommended way to tail log files with offsets
|
assumes unix like system import os def tail offset stdin stdout os popen tail offset stdin close lines stdout readlines stdout close return lines offset
|
QA
|
get last lines of file with python similar to tail am writing log file viewer for web application and for that want to paginate through the lines of the log file the items in the file are line based with the newest item on the bottom so need tail method that can read lines from the bottom and supports an offset what came up with looks like this def tail offset reads lines from with an offset of offset lines avg line length to read offset while try seek avg line length to read except ioerror woops apparently file is smaller than what we want to step back go to the beginning instead seek pos tell lines read splitlines if len lines to read or pos return lines to read offset and offset or none avg line length is this reasonable approach what is the recommended way to tail log files with offsets
|
for efficiency with very large files common in logfile situations where you may want to use tail you generally want to avoid reading the whole file even if you do do it without reading the whole file into memory at once however you do need to somehow work out the offset in lines rather than characters one possibility is reading backwards with seek char by char but this is very slow instead its better to process in larger blocks have utility function wrote while ago to read files backwards that can be used here import os itertools def rblocks blocksize read file as series of blocks from end of file to start the data itself is in normal order only the order of the blocks is reversed ie hello world ld wor lo hel note that the file must be opened in binary mode if not in mode lower raise exception file must be opened using binary mode size os stat name st size fullblocks lastblock divmod size blocksize the first end of file block will be short since this leaves the rest aligned on blocksize boundary this may be more efficient than having the last first in file block be short seek lastblock yield read lastblock for in range fullblocks seek blocksize yield read blocksize def tail nlines buf result for block in rblocks buf block buf lines buf splitlines return all lines except the first since may be partial if lines result extend lines first line may not be complete if len result nlines return result nlines buf lines return buf result nlines open file to tail txt rb for line in tail print line edit added more specific version avoids need to reverse twice
|
QA
|
get last lines of file with python similar to tail am writing log file viewer for web application and for that want to paginate through the lines of the log file the items in the file are line based with the newest item on the bottom so need tail method that can read lines from the bottom and supports an offset what came up with looks like this def tail offset reads lines from with an offset of offset lines avg line length to read offset while try seek avg line length to read except ioerror woops apparently file is smaller than what we want to step back go to the beginning instead seek pos tell lines read splitlines if len lines to read or pos return lines to read offset and offset or none avg line length is this reasonable approach what is the recommended way to tail log files with offsets
|
this may be quicker than yours makes no assumptions about line length backs through the file one block at time till it is found the right number of characters def tail lines total lines wanted lines block size seek block end byte tell lines to go total lines wanted block number blocks blocks of size block size in reverse order starting from the end of the file while lines to go and block end byte if block end byte block size read the last block we have not yet read seek block number block size blocks append read block size else file too small start from begining seek only read what was not read blocks append read block end byte lines found blocks count lines to go lines found block end byte block size block number all read text join reversed blocks return join all read text splitlines total lines wanted do not like tricky assumptions about line length when as practical matter you can never know things like that generally this will locate the last lines on the first or second pass through the loop if your character thing is actually accurate you make the block size and you will tail lines almost immediately also do not burn lot of brain calories trying to finesse alignment with physical os blocks using these high level packages doubt you will see any performance consequence of trying to align on os block boundaries if you use lower level then you might see speedup
|
QA
|
style when to serialize django model instance signals vs model save method plan to serialize django model to xml when it is saved or updated the xml going to be imported into flash movie is it better to listen for post save or pre save signal and then perform the serialization or to just handle it in the model save methon
|
if it is core functionality for saving the model you will want it as part of the save method however if you already have functioning model and you want to extend it for other purposes then signals are your best bet since they allow for properly decoupled modules good example might be that you want to add event logging to your site so you simply listen for the signals that signify an event rather than modifying the original site code post save is usually best because it means the model has been successfully saved using pre save does not guarantee that the save will be successful so should not be used for anything that would depend on the save being completed
|
QA
|
python web development with or without framework am planning on porting php application over to python the application is mostly about data collection and processing the main application runs as stand alone command line application there is web interface to the application which is basically very light weight reporting interface did not use framework in the php version but being new to python am wondering if it would be advantageous to use something like django or at the very least genshi the caveat is do not want my application distribution to be overwhelmed by the framework parts would need to distribute with the application is using only the cgi import in python the best way to go in this circumstance would tend to think framework is too much overhead but perhaps am not thinking in very python way about them what suggestions do you have in this scenario
|
django makes it possible to whip out website rapidly that is for sure you do not need to be python master to use it and since it is very pythonic in it is design and there is not really any magic going on it will help you learn python along the way start with the examples check out some django screencasts from twid and you will be on your way start slow tweaking the admin and playing with it via she will is the way to start once you have handle on the orm and get how things work start building the real stuff the framework is not going to cause any performance problems like lott said it is code you do not have to maintain and that is the best kind
|
QA
|
how do use django core urlresolvers reverse with function reference instead of named url pattern in my urls py file have from myapp import views categories views categories where categories is view function inside myapp views py no other urlconf lines reference views categories in unit test file trying to grab this url using django core urlresolvers reverse instead of just copying categories dry and all that so have from django core urlresolvers import reverse from myapp import views url reverse views categories when run my tests get noreversematch error noreversematch reverse for function categories at with arguments and keyword arguments not found it matches just fine if make the url pattern named pattern like this url categories views categories myapp categories and use the pattern name to match it url reverse myapp categories but as far as can tell from the reverse documentation shouldn need to make it named url pattern just to use reverse any ideas what doing wrong
|
jack example is nearly correct it needs to be url function not tuple if you want to use named urls url no monkeys views nomonkeys no monkeys
|
QA
|
key presses in python is it possible to make it appear to system that key was pressed for example need to make key be pressed thousands of times and it is much to time consuming to do it manually would like to write something to do it for me and the only thing know well enough is python better way to put it need to emulate key press not capture key press more info as requested am running windows xp and need to send the keys to another application
|
it is probably possible but where do you want the key presses to go to another application that would probably be case of understanding your platform windowing toolkit and sending the right messages to the right window clarify your requirements and am sure we can help out
|
QA
|
python language api am starting with python coming from java was wondering if there exists something similar to javadoc api where can find the class its methods and and example of how to use it have found very helpul to use help thing from the python command line have found this also http docs python org https docs python org py modindex html but it seems to help when you already have the class name you are looking for in javadoc api have all the classes so if need something scroll down to class that sounds like what need or some times just browse all the classes to see what they do and when need feature my brain recalls me we saw something similar in the javadoc remember but do not seem to find the similar in python yet and that why am posting this questin by the way know that would eventually will read this https docs python org library but well think it is not today
|
pydoc am not sure if you are looking for something more sophisticated but it does the trick
|
QA
|
python language api am starting with python coming from java was wondering if there exists something similar to javadoc api where can find the class its methods and and example of how to use it have found very helpul to use help thing from the python command line have found this also http docs python org https docs python org py modindex html but it seems to help when you already have the class name you are looking for in javadoc api have all the classes so if need something scroll down to class that sounds like what need or some times just browse all the classes to see what they do and when need feature my brain recalls me we saw something similar in the javadoc remember but do not seem to find the similar in python yet and that why am posting this questin by the way know that would eventually will read this https docs python org library but well think it is not today
|
here is list of all the modules in python not sure if that is what you are really after
|
QA
|
key presses in python is it possible to make it appear to system that key was pressed for example need to make key be pressed thousands of times and it is much to time consuming to do it manually would like to write something to do it for me and the only thing know well enough is python better way to put it need to emulate key press not capture key press more info as requested am running windows xp and need to send the keys to another application
|
autohotkey is perfect for this kind of tasks keyboard automation remapping script to send times send that is all edit to send the keys to an specific application winactivate word send
|
QA
|
python language api am starting with python coming from java was wondering if there exists something similar to javadoc api where can find the class its methods and and example of how to use it have found very helpul to use help thing from the python command line have found this also http docs python org https docs python org py modindex html but it seems to help when you already have the class name you are looking for in javadoc api have all the classes so if need something scroll down to class that sounds like what need or some times just browse all the classes to see what they do and when need feature my brain recalls me we saw something similar in the javadoc remember but do not seem to find the similar in python yet and that why am posting this questin by the way know that would eventually will read this https docs python org library but well think it is not today
|
if you are working on windows activestate python comes with the documentation including the library reference in searchable help file
|
QA
|
key presses in python is it possible to make it appear to system that key was pressed for example need to make key be pressed thousands of times and it is much to time consuming to do it manually would like to write something to do it for me and the only thing know well enough is python better way to put it need to emulate key press not capture key press more info as requested am running windows xp and need to send the keys to another application
|
install the pywin extensions then you can do the following import win com client as comclt wsh comclt dispatch wscript she will wsh appactivate notepad select another application wsh sendkeys send the keys you want search for documentation of the wscript she will object believe installed by default in all windows xp installations you can start here perhaps edit sending import win com client as comctl wsh comctl dispatch wscript she will google chrome window title wsh appactivate icanhazip com wsh sendkeys
|
QA
|
python language api am starting with python coming from java was wondering if there exists something similar to javadoc api where can find the class its methods and and example of how to use it have found very helpul to use help thing from the python command line have found this also http docs python org https docs python org py modindex html but it seems to help when you already have the class name you are looking for in javadoc api have all the classes so if need something scroll down to class that sounds like what need or some times just browse all the classes to see what they do and when need feature my brain recalls me we saw something similar in the javadoc remember but do not seem to find the similar in python yet and that why am posting this questin by the way know that would eventually will read this https docs python org library but well think it is not today
|
the standard python library is fairly well documented try jumping into python and importing module say os and running import os help os this reads the doc strings on each of the items in the module and displays it this is exactly what pydoc will do too edit epydoc is probably exactly what you are looking for
|
QA
|
python web development with or without framework am planning on porting php application over to python the application is mostly about data collection and processing the main application runs as stand alone command line application there is web interface to the application which is basically very light weight reporting interface did not use framework in the php version but being new to python am wondering if it would be advantageous to use something like django or at the very least genshi the caveat is do not want my application distribution to be overwhelmed by the framework parts would need to distribute with the application is using only the cgi import in python the best way to go in this circumstance would tend to think framework is too much overhead but perhaps am not thinking in very python way about them what suggestions do you have in this scenario
|
you might consider using something like web py which would be easy to distribute since it is small and it would also be easy to adapt your other tools to it since it does not require you to submit to the framework so much like django does be forewarned however it is not the most loved framework in the python community but it might be just the thing for you you might also check out web py but know less about that
|
QA
|
how do you make python postgresql faster right now have log parser reading through mb of plain text files file for each day over the past years my code currently stands as this http gist github com have used psyco as seen in the code and am also compiling it and using the compiled version it is doing about lines every seconds the machine is standard macbook pro ghz gb ram is it possible for this to go faster or is that limitation on the language database
|
use bind variables instead of literal values in the sql statements and create cursor for each unique sql statement so that the statement does not need to be reparsed the next time it is used from the python db api doc prepare and execute database operation query or command parameters may be provided as sequence or mapping and will be bound to variables in the operation variables are specified in database specific notation see the module paramstyle attribute for details reference to the operation will be retained by the cursor if the same operation object is passed in again then the cursor can optimize its behavior this is most effective for algorithms where the same operation is used but different parameters are bound to it many times always always always use bind variables
|
QA
|
python language api am starting with python coming from java was wondering if there exists something similar to javadoc api where can find the class its methods and and example of how to use it have found very helpul to use help thing from the python command line have found this also http docs python org https docs python org py modindex html but it seems to help when you already have the class name you are looking for in javadoc api have all the classes so if need something scroll down to class that sounds like what need or some times just browse all the classes to see what they do and when need feature my brain recalls me we saw something similar in the javadoc remember but do not seem to find the similar in python yet and that why am posting this questin by the way know that would eventually will read this https docs python org library but well think it is not today
|
have downloaded python from python org and it does not contains pydoc directorio de python pm dir pm dir pm dir dlls pm dir doc pm dir include pm dir lib pm dir libs pm license txt pm news txt pm python exe pm pythonw exe pm readme txt pm dir tcl pm dir tools pm xpopen exe archivos bytes but it has the substitute guess pydocgui python dir tools scripts pydocgui pyw pm pydocgui pyw archivos bytes this launches webserver and shows what was looking for all the modules plus all the classes that come with the platform the doc dir contains the same as in http docs python org thanks lot for guide me to pydoc
|
QA
|
how do you make python postgresql faster right now have log parser reading through mb of plain text files file for each day over the past years my code currently stands as this http gist github com have used psyco as seen in the code and am also compiling it and using the compiled version it is doing about lines every seconds the machine is standard macbook pro ghz gb ram is it possible for this to go faster or is that limitation on the language database
|
in the for loop you are inserting into the chats table repeatedly so you only need single sql statement with bind variables to be executed with different values so you could put this before the for loop insert statement insert into chats person id message type created at channel values person id message type created at channel then in place of each sql statement you execute put this in place cursor execute insert statement person id person message type message created at some date channel this will make things run faster because the cursor object will not have to reparse the statement each time the db server will not have to generate new execution plan as it can use the one it create previously you will not have to call santitize as special characters in the bind variables will not part of the sql statement that gets executed note the bind variable syntax used is oracle specific you will have to check the psycopg library documentation for the exact syntax other optimizations you are incrementing with the update people set chatscount after each loop iteration keep dictionary mapping user to chat count and then execute the statement of the total number you have seen this will be faster then hitting the db after every record use bind variables on all your queries not just the insert statement choose that as an example change all the find functions that do db look ups to cache their results so they do not have to hit the db every time psycho optimizes python programs that perform large number of numberic operation the script is io expensive and not cpu expensive so would not expect to give you much if any optimization
|
QA
|
how do you manage your custom modules write tons of python scripts and find myself reusing lots code that have written for other projects my solution has been to make sure the code is separated into logical modules packages this one given then make them setuptools aware and publish them on pypi this allows my other scripts to always have the most up to date code get warm fuzzy feeling because am not repeating myself and my development in general is made less complicated also feel good that there may be someone out there that finds my code handy for something they are working on but it is mainly for selfish reasons to all the pythonistas how do you handle this do you use pypi or setuptools easy install or something else
|
have been doing the same thing extract common functionality pretty the code up with extra documentation and unit tests doctests create an easy install setup py and then release on pypi recently created single google code site where manage the source and keep the wiki up to date
|
QA
|
how do you make python postgresql faster right now have log parser reading through mb of plain text files file for each day over the past years my code currently stands as this http gist github com have used psyco as seen in the code and am also compiling it and using the compiled version it is doing about lines every seconds the machine is standard macbook pro ghz gb ram is it possible for this to go faster or is that limitation on the language database
|
as mark suggested use binding variables the database only has to prepare each statement once then fill in the blanks for each execution as nice side effect it will automatically take care of string quoting issues which your program is not handling turn transactions on if they are not already and do single commit at the end of the program the database will not have to write anything to disk until all the data needs to be committed and if your program encounters an error none of the rows will be committed allowing you to simply re run the program once the problem has been corrected your log hostname log person and log date functions are doing needless selects on the tables make the appropriate table attributes primary key or unique then instead of checking for the presence of the key before you insert just do the insert if the person date hostname already exists the insert will fail from the constraint violation this will not work if you use transaction with single commit as suggested above alternatively if you know you are the only one inserting into the tables while your program is running then create parallel data structures in memory and maintain them in memory while you do your inserts for example read in all the hostnames from the table into an associative array at the start of the program when want to know whether to do an insert just do an array lookup if no entry found do the insert and update the array appropriately this suggestion is compatible with transactions and single commit but requires more programming it will be wickedly faster though
|
QA
|
how do you make python postgresql faster right now have log parser reading through mb of plain text files file for each day over the past years my code currently stands as this http gist github com have used psyco as seen in the code and am also compiling it and using the compiled version it is doing about lines every seconds the machine is standard macbook pro ghz gb ram is it possible for this to go faster or is that limitation on the language database
|
additionally to the many fine suggestions mark roddy has given do the following do not use readlines you can iterate over file objects try to use executemany rather than execute try to do batch inserts rather single inserts this tends to be faster because there is less overhead it also reduces the number of commits str rstrip will work just fine instead of stripping of the newline with regex batching the inserts will use more memory temporarily but that should be fine when you do not read the whole file into memory
|
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
|
for medium complex grammars pyparsing is brilliant you can define grammars directly within python code no need for code generation from pyparsing import word alphas greet word alphas word alphas grammar defined here hello hello world print hello greet parsestring hello hello world hello world example taken from the pyparsing home page with parse actions functions that are invoked when certain grammar rule is triggered you can convert parses directly into abstract syntax trees or any other representation there are many helper functions that encapsulate recurring patterns like operator hierarchies quoted strings nesting or style comments
|
QA
|
how do you manage your custom modules write tons of python scripts and find myself reusing lots code that have written for other projects my solution has been to make sure the code is separated into logical modules packages this one given then make them setuptools aware and publish them on pypi this allows my other scripts to always have the most up to date code get warm fuzzy feeling because am not repeating myself and my development in general is made less complicated also feel good that there may be someone out there that finds my code handy for something they are working on but it is mainly for selfish reasons to all the pythonistas how do you handle this do you use pypi or setuptools easy install or something else
|
what kind of modules are we talking about here if you are planning on distributing your projects to other python developers setuptools is great but it is usually not very good way to distribute apps to end users your best bet in the latter case is to tailor your packaging to the platforms you are distributing it for sure it is pain but it makes life for end users far easier for example in my debian system usually do not use easy install because it is little bit more difficult to get eggs to work well with the package manager in os and windows you would probably want to package everything up using py app and py exe respectively this makes life for the end user better after all they should not know or care what language your scripts are written in they just need them to install
|
QA
|
how do you make python postgresql faster right now have log parser reading through mb of plain text files file for each day over the past years my code currently stands as this http gist github com have used psyco as seen in the code and am also compiling it and using the compiled version it is doing about lines every seconds the machine is standard macbook pro ghz gb ram is it possible for this to go faster or is that limitation on the language database
|
do not waste time profiling the time is always in the database operations do as few as possible just the minimum number of inserts three things one do not select over and over again to conform the date hostname and person dimensions fetch all the data once into python dictionary and use it in memory do not do repeated singleton selects use python two do not update specifically do not do this it is bad code for two reasons cursor execute update people set chats count chats count where id person id it be replaced with simple select count from never update to increment count just count the rows that are there with select statement if you cannot do this with simple select count or select count distinct you are missing some data your data model should always provide correct complete counts never update and never build sql using string substitution completely dumb if for some reason the select count is not fast enough benchmark first before doing anything lame you can cache the result of the count in another table after all of the loads do select count from whatever group by whatever and insert this into table of counts do not update ever three use bind variables always cursor execute insert into values person id time to string time channel the sql never changes the values bound in change but the sql never changes this is much faster never build sql statements dynamically never
|
QA
|
python language api am starting with python coming from java was wondering if there exists something similar to javadoc api where can find the class its methods and and example of how to use it have found very helpul to use help thing from the python command line have found this also http docs python org https docs python org py modindex html but it seems to help when you already have the class name you are looking for in javadoc api have all the classes so if need something scroll down to class that sounds like what need or some times just browse all the classes to see what they do and when need feature my brain recalls me we saw something similar in the javadoc remember but do not seem to find the similar in python yet and that why am posting this questin by the way know that would eventually will read this https docs python org library but well think it is not today
|
by the way know that would eventually will read this http docs python org lib lib html but well think it is not today suggest that you are making mistake the lib doc has the class its methods and and example of how to use it it is what you are looking for use both java and python all the time dig into the library doc you will find everything you are looking for
|
QA
|
how can perform head request with the mechanize library know how to do head request with httplib but have to use mechanize for this site essentially what need to do is grab value from the header filename without actually downloading the file any suggestions how could accomplish this
|
mechanize itself only sends gets and posts but you can easily extend the request class to send head example import mechanize class headrequest mechanize request def get method self return head request headrequest http www example com response mechanize urlopen request print response info
|
QA
|
python swig vs ctypes in python under what circumstances is swig better choice than ctypes for calling entry points in shared libraries let us assume you do not already have the swig interface file what are the performance metrics of the two
|
am going to be contrarian and suggest that if you can you should write your extension library using the standard python api it is really well integrated from both and python perspective if you have any experience with the perl api you will find it very pleasant surprise ctypes is nice too but as others have said it does not do how big is the library you are trying to wrap how quickly does the codebase change any other maintenance issues these will all probably affect the choice of the best way to write the python bindings
|
QA
|
regex to remove conditional comments want regex which can match conditional comments in html source page so can remove only those want to preserve the regular comments would also like to avoid using the notation if possible the text is foo if ie style type text css ul menu ul li font size px font weight normal padding top px style endif bar and want to remove everything in if ie and endif edit it is because of beautifulsoup want to remove these tags beautifulsoup fails to parse and gives an incomplete source edit if ie is not the only condition there are lots more and do not have any list of all possible combinations edit vinko vrsalovic solution works but the actual problem why beautifulsoup failed was because of rogue comment within the conditional comment like if lt ie script defer type text javascript src pngfix js script png fix for ie endif notice the png fix for ie comment though my problem was solve would love to get regex solution for this
|
as see it you only need to worry about downlevel hidden comments the ones that start with and you do not need to match anything beyond the word if and the space following it this should do what you want if endif endif that mess in the middle is to satisfy your desire not to use but do not really think it is worth the effort the approach should work fine if you compile the regex with the re flag set or wrap it in for example if endif
|
QA
|
what are the advantages of packaging your python library application as an egg file have read some about egg files and have noticed them in my lib directory but what are the advantages disadvantages of using then as developer
|
whatever you do do not stop distributing your application also as tarball as that is the easiest packagable format for operating systems with package sysetem
|
QA
|
get bound event handler in tkinter after bind method to an event of tkinter element is there way to get the method back root tkinter tk frame tkinter frame root width height frame bind button lambda pprint click function needed frame pack bound event method frame
|
does not appear to be why not just save it yourself if you are going to need it or use non anonymous function also your code does not work as written lambda functions can only contain expressions not statements so print is no go this will change in python when print becomes function
|
QA
|
is there something like python getattr in is there something like python getattr in would like to create window by reading list which contains the names of controls to put on the window
|
use reflection for this type getproperty and type getproperties each return propertyinfo instances which can be used to read property value on an object var result typeof datetime getproperty year getvalue dt null type getmethod and type getmethods each return methodinfo instances which can be used to execute method on an object var result typeof datetime getmethod tolongdatestring invoke dt null if you do not necessarily know the type which would be little wierd if you new the property name than you could do something like this as well var result dt gettype getproperty year invoke dt null
|
QA
|
is there something like python getattr in is there something like python getattr in would like to create window by reading list which contains the names of controls to put on the window
|
yes you can do this typeof yourobjecttype getproperty propertyname getvalue instanceobjecttogetpropfrom null
|
QA
|
is there something like python getattr in is there something like python getattr in would like to create window by reading list which contains the names of controls to put on the window
|
there is the system reflection propertyinfo class that can be created using object gettype getproperties that can be used to probe an object properties using strings similar methods exist for object methods fields etc do not think that will help you accomplish your goals though you should probably just create and manipulate the objects directly controls have name property that you can set for example
|
QA
|
is there something like python getattr in is there something like python getattr in would like to create window by reading list which contains the names of controls to put on the window
|
there is also type invokemember public static class reflectionext public static object getattr this object obj string name type type obj gettype bindingflags flags bindingflags instance bindingflags public bindingflags getproperty return type invokemember name flags type defaultbinder obj null which could be used like object value reflectionext getattr obj propertyname or as an extension method object value obj getattr propertyname
|
QA
|
what are the advantages of packaging your python library application as an egg file have read some about egg files and have noticed them in my lib directory but what are the advantages disadvantages of using then as developer
|
for simple python programs you probably do not need to use eggs distributing the raw py files should suffice it is like distributing source files for gnu linux you can also use the various os packagers like py exe or py app to create exe dmg or other files for different operating systems more complex programs django pretty much require eggs due to the various modules and dependencies required
|
QA
|
python language api am starting with python coming from java was wondering if there exists something similar to javadoc api where can find the class its methods and and example of how to use it have found very helpul to use help thing from the python command line have found this also http docs python org https docs python org py modindex html but it seems to help when you already have the class name you are looking for in javadoc api have all the classes so if need something scroll down to class that sounds like what need or some times just browse all the classes to see what they do and when need feature my brain recalls me we saw something similar in the javadoc remember but do not seem to find the similar in python yet and that why am posting this questin by the way know that would eventually will read this https docs python org library but well think it is not today
|
it does not directly answer your question so will probably be downgraded but you may be interested in jython jython is an implementation of the high level dynamic object oriented language python written in pure java and seamlessly integrated with the java platform it thus allows you to run python on any java platform since you are coming from java jython may help you leverage python while still allowing you to use your java knowledge
|
QA
|
how can search word in word docx file would like to search word file docx for text string some special phrase that could would be found from search within word is there way from python to see the text have no interest in formatting just want to classify documents as having or not having some special phrase
|
here is example of using xlinq to search throu word document
|
QA
|
python language api am starting with python coming from java was wondering if there exists something similar to javadoc api where can find the class its methods and and example of how to use it have found very helpul to use help thing from the python command line have found this also http docs python org https docs python org py modindex html but it seems to help when you already have the class name you are looking for in javadoc api have all the classes so if need something scroll down to class that sounds like what need or some times just browse all the classes to see what they do and when need feature my brain recalls me we saw something similar in the javadoc remember but do not seem to find the similar in python yet and that why am posting this questin by the way know that would eventually will read this https docs python org library but well think it is not today
|
you can set the environment variable pythondocs to point to where the python documentation is installed on my system it is in usr share doc python so you can define this variable in your she will profile or somewhere else depending on your system export pythondocs usr share doc python now if you open an interractive python console you can call the help system for exemple help exception help on class exception in module exceptions class exception baseexception common base class for all non exit exceptions method resolution order exception documentation is here https docs python org library pydoc html
|
QA
|
how can read the rgb value of given pixel in python if open an image with open image jpg how can get the rgb values of pixel if have the coordinates of the pixel then how can do the reverse of this starting with blank graphic write pixel with certain rgb value it would be so much better if did not have to download any additional libraries
|
image manipulation is complex topic and it is best if you do use library can recommend gdmodule which provides easy access to many different image formats from within python
|
QA
|
get bound event handler in tkinter after bind method to an event of tkinter element is there way to get the method back root tkinter tk frame tkinter frame root width height frame bind button lambda pprint click function needed frame pack bound event method frame
|
the associated call to do that for the tk api would be get getcommandinfo which places information about the command in the tcl cmdinfo structure pointed to by infoptr however this function is not used anywhere in tkinter which is the binding for tk used by python trough tkinter py therefore it is impossible to get the bound function out of tkinter you need to remember that function yourself
|
QA
|
how can read the rgb value of given pixel in python if open an image with open image jpg how can get the rgb values of pixel if have the coordinates of the pixel then how can do the reverse of this starting with blank graphic write pixel with certain rgb value it would be so much better if did not have to download any additional libraries
|
it is probably best to use the python image library to do this which am afraid is separate download the easiest way to do what you want is via the load method on the image object which returns pixel access object which you can manipulate like an array from pil import image am image open dead parrot jpg can be many different formats pix am load print am size get the width and hight of the image for iterating over print pix get the rgba value of the pixel of an image pix value set the rgba value of the image tuple alternatively look at imagedraw which gives much richer api for creating images
|
QA
|
how can read the rgb value of given pixel in python if open an image with open image jpg how can get the rgb values of pixel if have the coordinates of the pixel then how can do the reverse of this starting with blank graphic write pixel with certain rgb value it would be so much better if did not have to download any additional libraries
|
there is really good article on wiki wxpython org entitled working with images the article mentions the possiblity of using wxwidgets wximage pil or pythonmagick personally have used pil and wxwidgets and both make image manipulation fairly easy
|
QA
|
python language api am starting with python coming from java was wondering if there exists something similar to javadoc api where can find the class its methods and and example of how to use it have found very helpul to use help thing from the python command line have found this also http docs python org https docs python org py modindex html but it seems to help when you already have the class name you are looking for in javadoc api have all the classes so if need something scroll down to class that sounds like what need or some times just browse all the classes to see what they do and when need feature my brain recalls me we saw something similar in the javadoc remember but do not seem to find the similar in python yet and that why am posting this questin by the way know that would eventually will read this https docs python org library but well think it is not today
|
also try pydoc then type in web browser http localhost edit of course you can use any other value for port number instead of
|
QA
|
dynamic radio button creation in wxpython if create list of radio buttons and place the list initially is it possible to change the contents in that list later for example have panel that uses boxsizer to place the widgets initially one of those widgets is list of radio buttons have also tried normal radiobox would like to dynamically change the list based on variables from another class however once the list is placed in the sizer it is effectively locked cannot just modify the list and have the changes appear if try re adding the list to the sizer it just gets put in the top left corner of the panel am sure could hide the original list and manually place the new list in the same position but that feels like kludge am sure am making this harder than it is am probably using the wrong widgets for this much less the wrong approach but am building this as learning experience class job wiz wizardpagesimple character job class def init self parent title attribs wiz wizardpagesimple init self parent self next self prev none self sizer makepagetitle self title self charattribs attribs create widgets self job list aircraft mechanic vehicle mechanic electronics specialist box title wx staticbox self box wx staticboxsizer box title wx vertical grid wx boxsizer wx vertical for item in self job list radio wx radiobutton self item grid add radio debugging self btn wx button self click self bind wx evt button self eligiblejob self btn place widgets self sizer add self job intro self sizer add self btn box add grid self sizer add box def eligiblejob self event determine which jobs character is eligible for if self charattribs intelligence skilllist analyst interrogator fire specialist aircraft pilot for skill in skilllist self job list append skill print self job list debugging return self job list
|
two possible solutions rebuild the sizer with the radio widgets each time you have to make change hold the radio button widgets in list and call setlabel each time you have to change their labels
|
QA
|
does anyone have experience creating shared library in matlab researcher has created small simulation in matlab and we want to make it accessible to others my plan is to take the simulation clean up few things and turn it into set of functions then plan to compile it into library and use swig to create python wrapper at that point should be able to call the simulation from small django app at least hope so do have the right plan has anyone else done something similar can you let me know if there are some serious pitfalls am not aware of at the moment
|
would also try ctypes first use the matlab compiler to compile the code into compile the code into dll use ctypes to load and call code from this dll the hardest step is probably but if you already know matlab and have used the matlab compiler you should not have serious problems with it
|
QA
|
is it feasible to compile python to machine code how feasible would it be to compile python possibly via an intermediate representation into machine code presumably it would need to link to python runtime library and any parts of the python standard library which were python themselves would need to be compiled and linked in too also you would need to bundle the python interpreter if you wanted to do dynamic evaluation of expressions but perhaps subset of python that did not allow this would still be useful would it provide any speed and or memory usage advantages presumably the startup time of the python interpreter would be eliminated although shared libraries would still need loading at startup
|
this might seem reasonable at first glance however there are lot of ordinary things in python that are not directly mappable to to representation without carrying over lot of the python runtime support for example duck typing comes to mind many functions in python that read input can take file or file like object as long as it supports certain operations eg read or readline if you think about what it would take to map this type of support to you begin to imagine exactly the sorts of things that the python runtime system already does there are utilities such as py exe that will bundle python program and runtime into single executable as far as possible
|
QA
|
pure python xslt library is there an xslt library that is pure python installing libxml libxslt or any similar libraries is problem on some of the platforms need to support really only need basic xslt support and speed is not major issue
|
have you looked at suite
|
QA
|
is it feasible to compile python to machine code how feasible would it be to compile python possibly via an intermediate representation into machine code presumably it would need to link to python runtime library and any parts of the python standard library which were python themselves would need to be compiled and linked in too also you would need to bundle the python interpreter if you wanted to do dynamic evaluation of expressions but perhaps subset of python that did not allow this would still be useful would it provide any speed and or memory usage advantages presumably the startup time of the python interpreter would be eliminated although shared libraries would still need loading at startup
|
psyco is kind of just in time jit compiler dynamic compiler for python runs code times faster but it needs much memory in short it run your existing python software much faster with no change in your source but it does not compile to object code the same way compiler would
|
QA
|
is it feasible to compile python to machine code how feasible would it be to compile python possibly via an intermediate representation into machine code presumably it would need to link to python runtime library and any parts of the python standard library which were python themselves would need to be compiled and linked in too also you would need to bundle the python interpreter if you wanted to do dynamic evaluation of expressions but perhaps subset of python that did not allow this would still be useful would it provide any speed and or memory usage advantages presumably the startup time of the python interpreter would be eliminated although shared libraries would still need loading at startup
|
try shedskin python to compiler but it is far from perfect also there is psyco python jit if only speedup is needed but imho this is not worth the effort for speed critical parts of code best solution would be to write them as extensions
|
QA
|
is it feasible to compile python to machine code how feasible would it be to compile python possibly via an intermediate representation into machine code presumably it would need to link to python runtime library and any parts of the python standard library which were python themselves would need to be compiled and linked in too also you would need to bundle the python interpreter if you wanted to do dynamic evaluation of expressions but perhaps subset of python that did not allow this would still be useful would it provide any speed and or memory usage advantages presumably the startup time of the python interpreter would be eliminated although shared libraries would still need loading at startup
|
jython has compiler targeting jvm bytecode the bytecode is fully dynamic just like the python language itself very cool yes as greg hewgill answer alludes the bytecode does use the jython runtime and so the jython jar file must be distributed with your app
|
QA
|
is it feasible to compile python to machine code how feasible would it be to compile python possibly via an intermediate representation into machine code presumably it would need to link to python runtime library and any parts of the python standard library which were python themselves would need to be compiled and linked in too also you would need to bundle the python interpreter if you wanted to do dynamic evaluation of expressions but perhaps subset of python that did not allow this would still be useful would it provide any speed and or memory usage advantages presumably the startup time of the python interpreter would be eliminated although shared libraries would still need loading at startup
|
pypy is project to reimplement python in python using compilation to native code as one of the implementation strategies others being vm with jit using jvm etc their compiled versions run slower than cpython on average but much faster for some programs shedskin is an experimental python to compiler pyrex is language specially designed for writing python extension modules it is designed to bridge the gap between the nice high level easy to use world of python and the messy low level world of
|
QA
|
is it feasible to compile python to machine code how feasible would it be to compile python possibly via an intermediate representation into machine code presumably it would need to link to python runtime library and any parts of the python standard library which were python themselves would need to be compiled and linked in too also you would need to bundle the python interpreter if you wanted to do dynamic evaluation of expressions but perhaps subset of python that did not allow this would still be useful would it provide any speed and or memory usage advantages presumably the startup time of the python interpreter would be eliminated although shared libraries would still need loading at startup
|
as greg hewgill says it there are good reasons why this is not always possible however certain kinds of code like very algorithmic code can be turned into real machine code there are several options use psyco which emits machine code dynamically you should choose carefully which methods functions to convert though use cython which is python like language that is compiled into python extension use pypy which has translator from rpython restricted subset of python that does not support some of the most dynamic features of python to or llvm pypy is still highly experimental not all extensions will be present after that you can use one of the existing packages freeze py exe pyinstaller to put everything into one binary all in all there is no general answer for your question if you have python code that is performance critical try to use as much builtin functionality as possible or ask how do make my python code faster question if that does not help try to identify the code and port it to or cython and use the extension
|
QA
|
is it feasible to compile python to machine code how feasible would it be to compile python possibly via an intermediate representation into machine code presumably it would need to link to python runtime library and any parts of the python standard library which were python themselves would need to be compiled and linked in too also you would need to bundle the python interpreter if you wanted to do dynamic evaluation of expressions but perhaps subset of python that did not allow this would still be useful would it provide any speed and or memory usage advantages presumably the startup time of the python interpreter would be eliminated although shared libraries would still need loading at startup
|
pyrex is subset of the python language that compiles to done by the guy that first built list comprehensions for python it was mainly developed for building wrappers but can be used in more general context cython is more actively maintained fork of pyrex
|
QA
|
running subversion under apache and mod python my apache server runs on some non default not root account when it tries to run python script which in turn executes subversion check out command svn checkout fails with the following error message svn cannot open file root subversion servers permission denied at the same time running that python script with subversion checkout command inside from command line under the same user account goes on perfectly well apache server with mod python runs on fedora core machine can anybody help me out thanks lot
|
the permission denied error is showing that the script is running with root credentials because it is looking in root home dir for files suggest you change the hook script to something that does id tmp id so that you can check the results of that to make sure what the uid gid and euid egid are you will probably find it is not actually running as the user you think it is my first guess like troels was also selinux but that would only be my guess if you are absolutely sure the script through apache is running with exactly the same user group as your manual test
|
QA
|
can regex be used for this particular string manipulation need to replace character say with character say in string but only if it is contained in quoted substring an example makes it clearer axbx cxdxe fxgh ixj axbx cpdpe fxgh ipj let us assume for the sake of simplicity that quotes always come in pairs the obvious way is to just process the string one character at time simple state machine approach however am wondering if regular expressions can be used to do all the processing in one go my target language is but guess my question pertains to any language having builtin or library support for regular expressions
|
not with plain regexp regular expressions have no memory so they cannot distinguish between being inside or outside quotes you need something more powerful for example using gema it would be straighforward repl repl
|
QA
|
can regex be used for this particular string manipulation need to replace character say with character say in string but only if it is contained in quoted substring an example makes it clearer axbx cxdxe fxgh ixj axbx cpdpe fxgh ipj let us assume for the sake of simplicity that quotes always come in pairs the obvious way is to just process the string one character at time simple state machine approach however am wondering if regular expressions can be used to do all the processing in one go my target language is but guess my question pertains to any language having builtin or library support for regular expressions
|
sorry to break your hopes but you need push down automata to do that there is more info here pushdown automaton in short regular expressions which are finite state machines can only read and has no memory while pushdown automaton has stack and manipulating capabilities edit spelling
|
QA
|
is it feasible to compile python to machine code how feasible would it be to compile python possibly via an intermediate representation into machine code presumably it would need to link to python runtime library and any parts of the python standard library which were python themselves would need to be compiled and linked in too also you would need to bundle the python interpreter if you wanted to do dynamic evaluation of expressions but perhaps subset of python that did not allow this would still be useful would it provide any speed and or memory usage advantages presumably the startup time of the python interpreter would be eliminated although shared libraries would still need loading at startup
|
the answer is yes it is possible you could take python code and attempt to compile it into the equivalent code using the cpython api in fact there used to be python project that did just that but have not heard about it in many years back in the python days is when last saw it you could attempt to translate the python code into native as much as possible and fall back to the cpython api when you need actual python features have been toying with that idea myself the last month or two it is however an awful lot of work and an enormous amount of python features are very hard to translate into nested functions generators anything but simple classes with simple methods anything involving modifying module globals from outside the module etc etc
|
QA
|
can regex be used for this particular string manipulation need to replace character say with character say in string but only if it is contained in quoted substring an example makes it clearer axbx cxdxe fxgh ixj axbx cpdpe fxgh ipj let us assume for the sake of simplicity that quotes always come in pairs the obvious way is to just process the string one character at time simple state machine approach however am wondering if regular expressions can be used to do all the processing in one go my target language is but guess my question pertains to any language having builtin or library support for regular expressions
|
was able to do this with python import re re sub axbx cxdxe fxgh ixj axbx cpdpe fxgh ipj what this does is use the non capturing match to check that the character is within quoted string it looks for some nonquote characters up to the next quote then looks for sequence of either single characters or quoted groups of characters until the end of the string this relies on your assumption that the quotes are always balanced this is also not very efficient
|
QA
|
can regex be used for this particular string manipulation need to replace character say with character say in string but only if it is contained in quoted substring an example makes it clearer axbx cxdxe fxgh ixj axbx cpdpe fxgh ipj let us assume for the sake of simplicity that quotes always come in pairs the obvious way is to just process the string one character at time simple state machine approach however am wondering if regular expressions can be used to do all the processing in one go my target language is but guess my question pertains to any language having builtin or library support for regular expressions
|
similar discussion about balanced text replaces http stackoverflow com questions can regular expressions be used to match nested patterns although you can try this in vim but it works well only if the string is on one line and there is only one pair of gci if there is one more pair or even an unbalanced then it could fail that is way included the confirm flag on the ex command the same can be done with sed without the interaction or with awk so you can add some interaction one possible solution is to break the lines on pairs of then you can do with vim solution
|
QA
|
which is more preferable to use in python lambda functions or nested functions def mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior here are some trivial examples where they functionally do the same thing if either were found within another function lambda function lambda nested function def return is there advantages to using one over the other performance readability limitations consistency etc does it even matter if does not then does that violate the pythonic principle there should be one and preferably only one obvious way to do it
|
practically speaking to me there are two differences the first is about what they do and what they return def is keyword that does not return anything and creates name in the local namespace lambda is keyword that returns function object and does not create name in the local namespace hence if you need to call function that takes function object the only way to do that in one line of python code is with lambda there is no equivalent with def in some frameworks this is actually quite common for example use twisted lot and so doing something like addcallback lambda result setattr self somevariable result is quite common and more concise with lambdas the second difference is about what the actual function is allowed to do function defined with def can contain any python code function defined with lambda has to evaluate to an expression and can thus not contain statements like print import raise for example def print works as expected while lambda print is syntaxerror of course there are workarounds substitute print with sys stdout write or import with import but usually you are better off going with function in that case
|
QA
|
opengl user interface programming am developing graphical application to present data not game but real workhorse app it needs to be cross platform so have chosen python opengl need blending textures etc pyopengl wx pywx windowing dialogs etc the last component wx raises the question can put together very nice looking app the prototypes look slick but when need to interact with the user to ask questions get input have to use wx it makes the app look inconsistent to have traditional ui with traditional dialogs and combos and text entry on top of full screen app with blending smooth motion textures etc has anyone developed gui using opengl and python can you share with me the toolkits and or tricks you used need combos text entry buttons radios option buttons tree view there are some toolkits out there but they are either incomplete or old and unmaintained great example is pyui http pyui sourceforge net looks slick but untouched for years
|
in the latest releases of qt you can draw widgets into your opengl context if you really would like to do something like that otherwise there is cegui that is used in some game engines implementing gui widgets yourself unless you want to edify yourself is waste of your time unless you would be satisfied with the most rudimentary of looks and functionality
|
QA
|
what is the best way to upgrade from django to should try to actually upgrade my existing app or just rewrite it mostly from scratch saving what pieces templates etc can
|
only simplest sites are easy to upgrade expect real pain if your site happen to be for non ascii part of the world read anywhere outside usa and uk the most painful change in django was switching from bytestrings to unicode objects internally now you have to find all places where you use bytestrings and change this to unicode worst case is the template rendering you will never know you forgot to change one variable until you get unicodeerror other notable thing manipulators oldforms have gone and you have no other way than to rewrite all parts with forms newforms if this is your case and your project is larger than apps would be rather reluctant to upgrade until really necessary
|
QA
|
vim extension via python is it possible to extend vim functionality via custom extension preferably written in python what need ideally is custom command when in command mode esc do this do that
|
vim supports scripting in python and in perl as well think you just have to make sure that the vim distribution you are using has been compiled with python support if you are using linux system you can download the source and then compile it with configure enable pythoninterp make sudo make install inside vim you can type version to list the available features if it has python support you should see python somewhere python otherwise then to check the usage of the python module you can type help python if you are going to compile the vim sources make sure to check the available configure options you might need to specify with python config dir as well to create custom command in command mode if understand correctly what you mean you can create function myfunction in vim script using python or the vim scripting language and then invoke it with call myfunction check help user functions for details
|
QA
|
vim extension via python is it possible to extend vim functionality via custom extension preferably written in python what need ideally is custom command when in command mode esc do this do that
|
yes it is there are several extensions on http www vim org scripts index php it can be done with python as well if the support for python is compiled in article about it http www techrepublic com article extending vim with python google is our friend hth
|
QA
|
can regex be used for this particular string manipulation need to replace character say with character say in string but only if it is contained in quoted substring an example makes it clearer axbx cxdxe fxgh ixj axbx cpdpe fxgh ipj let us assume for the sake of simplicity that quotes always come in pairs the obvious way is to just process the string one character at time simple state machine approach however am wondering if regular expressions can be used to do all the processing in one go my target language is but guess my question pertains to any language having builtin or library support for regular expressions
|
converted greg hewgill python code to and it worked test public void replacetextinquotes assert areequal axbx cpdpe fxgh ipj regex replace axbx cxdxe fxgh ixj that test passed
|
QA
|
can parallel traversals be done in matlab just as in python using the zip function python allows for loops to traverse multiple sequences in parallel for in zip list list does matlab have an equivalent syntax if not what is the best way to iterate over two parallel arrays at the same time using matlab
|
for loops in matlab used to be slow but this is not true anymore so vectorizing is not always the miracle solution just use the profiler and tic and toc functions to help you identify possible bottlenecks
|
QA
|
python web development with or without framework am planning on porting php application over to python the application is mostly about data collection and processing the main application runs as stand alone command line application there is web interface to the application which is basically very light weight reporting interface did not use framework in the php version but being new to python am wondering if it would be advantageous to use something like django or at the very least genshi the caveat is do not want my application distribution to be overwhelmed by the framework parts would need to distribute with the application is using only the cgi import in python the best way to go in this circumstance would tend to think framework is too much overhead but perhaps am not thinking in very python way about them what suggestions do you have in this scenario
|
go for framework basic stuffs like session handling are nightmare if you do not use one because python is not web specialized like php if you think django is too much you can try lighter one like the very small but still handy web py
|
QA
|
request uac elevation from within python script want my python script to copy files on vista when run it from normal cmd exe window no errors are generated yet the files are not copied if run cmd exe as administator and then run my script it works fine this makes sense since user account control uac normally prevents many file system actions is there way can from within python script invoke uac elevation request those dialogs that say something like such and such app needs admin access is this ok if that is not possible is there way my script can at least detect that it is not elevated so it can fail gracefully
|
if your script always requires an administrator privileges then runas user administrator python your script py
|
QA
|
dynamic radio button creation in wxpython if create list of radio buttons and place the list initially is it possible to change the contents in that list later for example have panel that uses boxsizer to place the widgets initially one of those widgets is list of radio buttons have also tried normal radiobox would like to dynamically change the list based on variables from another class however once the list is placed in the sizer it is effectively locked cannot just modify the list and have the changes appear if try re adding the list to the sizer it just gets put in the top left corner of the panel am sure could hide the original list and manually place the new list in the same position but that feels like kludge am sure am making this harder than it is am probably using the wrong widgets for this much less the wrong approach but am building this as learning experience class job wiz wizardpagesimple character job class def init self parent title attribs wiz wizardpagesimple init self parent self next self prev none self sizer makepagetitle self title self charattribs attribs create widgets self job list aircraft mechanic vehicle mechanic electronics specialist box title wx staticbox self box wx staticboxsizer box title wx vertical grid wx boxsizer wx vertical for item in self job list radio wx radiobutton self item grid add radio debugging self btn wx button self click self bind wx evt button self eligiblejob self btn place widgets self sizer add self job intro self sizer add self btn box add grid self sizer add box def eligiblejob self event determine which jobs character is eligible for if self charattribs intelligence skilllist analyst interrogator fire specialist aircraft pilot for skill in skilllist self job list append skill print self job list debugging return self job list
|
to make new list elements appear in correct places you have to re layout the grid after adding new elements to it for example to add few new items you could call def addnewskills self newskilllist newskilllist is list of skill names you want to add for skillname in newskilllist newradiobutton wx radiobutton self skillname self grid add newradiobutton appears in top left corner of the panel self layout all newly added radio buttons appear where they should be self fit if you need to resize the panel to fit new items this will help where self grid is the sizer you keep all your radio buttons on
|
QA
|
wxpython how do examine dragged data in ondragover am bit perplexed by drag and drop in wxpython but perhaps this questions pertains to drag and drop in other gui frameworks as well the frameworks provides couple of callbacks onenter and ondragover that purportedly allow me to inform the system whether the current mouse position is valid place to drop whatever it is that is being dragged from these methods can return wx dragnone wx dragcopy etc what baffles me is that from within these methods am not allowed to call getdata which means am not allowed to examine the data that the user is dragging if cannot see the data how am supposed to know whether it is ok for the user to drop here
|
there is no way to see dragged data in onenter and ondragover methods the only solution found is to store the dragged item in some instance variable that is then readable inside these methods
|
QA
|
pyqt qscrollbar dear stacktoverflow can you show me an example of how to use qscrollbar thanks
|
it will come down to you using the qscrollarea it is widget that implements showing something that is larger than the available space you will not need to use qscrollbar directly do not have pyqt example but there is example in the qt distribution it is called the image viewer the object hierarchy will still be the same
|
QA
|
how can read the rgb value of given pixel in python if open an image with open image jpg how can get the rgb values of pixel if have the coordinates of the pixel then how can do the reverse of this starting with blank graphic write pixel with certain rgb value it would be so much better if did not have to download any additional libraries
|
pypng lightweight png decoder encoder although the question hints at jpg hope my answer will be useful to some people here is how to read and write png pixels using pypng module import png array point coordinates of pixel to be painted red reader png reader filename image png pixels metadata reader read flat pixel byte width if metadata alpha else pixel position point point new pixel value if metadata alpha else pixels pixel position pixel byte width pixel position pixel byte width array array new pixel value output open image with red dot png wb writer png writer metadata writer write array output pixels output close pypng is single pure python module less than lines long including tests and comments pil is more comprehensive imaging library but it is also significantly heavier
|
QA
|
pyqt qscrollbar dear stacktoverflow can you show me an example of how to use qscrollbar thanks
|
in the pyqt source code distribution look at the file examples widgets sliders pyw or there is minimal example here guess should not copy paste because of potential copyright issues
|
QA
|
pyqt qscrollbar dear stacktoverflow can you show me an example of how to use qscrollbar thanks
|
import sys from pyqt import qtcore qtgui app qtgui qapplication sys argv sb qtgui qscrollbar sb setminimum sb setmaximum def on slider moved value print new slider position value sb connect sb qtcore signal slidermoved int on slider moved sb show app exec now when you move the slider you might have to resize the window you will see the slider position printed to the terminal as you the handle
|
QA
|
how do test django database schema want to write tests that can show whether or not the database is in sync with my models py file actually have already written them only to find out that django creates new database each time the tests are run based on the models py file is there any way can make the models py test use the existing database schema the one that is in mysql postgresql and not the one that is in myapp models py do not care about the data that is in the database only care about it is schema want my tests to notice if table in the database has less fields than the schema in my models py file am using the unittest framework actually the django extension to it if this has any relevance thanks
|
what we did was override the default test runner so that it would not create new database to test against this way it runs the test against whatever our current local database looks like but be very careful if you use this method because any changes to data you make in your tests will be permanent made sure that all our tests restores any changes back to their original state and keep our pristine version of our database on the server and backed up so to do this you need to copy the run test method from django test simple to location in your project put mine in myproject test test runner py then make the following changes to that method change old name settings database name from django db import connection connection creation create test db verbosity autoclobber not interactive result unittest texttestrunner verbosity verbosity run suite connection creation destroy test db old name verbosity to result unittest texttestrunner verbosity verbosity run suite make sure to do all the necessary imports at the top and then in your settings file set the setting test runner myproject test test runner run tests now when you run manage py test django will run the tests against the current state of your database rather than creating new version based on your current model definitions another thing you can do is create copy of your database locally and then do check in your new run test method like this if settings database name my test db sys exit you cannot run tests using the database please switch database name to my test db in settings py settings database name that way there is no danger of running tests against your main database
|
QA
|
listing all functions in python module have python module installed on my system and would like to be able to see what functions classes methods are available in it want to call the doc function on each one in ruby can do something like classname methods to get list of all the methods available on that class is there something similar in python eg something like from somemodule import foo print foo methods or whatever is the correct method to call
|
you can use dir module to see all available methods attributes also check out pydocs
|
QA
|
listing all functions in python module have python module installed on my system and would like to be able to see what functions classes methods are available in it want to call the doc function on each one in ruby can do something like classname methods to get list of all the methods available on that class is there something similar in python eg something like from somemodule import foo print foo methods or whatever is the correct method to call
|
the inspect module also see the pydoc module the help function in the interactive interpreter and the pydoc command line tool which generates the documentation you are after you can just give them the class you wish to see the documentation of they can also generate for instance html output and write it to disk
|
QA
|
listing all functions in python module have python module installed on my system and would like to be able to see what functions classes methods are available in it want to call the doc function on each one in ruby can do something like classname methods to get list of all the methods available on that class is there something similar in python eg something like from somemodule import foo print foo methods or whatever is the correct method to call
|
import types import yourmodule print yourmodule dict get for in dir yourmodule if isinstance yourmodule dict get types functiontype
|
QA
|
how many bytes per element are there in python list tuple for example how much memory is required to store list of one million bit integers alist range or list range in python
|
addressing tuple part of the question declaration of cpython pytuple in typical build configuration boils down to this struct pytuple size refcount tuple reference count typeobject type tuple type object size items number of items in tuple pyobject items contains space for items elements size of pytuple instance is fixed during it is construction and cannot be changed afterwards the number of bytes occupied by pytuple can be calculated as sizeof size sizeof void items this gives shallow size of tuple to get full size you also need to add total number of bytes consumed by object graph rooted in pytuple items array it is worth noting that tuple construction routines make sure that only single instance of empty tuple is ever created singleton references python object tupleobject tupleobject
|
QA
|
can regex be used for this particular string manipulation need to replace character say with character say in string but only if it is contained in quoted substring an example makes it clearer axbx cxdxe fxgh ixj axbx cpdpe fxgh ipj let us assume for the sake of simplicity that quotes always come in pairs the obvious way is to just process the string one character at time simple state machine approach however am wondering if regular expressions can be used to do all the processing in one go my target language is but guess my question pertains to any language having builtin or library support for regular expressions
|
pattern replacement anchor each match at the end of the previous one or the start of the string if it is at the beginning of the string match up to the first quote match any block of unquoted characters or any non quote characters up to an one sweep trough the source string except for single character look behind
|
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 allows you to use round parenthesis and eventually pass some parameters just like functions every time you define function python creates callable object in example you could define the function func in these ways it is the same class object def call self args print hello func or def func args print hello you could use this method instead of methods like doit or run think it is just more clear to see obj than obj doit
|
QA
|
user authentication in pylons authkit am trying to create web application using pylons and the resources on the web point to the pylonsbook page which is not of much help want authentication and authorisation and is there anyway to setup authkit to work easily with pylons tried downloading the simplesitetemplate from the cheeseshop but was not able to run the setup app command it throws up an error file home cnu env lib python site packages sqlalchemy py egg sqlalchemy schema py line in call table metadata tables key attributeerror module object has no attribute tables use pylons rc sqlalchemy authkit
|
ok another update on the subject it seems that the cheeseshop template is broken have followed the chapter you linked in the post and it seems that authkit is working fine there are some caveats sqlalchemy has to be in version authkit has to be the dev version from svn easy install authkit dev managed to get it working fine
|
QA
|
can regex be used for this particular string manipulation need to replace character say with character say in string but only if it is contained in quoted substring an example makes it clearer axbx cxdxe fxgh ixj axbx cpdpe fxgh ipj let us assume for the sake of simplicity that quotes always come in pairs the obvious way is to just process the string one character at time simple state machine approach however am wondering if regular expressions can be used to do all the processing in one go my target language is but guess my question pertains to any language having builtin or library support for regular expressions
|
the trick is to use non capturing group to match the part of the string following the match character we are searching for trying to match the string up to will only find either the first or the last occurence depending whether non greedy quantifiers are used here is greg idea transposed to tcl with comments set strin axbx cxdxe fxgh ixj set regex enable expanded syntax allows comments ignores whitespace the actual match non matching group match to end of current quoted substring assuming quotes are in pairs make sure we actually were inside quoted substring by making sure the rest of the string is what we expect it to be match any non quoted substring or any quoted substring including the quotes any number of times until we run out of string end of non matching group the same regular expression without the comments set regexcondensed set replregex set nmatches regsub all regex strin replregex strout puts nmatches replacements if nmatches puts original strin puts result strout exit this prints replacements original axbx cxdxe fxgh ixj result axbx cpdpe fxgh ipj
|
QA
|
why results of map and list comprehension are different the following test fails usr bin env python def args map lambda lambda lambda for in lambda for in alist for in args print alist if name main import doctest doctest testmod in other words args for in args append lambda map lambda args args for in args append lambda lambda map lambda args args for in args append lambda map lambda args
|
the lambda captures variables not values hence the code lambda will always return the value is currently bound to in the closure by the time it gets called this value has been set to to get what you want you will need to capture the actual binding at the time the lambda is created by lambda for in lambda for in
|
QA
|
why results of map and list comprehension are different the following test fails usr bin env python def args map lambda lambda lambda for in lambda for in alist for in args print alist if name main import doctest doctest testmod in other words args for in args append lambda map lambda args args for in args append lambda lambda map lambda args args for in args append lambda map lambda args
|
they are different because the value of in both the generator expression and the list comp are evaluated lazily when the anonymous functions are invoked in by that time is bound to the last value if which is so basically this is what the list comprehension does likewise for the genexp from append lambda from append lambda now the lambdas carry around closure that references but is bound to in both cases because that is the last value it was assigned to if you want to make sure that the lambda receives the current value of do lambda you you for in this way you force the evaluation of at the time the closure is created edit there is one difference between generator expressions and list comprehensions the latter leak the loop variable into the surrounding scope
|
QA
|
writing domain specific language for selecting rows from table am writing server that expect to be run by many different people not all of whom will have direct contact with the servers will communicate with each other in cluster part of the server functionality involves selecting small subset of rows from potentially very large table the exact choice of what rows are selected will need some tuning and it is important that it is possible for the person running the cluster eg myself to update the selection criteria without getting each and every server administrator to deploy new version of the server simply writing the function in python is not really an option since nobody is going to want to install server that downloads and executes arbitrary python code at runtime what need are suggestions on the simplest way to implement domain specific language to achieve this goal the language needs to be capable of simple expression evaluation as well as querying table indexes and iterating through the returned rows ease of writing and reading the language is secondary to ease of implementing it would also prefer not to have to write an entire query optimiser so something that explicitly specifies what indexes to query would be ideal the interface that this will have to compile against will be similar in capabilities to what the app engine datastore exports you can query for sequential ranges on any index on the table eg less than greater than range and equality queries then filter the returned row by any boolean expression you can also concatenate multiple independent result sets together realise this question sounds lot like am asking for sql however do not want to require that the datastore backing this data be relational database and do not want the overhead of trying to reimplement sql myself am also dealing with only single table with known schema finally no joins will be required something much simpler would be far preferable edit expanded description to clear up some misconceptions
|
why not create language that when it compiles it generates sql or whatever query language your datastore requires you would be basically creating an abstraction over your persistence layer
|
QA
|
writing domain specific language for selecting rows from table am writing server that expect to be run by many different people not all of whom will have direct contact with the servers will communicate with each other in cluster part of the server functionality involves selecting small subset of rows from potentially very large table the exact choice of what rows are selected will need some tuning and it is important that it is possible for the person running the cluster eg myself to update the selection criteria without getting each and every server administrator to deploy new version of the server simply writing the function in python is not really an option since nobody is going to want to install server that downloads and executes arbitrary python code at runtime what need are suggestions on the simplest way to implement domain specific language to achieve this goal the language needs to be capable of simple expression evaluation as well as querying table indexes and iterating through the returned rows ease of writing and reading the language is secondary to ease of implementing it would also prefer not to have to write an entire query optimiser so something that explicitly specifies what indexes to query would be ideal the interface that this will have to compile against will be similar in capabilities to what the app engine datastore exports you can query for sequential ranges on any index on the table eg less than greater than range and equality queries then filter the returned row by any boolean expression you can also concatenate multiple independent result sets together realise this question sounds lot like am asking for sql however do not want to require that the datastore backing this data be relational database and do not want the overhead of trying to reimplement sql myself am also dealing with only single table with known schema finally no joins will be required something much simpler would be far preferable edit expanded description to clear up some misconceptions
|
you mentioned python why not use python if someone can type in an expression in your dsl they can type in python you will need some rules on structure of the expression but that is lot easier than implementing something new
|
QA
|
listing all functions in python module have python module installed on my system and would like to be able to see what functions classes methods are available in it want to call the doc function on each one in ruby can do something like classname methods to get list of all the methods available on that class is there something similar in python eg something like from somemodule import foo print foo methods or whatever is the correct method to call
|
once you have imported the module you can just do help modulename to get the docs on all the functions at once interactively or you can use dir modulename to simply list the names of all the functions and variables defined in the module
|
QA
|
regular expressions but for writing in the match when using regular expressions we generally if not always use them to extract some kind of information what need is to replace the match value with some other value right now am doing this def getexpandedtext pattern text replacevalue one liner really ugly but it is only used in here return text replace text text find re findall pattern text replacevalue text text find re findall pattern text len replacevalue so if do sth like getexpandedtext aaa bbb hola aaaiiibbb como estas ooo hola aaaooobbb como estas it changes the with ooo do you guys know whether with python regular expressions we can do this thanks lot guys
|
of course see the sub and subn methods of compiled regular expressions or the are sub and are subn functions you can either make it replace the matches with string argument you give or you can pass callable such as function which will be called to supply the replacement see https docs python org library re html
|
QA
|
regular expressions but for writing in the match when using regular expressions we generally if not always use them to extract some kind of information what need is to replace the match value with some other value right now am doing this def getexpandedtext pattern text replacevalue one liner really ugly but it is only used in here return text replace text text find re findall pattern text replacevalue text text find re findall pattern text len replacevalue so if do sth like getexpandedtext aaa bbb hola aaaiiibbb como estas ooo hola aaaooobbb como estas it changes the with ooo do you guys know whether with python regular expressions we can do this thanks lot guys
|
sub replacement string count sub returns the string obtained by replacing the leftmost non overlapping occurrences of the re in string by the replacement replacement if the pattern is not found string is returned unchanged re compile blue white red sub colour blue socks and red shoes colour socks and colour shoes sub colour blue socks and red shoes count colour socks and red shoes
|
QA
|
regular expressions but for writing in the match when using regular expressions we generally if not always use them to extract some kind of information what need is to replace the match value with some other value right now am doing this def getexpandedtext pattern text replacevalue one liner really ugly but it is only used in here return text replace text text find re findall pattern text replacevalue text text find re findall pattern text len replacevalue so if do sth like getexpandedtext aaa bbb hola aaaiiibbb como estas ooo hola aaaooobbb como estas it changes the with ooo do you guys know whether with python regular expressions we can do this thanks lot guys
|
you want to use re sub import re re sub aaa bbb aaaooobbb hola aaaiiibbb como estas hola aaaooobbb como estas to re use variable parts from the pattern use in the replacement string to access the th group re sub svcordnbr xx svcordnbr iasz svcordnbr xxsz
|
QA
|
writing domain specific language for selecting rows from table am writing server that expect to be run by many different people not all of whom will have direct contact with the servers will communicate with each other in cluster part of the server functionality involves selecting small subset of rows from potentially very large table the exact choice of what rows are selected will need some tuning and it is important that it is possible for the person running the cluster eg myself to update the selection criteria without getting each and every server administrator to deploy new version of the server simply writing the function in python is not really an option since nobody is going to want to install server that downloads and executes arbitrary python code at runtime what need are suggestions on the simplest way to implement domain specific language to achieve this goal the language needs to be capable of simple expression evaluation as well as querying table indexes and iterating through the returned rows ease of writing and reading the language is secondary to ease of implementing it would also prefer not to have to write an entire query optimiser so something that explicitly specifies what indexes to query would be ideal the interface that this will have to compile against will be similar in capabilities to what the app engine datastore exports you can query for sequential ranges on any index on the table eg less than greater than range and equality queries then filter the returned row by any boolean expression you can also concatenate multiple independent result sets together realise this question sounds lot like am asking for sql however do not want to require that the datastore backing this data be relational database and do not want the overhead of trying to reimplement sql myself am also dealing with only single table with known schema finally no joins will be required something much simpler would be far preferable edit expanded description to clear up some misconceptions
|
you said nobody is going to want to install server that downloads and executes arbitrary code at runtime however that is exactly what your dsl will do eventually so there probably is not that much of difference unless you are doing something very specific with the data then do not think dsl will buy you that much and it will frustrate the users who are already versed in sql do not underestimate the size of the task you will be taking on to answer your question however you will need to come up with grammar for your language something to parse the text and walk the tree emitting code or calling an api that you have written which is why my comment that you are still going to have to ship some code there are plenty of educational texts on grammars for mathematical expressions you can refer to on the net that is fairly straight forward you may have parser generator tool like antlr or yacc you can use to help you generate the parser or use language like lisp scheme and marry the two up coming up with reasonable sql grammar will not be easy but google bnf sql and see what you come up with best of luck
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.