prefix
stringclasses 1
value | input_text
stringlengths 19
27.3k
⌀ | target_text
stringlengths 2
24.8k
⌀ |
---|---|---|
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
|
well thanks to all who answered the question anyway think solved the mistery selinux is completely disabled on the machine so the problem is definitely in svn co not being able to found config dir for the user account it runs under apache mod python does not read in she will environment of the user account which apache is running on thus for examle no home is seen by mod python when apache is running under some real user not nobody now svn co has flag config dir which points to configuration directory to read params from by default it is home subversion it corresponds to the user account home directory apparently when no home exists mod python goes to root home dir root and tries to fiddle with subversion content over there which is obviously fails miserably putting setenv home home qa into the etc httpd conf httpd conf does not solve the problem because of setenv having nothing to do with she will environment it only sets apache related environment likewise pythonoption sets only mod python related variables which can be read with req get options after that running svn co config dir home definitely gives workaround for running from within mod python but gets in the way of those who will try to run the script from command line so the proposed and working solution is to set home environment variable prior to starting appache for example in etc init httpd script qahome home qa home qahome lang httpd lang daemon httpd options
|
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
|
was able to fix it by using the info dzinx provided with some modification it appears that posting the radio buttons box first locked in the box to the sizer if tried to add new box would get an error message stating that was trying to add the widget to the same sizer twice by simply removing the radio buttons initially and having the user click button to call method could simply add the list of radio buttons without problem additionally by having the user click button did not run into errors of class foo has no attribute bar apparently when the wizard initalizes the attributes are not available to the rest of the wizard pages had thought the wizard pages were dynamically created with each click of next but they are all created at the same time
|
QA
|
text difference algorithm need an algorithm that can compare two text files and highlight their difference and even better can compute their difference in meaningful way like two similar files should have similarity score higher than two dissimilar files with the word similar defined in the normal terms it sounds easy to implement but it is not the implementation can be in or python thanks
|
look at difflib python that will calculate the diffs in various formats you could then use the size of the context different as measure of how different two documents are
|
QA
|
adding cookie to zsi posts have added cookie support to soappy by overriding httptransport need functionality beyond that of soappy so was planning on moving to zsi but cannot figure out how to put the cookies on the zsi posts made to the service without these cookies the server will think it is an unauthorized request and it will fail how can add cookies from python cookiejar to zsi requests
|
if you read the binding class in client py of zsi you can see that it has variable cookies which is an instance of cookie simplecookie following the zsi example and the cookie example that is how it should work binding url cgi bin simple test tracefile fp cookies foo bar
|
QA
|
text difference algorithm need an algorithm that can compare two text files and highlight their difference and even better can compute their difference in meaningful way like two similar files should have similarity score higher than two dissimilar files with the word similar defined in the normal terms it sounds easy to implement but it is not the implementation can be in or python thanks
|
if you need finer granularity than lines you can use levenshtein distance levenshtein distance is straight forward measure on how to similar two texts are you can also use it to extract the edit logs and can very fine grained different similar to that on the edit history pages of so be warned though that levenshtein distance can be quite cpu and memory intensive to calculate so using difflib as douglas leder suggested is most likely going to be faster cf also this answer
|
QA
|
text difference algorithm need an algorithm that can compare two text files and highlight their difference and even better can compute their difference in meaningful way like two similar files should have similarity score higher than two dissimilar files with the word similar defined in the normal terms it sounds easy to implement but it is not the implementation can be in or python thanks
|
as stated use difflib once you have the diffed output you may find the levenshtein distance of the different strings as to give value of how different they are
|
QA
|
text difference algorithm need an algorithm that can compare two text files and highlight their difference and even better can compute their difference in meaningful way like two similar files should have similarity score higher than two dissimilar files with the word similar defined in the normal terms it sounds easy to implement but it is not the implementation can be in or python thanks
|
bazaar contains an alternative difference algorithm called patience different there is more info in the comments on that page which is claimed to be better than the traditional different algorithm the file patiencediff py in the bazaar distribution is simple command line front end
|
QA
|
calling from python what would be the quickest way to construct python binding to or library using windows if this matters
|
like ctypes lot swig always tended to give me problems also ctypes has the advantage that you do not need to satisfy any compile time dependency on python and your binding will work on any python that has ctypes not just the one it was compiled against suppose you have simple example class you want to talk to in file called foo cpp include iostream class foo public void bar std cout hello std endl since ctypes can only talk to functions you need to provide those declaring them as extern extern foo foo new return new foo void foo bar foo foo foo bar next you have to compile this to shared library fpic foo cpp foo shared wl soname libfoo so libfoo so foo and finally you have to write your python wrapper in foowrapper py from ctypes import cdll lib cdll loadlibrary libfoo so class foo object def init self self obj lib foo new def bar self lib foo bar self obj once you have that you can call it like foo bar and you will see hello on the screen
|
QA
|
text difference algorithm need an algorithm that can compare two text files and highlight their difference and even better can compute their difference in meaningful way like two similar files should have similarity score higher than two dissimilar files with the word similar defined in the normal terms it sounds easy to implement but it is not the implementation can be in or python thanks
|
can recommend to take look at neil fraser code and articles google different match patch currently available in java javascript and python regardless of language each library features the same api and the same functionality all versions also have comprehensive test harnesses neil fraser different strategies for theory and implementation notes
|
QA
|
python postgresql modules which is best have seen number of postgresql modules for python like pygresql pypgsql psyco most of them are python db api compliant some are not being actively developed anymore which module do you recommend why
|
psycopg is known for better performance in heavilyy threaded environments like web applications than psycopg although not maintained both are well written and rock solid would choose one of these two depending on use case
|
QA
|
does anyone know of widget for desktop toolkit gtk qt wx for displaying map of us states am specifically looking for one that let us me display map of us states with each one as it is own object in the sense that can control the color on click and on mouseover of each one individually gtk is my personal preference but at this point would settle for just about anything the application itself will be written in python fwiw
|
if you consider qt consider also throwing in kdelibs dependency then you will have marble widget which handles maps in neat way if you stick only to qt then qgraphicsview is framework to go note kdelibs running whole kde desktop
|
QA
|
does anyone know of widget for desktop toolkit gtk qt wx for displaying map of us states am specifically looking for one that let us me display map of us states with each one as it is own object in the sense that can control the color on click and on mouseover of each one individually gtk is my personal preference but at this point would settle for just about anything the application itself will be written in python fwiw
|
you can use quantum gis qgis is open source geographic information system using the qt framework qgis can also be used with python you can either extend it with plugins written in python or use the pygis python bindings to write your own application they have wiki with some good informations for developers maybe qgis is to heavy for your purpose but add it here for completition anyway
|
QA
|
how do successfully pass function reference to django reverse function ve got brand new django project ve added one minimal view function to views py and one url pattern to urls py passing the view by function reference instead of string urls py coding utf from django conf urls defaults import from myapp import views urlpatterns patterns url myview views myview views py coding utf from django http import httpresponse def myview request return httpresponse myview lol content type text plain trying to use reverse to get the url by passing it function reference but not getting match despite confirming that the view function passing to reverse is the exact same view function put in the url pattern from django core urlresolvers import reverse import urls from myapp import views urls urlpatterns callback is views myview true reverse views myview traceback most recent call last file console line in module file library python site packages django core urlresolvers py line in reverse args kwargs file library python site packages django core urlresolvers py line in reverse arguments not found lookup view args kwargs noreversematch reverse for function myview at fe with arguments and keyword arguments not found as far as can tell from the documentation function references should be fine in both the url pattern and reverse url patterns with function references reverse with function references using the django trunk revision
|
got it the problem is that some of the imports are of myproject myapp views and some are just of myapp views this is confusing the python module system enough that it no longer detects the functions as the same object this is because your main settings py probably has line like root urlconf myproject urls to solve this try using the full import in your she will session from django core urlresolvers import reverse from myproject myapp import views reverse views myview myview here is log of the debugging session for any interested future readers from django core import urlresolvers from myapp import myview urlresolvers get resolver none reverse dict none you myview myview function myview at you myview myview urlresolvers get resolver none reverse dict items reverse myview is myview false module testproject myapp views myview module myapp views what happens if you change the url match to be myview have you tried it with the view name something like reverse myapp myview is urls py the root urlconf or in the myapp application there needs to be full path from the root to view for it to be resolved if that is myproject myapp urls py then in myproject urls py you will need code like this from django conf urls defaults import patterns urlpatterns patterns myapp urls
|
QA
|
text difference algorithm need an algorithm that can compare two text files and highlight their difference and even better can compute their difference in meaningful way like two similar files should have similarity score higher than two dissimilar files with the word similar defined in the normal terms it sounds easy to implement but it is not the implementation can be in or python thanks
|
there are number of distance metrics as paradoja mentioned there is the levenshtein distance but there is also nysiis and soundex in terms of python implementations have used py editdist and advas before both are nice in the sense that you get single number back as score check out advas first it implements bunch of algorithms
|
QA
|
how do successfully pass function reference to django reverse function ve got brand new django project ve added one minimal view function to views py and one url pattern to urls py passing the view by function reference instead of string urls py coding utf from django conf urls defaults import from myapp import views urlpatterns patterns url myview views myview views py coding utf from django http import httpresponse def myview request return httpresponse myview lol content type text plain trying to use reverse to get the url by passing it function reference but not getting match despite confirming that the view function passing to reverse is the exact same view function put in the url pattern from django core urlresolvers import reverse import urls from myapp import views urls urlpatterns callback is views myview true reverse views myview traceback most recent call last file console line in module file library python site packages django core urlresolvers py line in reverse args kwargs file library python site packages django core urlresolvers py line in reverse arguments not found lookup view args kwargs noreversematch reverse for function myview at fe with arguments and keyword arguments not found as far as can tell from the documentation function references should be fine in both the url pattern and reverse url patterns with function references reverse with function references using the django trunk revision
|
if your two code pastes are complete then it does not look like the second which makes the actual call to reverse ever imports the urls module and therefor if the url mapping is ever actually achieved
|
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
|
after futher investigation turns out it was an issue with how was importing the views module http stackoverflow com questions how do successfully pass function reference to djangos reverse function thanks for the help though guys you inspired me to look at it properly
|
QA
|
am using python regexes in criminally inefficient manner my goal here is to create very simple template language at the moment am working on replacing variable with value like this this input title this is test variable the web title should produce this output the web this is test variable have got it working but looking at my code am running multiple identical regexes on the same strings that just offends my sense of efficiency there is got to be better more pythonic way it is the two while loops that really offend this does pass the unit tests so if this is silly premature optimization tell me am willing to let this go there may be dozens of these variable definitions and uses in document but not hundreds but suspect there is obvious to other people ways of improving this and am curious what the stackoverflow crowd will come up with def stripmatchedquotes item matchedsinglequotes re compile re locale matcheddoublequotes re compile re locale item matchedsinglequotes sub item item matcheddoublequotes sub item return item def processvariables item variabledefinition re compile re locale variableuse re compile re locale variables while variabledefinition search item varname vardef variabledefinition search item groups varname stripmatchedquotes varname upper strip vardef stripmatchedquotes vardef strip variables varname vardef item variabledefinition sub item while variableuse search item varname stripmatchedquotes variableuse search item group upper strip item variableuse sub variables varname item return item
|
never create your own programming language ever used to have an exception to this rule but not any more there is always an existing language you can use which suits your needs better if you elaborated on your use case people may help you select suitable language
|
QA
|
am using python regexes in criminally inefficient manner my goal here is to create very simple template language at the moment am working on replacing variable with value like this this input title this is test variable the web title should produce this output the web this is test variable have got it working but looking at my code am running multiple identical regexes on the same strings that just offends my sense of efficiency there is got to be better more pythonic way it is the two while loops that really offend this does pass the unit tests so if this is silly premature optimization tell me am willing to let this go there may be dozens of these variable definitions and uses in document but not hundreds but suspect there is obvious to other people ways of improving this and am curious what the stackoverflow crowd will come up with def stripmatchedquotes item matchedsinglequotes re compile re locale matcheddoublequotes re compile re locale item matchedsinglequotes sub item item matcheddoublequotes sub item return item def processvariables item variabledefinition re compile re locale variableuse re compile re locale variables while variabledefinition search item varname vardef variabledefinition search item groups varname stripmatchedquotes varname upper strip vardef stripmatchedquotes vardef strip variables varname vardef item variabledefinition sub item while variableuse search item varname stripmatchedquotes variableuse search item group upper strip item variableuse sub variables varname item return item
|
you can match both kind of quotes in one go with the refers to the first group so it will only match matching quotes
|
QA
|
am using python regexes in criminally inefficient manner my goal here is to create very simple template language at the moment am working on replacing variable with value like this this input title this is test variable the web title should produce this output the web this is test variable have got it working but looking at my code am running multiple identical regexes on the same strings that just offends my sense of efficiency there is got to be better more pythonic way it is the two while loops that really offend this does pass the unit tests so if this is silly premature optimization tell me am willing to let this go there may be dozens of these variable definitions and uses in document but not hundreds but suspect there is obvious to other people ways of improving this and am curious what the stackoverflow crowd will come up with def stripmatchedquotes item matchedsinglequotes re compile re locale matcheddoublequotes re compile re locale item matchedsinglequotes sub item item matcheddoublequotes sub item return item def processvariables item variabledefinition re compile re locale variableuse re compile re locale variables while variabledefinition search item varname vardef variabledefinition search item groups varname stripmatchedquotes varname upper strip vardef stripmatchedquotes vardef strip variables varname vardef item variabledefinition sub item while variableuse search item varname stripmatchedquotes variableuse search item group upper strip item variableuse sub variables varname item return item
|
do not call search twice in row in the loop conditional and the first statement in the loop call and cache the result once before the loop and then in the final statement of the loop
|
QA
|
am using python regexes in criminally inefficient manner my goal here is to create very simple template language at the moment am working on replacing variable with value like this this input title this is test variable the web title should produce this output the web this is test variable have got it working but looking at my code am running multiple identical regexes on the same strings that just offends my sense of efficiency there is got to be better more pythonic way it is the two while loops that really offend this does pass the unit tests so if this is silly premature optimization tell me am willing to let this go there may be dozens of these variable definitions and uses in document but not hundreds but suspect there is obvious to other people ways of improving this and am curious what the stackoverflow crowd will come up with def stripmatchedquotes item matchedsinglequotes re compile re locale matcheddoublequotes re compile re locale item matchedsinglequotes sub item item matcheddoublequotes sub item return item def processvariables item variabledefinition re compile re locale variableuse re compile re locale variables while variabledefinition search item varname vardef variabledefinition search item groups varname stripmatchedquotes varname upper strip vardef stripmatchedquotes vardef strip variables varname vardef item variabledefinition sub item while variableuse search item varname stripmatchedquotes variableuse search item group upper strip item variableuse sub variables varname item return item
|
you are calling re compile quite bit global variable for these would not hurt here
|
QA
|
am using python regexes in criminally inefficient manner my goal here is to create very simple template language at the moment am working on replacing variable with value like this this input title this is test variable the web title should produce this output the web this is test variable have got it working but looking at my code am running multiple identical regexes on the same strings that just offends my sense of efficiency there is got to be better more pythonic way it is the two while loops that really offend this does pass the unit tests so if this is silly premature optimization tell me am willing to let this go there may be dozens of these variable definitions and uses in document but not hundreds but suspect there is obvious to other people ways of improving this and am curious what the stackoverflow crowd will come up with def stripmatchedquotes item matchedsinglequotes re compile re locale matcheddoublequotes re compile re locale item matchedsinglequotes sub item item matcheddoublequotes sub item return item def processvariables item variabledefinition re compile re locale variableuse re compile re locale variables while variabledefinition search item varname vardef variabledefinition search item groups varname stripmatchedquotes varname upper strip vardef stripmatchedquotes vardef strip variables varname vardef item variabledefinition sub item while variableuse search item varname stripmatchedquotes variableuse search item group upper strip item variableuse sub variables varname item return item
|
the first thing that may improve things is to move the re compile outside the function the compilation is cached but there is speed hit in checking this to see if its compiled another possibility is to use single regex as below matchedquotes re compile re locale item matchedquotes sub item finally you can combine this into the regex in processvariables taking torsten marek suggestion to use function for re sub this improves and simplifies things dramatically variabledefinition re compile re locale varrepl re compile re locale def processvariables item vars def findvars vars group upper group return item variabledefinition sub findvars item return varrepl sub lambda vars group upper item print processvariables title this is test variable the web title here are my timings for runs original global regexes single regex final version edit add missing non greedy specifier edit added upper calls so case insensitive like original version
|
QA
|
am using python regexes in criminally inefficient manner my goal here is to create very simple template language at the moment am working on replacing variable with value like this this input title this is test variable the web title should produce this output the web this is test variable have got it working but looking at my code am running multiple identical regexes on the same strings that just offends my sense of efficiency there is got to be better more pythonic way it is the two while loops that really offend this does pass the unit tests so if this is silly premature optimization tell me am willing to let this go there may be dozens of these variable definitions and uses in document but not hundreds but suspect there is obvious to other people ways of improving this and am curious what the stackoverflow crowd will come up with def stripmatchedquotes item matchedsinglequotes re compile re locale matcheddoublequotes re compile re locale item matchedsinglequotes sub item item matcheddoublequotes sub item return item def processvariables item variabledefinition re compile re locale variableuse re compile re locale variables while variabledefinition search item varname vardef variabledefinition search item groups varname stripmatchedquotes varname upper strip vardef stripmatchedquotes vardef strip variables varname vardef item variabledefinition sub item while variableuse search item varname stripmatchedquotes variableuse search item group upper strip item variableuse sub variables varname item return item
|
sub can take callable as it is argument rather than simple string using that you can replace all variables with one function call import re var matcher re compile re locale string title shmitle values title am title shmitle and am shmitle var matcher sub lambda vars group string am title and am shmitle follow eduffy myopenid com advice and keep the compiled regexes around the same recipe can be applied to the first loop only there you need to store the value of the variable first and always return as replacement
|
QA
|
am using python regexes in criminally inefficient manner my goal here is to create very simple template language at the moment am working on replacing variable with value like this this input title this is test variable the web title should produce this output the web this is test variable have got it working but looking at my code am running multiple identical regexes on the same strings that just offends my sense of efficiency there is got to be better more pythonic way it is the two while loops that really offend this does pass the unit tests so if this is silly premature optimization tell me am willing to let this go there may be dozens of these variable definitions and uses in document but not hundreds but suspect there is obvious to other people ways of improving this and am curious what the stackoverflow crowd will come up with def stripmatchedquotes item matchedsinglequotes re compile re locale matcheddoublequotes re compile re locale item matchedsinglequotes sub item item matcheddoublequotes sub item return item def processvariables item variabledefinition re compile re locale variableuse re compile re locale variables while variabledefinition search item varname vardef variabledefinition search item groups varname stripmatchedquotes varname upper strip vardef stripmatchedquotes vardef strip variables varname vardef item variabledefinition sub item while variableuse search item varname stripmatchedquotes variableuse search item group upper strip item variableuse sub variables varname item return item
|
if regexp only contains one wildcard and literals then you can use find and rfind to locate the opening and closing delimiters if it contains only series of wildcards and literals then you can just use series of find to do the work if the code is time critical this switch away from regexp altogether might give little more speed also it looks to me like this is an ll parsable language you could look for library that can already parse such things for you you could also use recursive calls to do one pass parse for example you could implement your processvariables function to only consume up the first quote and then call quote matching function to consume up to the next quote etc
|
QA
|
am using python regexes in criminally inefficient manner my goal here is to create very simple template language at the moment am working on replacing variable with value like this this input title this is test variable the web title should produce this output the web this is test variable have got it working but looking at my code am running multiple identical regexes on the same strings that just offends my sense of efficiency there is got to be better more pythonic way it is the two while loops that really offend this does pass the unit tests so if this is silly premature optimization tell me am willing to let this go there may be dozens of these variable definitions and uses in document but not hundreds but suspect there is obvious to other people ways of improving this and am curious what the stackoverflow crowd will come up with def stripmatchedquotes item matchedsinglequotes re compile re locale matcheddoublequotes re compile re locale item matchedsinglequotes sub item item matcheddoublequotes sub item return item def processvariables item variabledefinition re compile re locale variableuse re compile re locale variables while variabledefinition search item varname vardef variabledefinition search item groups varname stripmatchedquotes varname upper strip vardef stripmatchedquotes vardef strip variables varname vardef item variabledefinition sub item while variableuse search item varname stripmatchedquotes variableuse search item group upper strip item variableuse sub variables varname item return item
|
creating templating language is all well and good but should not one of the goals of the templating language be easy readability and efficient parsing the example you gave seems to be neither as jamie zawinsky famously said some people when confronted with problem think know will use regular expressions now they have two problems if regular expressions are solution to problem you have created the best bet is not to write better regular expression but to redesign your approach to eliminate their use entirely regular expressions are complicated expensive hugely difficult to maintain and ideally should only be used for working around problem someone else created
|
QA
|
in django where is the best place to put short snippets of html formatted data this question is related to but perhaps not quite the same as http stackoverflow com questions does django have html helpers my problem is this in django am constantly reproducing the basic formatting for low level database objects here is an example have two classes person and address there are multiple addresses for each person setup likeso in their respective models py class person models model class address models model contact models foreignkey person now whenever look at person want to see all their addresses so suppose persons views py has something likeso def detail request person id person get object or person pk person id return render to response persons details html title unicode person addresses person address set all and have template persons details html with code for example like so extends base html for address in addresses address name address type br address street br address street br address city address stateprov address postalcode br address country hr endfor am repeating this code quite bit often with minor variations such when it is in table and then br must be substituted by td td other times do not want street to display or the br after it all to say there is fundamental logic that want to express that am even more loath to tote around with block and copy what want is persons details html with for example the following extends base html for address in addresses address as html endfor and if want inline table something likeso guess extends base html table tr for address in addresses tr td address as html td td td tr endfor table the question is then where is the best place to put the formatting the logic django seem to have the following plausible options put the formatting in models py put the logic formatting in views py put the logic formatting in some other sub class of person or address addresses html py create custom tags help insight much appreciated
|
would use template tag outputting data using template html file inclusion tag
|
QA
|
in django where is the best place to put short snippets of html formatted data this question is related to but perhaps not quite the same as http stackoverflow com questions does django have html helpers my problem is this in django am constantly reproducing the basic formatting for low level database objects here is an example have two classes person and address there are multiple addresses for each person setup likeso in their respective models py class person models model class address models model contact models foreignkey person now whenever look at person want to see all their addresses so suppose persons views py has something likeso def detail request person id person get object or person pk person id return render to response persons details html title unicode person addresses person address set all and have template persons details html with code for example like so extends base html for address in addresses address name address type br address street br address street br address city address stateprov address postalcode br address country hr endfor am repeating this code quite bit often with minor variations such when it is in table and then br must be substituted by td td other times do not want street to display or the br after it all to say there is fundamental logic that want to express that am even more loath to tote around with block and copy what want is persons details html with for example the following extends base html for address in addresses address as html endfor and if want inline table something likeso guess extends base html table tr for address in addresses tr td address as html td td td tr endfor table the question is then where is the best place to put the formatting the logic django seem to have the following plausible options put the formatting in models py put the logic formatting in views py put the logic formatting in some other sub class of person or address addresses html py create custom tags help insight much appreciated
|
sounds like an inclusion tag is what you are looking for you could have template and tag for each major variation and use the tag arguments to customise the context for each template as required basic tag definition register inclusion tag person address html def display address address return address address use in templates assuming the templatetag module containing it has already been load ed display address address
|
QA
|
am using python regexes in criminally inefficient manner my goal here is to create very simple template language at the moment am working on replacing variable with value like this this input title this is test variable the web title should produce this output the web this is test variable have got it working but looking at my code am running multiple identical regexes on the same strings that just offends my sense of efficiency there is got to be better more pythonic way it is the two while loops that really offend this does pass the unit tests so if this is silly premature optimization tell me am willing to let this go there may be dozens of these variable definitions and uses in document but not hundreds but suspect there is obvious to other people ways of improving this and am curious what the stackoverflow crowd will come up with def stripmatchedquotes item matchedsinglequotes re compile re locale matcheddoublequotes re compile re locale item matchedsinglequotes sub item item matcheddoublequotes sub item return item def processvariables item variabledefinition re compile re locale variableuse re compile re locale variables while variabledefinition search item varname vardef variabledefinition search item groups varname stripmatchedquotes varname upper strip vardef stripmatchedquotes vardef strip variables varname vardef item variabledefinition sub item while variableuse search item varname stripmatchedquotes variableuse search item group upper strip item variableuse sub variables varname item return item
|
why not use mako seriously what feature do you require that mako does not have perhaps you can adapt or extend something that already works
|
QA
|
text difference algorithm need an algorithm that can compare two text files and highlight their difference and even better can compute their difference in meaningful way like two similar files should have similarity score higher than two dissimilar files with the word similar defined in the normal terms it sounds easy to implement but it is not the implementation can be in or python thanks
|
in python there is difflib as also others have suggested difflib offers the sequencematcher class which can be used to give you similarity ratio example function def text compare text text isjunk none return difflib sequencematcher isjunk text text ratio
|
QA
|
showing the stack trace from running python application have this python application that gets stuck from time to time and cannot find out where is there any way to signal python interpreter to show you the exact code that is running some kind of on the fly stacktrace related questions print current call stack from method in python code check what running process is doing print stack trace of an uninstrumented python program
|
the suggestion to install signal handler is good one and use it lot for example bzr by default installs sigquit handler that invokes pdb set trace to immediately drop you into pdb prompt see the bzrlib breakin module source for the exact details with pdb you can not only get the current stack trace but also inspect variables etc however sometimes need to debug process that did not have the foresight to install the signal handler in on linux you can attach gdb to the process and get python stack trace with some gdb macros put http svn python org projects python trunk misc gdbinit in gdbinit then attach gdb gdb pid get the python stack trace pystack it is not totally reliable unfortunately but it works most of the time finally attaching strace can often give you good idea what process is doing
|
QA
|
difflib sequencematcher isjunk optional parameter query how to ignore whitespaces tabs empty lines am trying to use difflib sequencematcher to compute the similarities between two files these two files are almost identical except that one contains some extra whitespaces empty lines and other does not am trying to use difflib sequencematcher isjunk text text ratio ratio for this purpose so the question is how to write the lambda expression for this isjunk method so the sequencematcher method will discount all the whitespaces empty lines etc tried to use the parameter lambda but the result is not as great for two closely similar text the ratio is very low this is highly counter intuitive for testing purpose here are the two strings that you can use on testing what motivates jwovu to do your job well ok this is an entry trying to win worth of software development books despite the fact that don read programming books in order to win the prize you have to write an entry and what motivatesfggmum to do your job well hence this post first motivation money know this doesn sound like great inspiration to many and saying that money is one of the motivation factors might just blow my chances away as if money is taboo in programming world know there are people who can be motivated by money mme on the other hand am living in real world with house mortgage to pay myself to feed and bills to cover so can really exclude money from my consideration if can get large sum of money for doing good job then definitely boost my morale won care whether am using an old workstation or forced to share rooms or cubicle with other people or have to put up with an annoying boss or whatever the fact that at the end of the day will walk off with large pile of money itself is enough for me to overcome all the obstacles put up with all the hard feelings and hurt egos tolerate slow computer and even endure and here is another string what motivates you to do your job well ok this is an entry trying to win worth of software development books despite the fact that do not read programming books in order to win the prize you have to write an entry and describes what motivates you to do your job well hence this post first motivation money know this does not sound like great inspiration to many and saying that money is one of the motivation factors might just blow my chances away as if money is taboo in programming world know there are people who cannot be motivated by money kudos to them me on the other hand am living in real world with house mortgage to pay myself to feed and bills to cover so cannot really exclude money from my consideration if can get large sum of money for doing good job then thatwill definitely boost my morale will not care whether am using an old workstation or forced to share rooms or cubicle with other people or have to put up with an annoying boss or whatever the fact that at the end of the day will walk off with large pile of money itself is enough for me to overcome all the obstacles put up with all the hard feelings and hurt egos tolerate slow computer and even endure ran the above command and set the isjunk to lambda the ratio is only
|
have not used difflib sequencematcher but have you considered pre processing the files to remove all blank lines and whitespace perhaps via regular expressions and then doing the compare
|
QA
|
how does one do the equivalent of import from module with python import function given string with module name how do you import everything in the module as if you had called from module import given string module how does one get the equivalent of the following import fromlist this does not seem to perform as expected as it does not import anything thanks
|
please reconsider the only thing worse than import is magic import if you really want to import try attrlist all except attributeerror attrlist dir for attr in attrlist globals attr getattr attr
|
QA
|
django vmware appliance does anyone know of django postgresql apache mod python vmware appliance vanilla django appliance where postgresql can be installed manually would also do
|
configure and build your appliance at elastic server on demand
|
QA
|
how do manipulate bits in python in could for example zero out bit in bit unsigned value like so unsigned long value xdeadbeef value how do do that in python
|
value xdeadbeef value
|
QA
|
how do manipulate bits in python in could for example zero out bit in bit unsigned value like so unsigned long value xdeadbeef value how do do that in python
|
have you tried copying and pasting your code into the python repl to see what will happen value xdeadbeef value hex value xdeadbaef
|
QA
|
how do manipulate bits in python in could for example zero out bit in bit unsigned value like so unsigned long value xdeadbeef value how do do that in python
|
omit the unsigned long and the semi colons are not needed either value xdeadbeef value print value value
|
QA
|
how do manipulate bits in python in could for example zero out bit in bit unsigned value like so unsigned long value xdeadbeef value how do do that in python
|
python has style bit manipulation operators so your example is literally the same in python except without type keywords value xdeadbeef value
|
QA
|
difflib sequencematcher isjunk optional parameter query how to ignore whitespaces tabs empty lines am trying to use difflib sequencematcher to compute the similarities between two files these two files are almost identical except that one contains some extra whitespaces empty lines and other does not am trying to use difflib sequencematcher isjunk text text ratio ratio for this purpose so the question is how to write the lambda expression for this isjunk method so the sequencematcher method will discount all the whitespaces empty lines etc tried to use the parameter lambda but the result is not as great for two closely similar text the ratio is very low this is highly counter intuitive for testing purpose here are the two strings that you can use on testing what motivates jwovu to do your job well ok this is an entry trying to win worth of software development books despite the fact that don read programming books in order to win the prize you have to write an entry and what motivatesfggmum to do your job well hence this post first motivation money know this doesn sound like great inspiration to many and saying that money is one of the motivation factors might just blow my chances away as if money is taboo in programming world know there are people who can be motivated by money mme on the other hand am living in real world with house mortgage to pay myself to feed and bills to cover so can really exclude money from my consideration if can get large sum of money for doing good job then definitely boost my morale won care whether am using an old workstation or forced to share rooms or cubicle with other people or have to put up with an annoying boss or whatever the fact that at the end of the day will walk off with large pile of money itself is enough for me to overcome all the obstacles put up with all the hard feelings and hurt egos tolerate slow computer and even endure and here is another string what motivates you to do your job well ok this is an entry trying to win worth of software development books despite the fact that do not read programming books in order to win the prize you have to write an entry and describes what motivates you to do your job well hence this post first motivation money know this does not sound like great inspiration to many and saying that money is one of the motivation factors might just blow my chances away as if money is taboo in programming world know there are people who cannot be motivated by money kudos to them me on the other hand am living in real world with house mortgage to pay myself to feed and bills to cover so cannot really exclude money from my consideration if can get large sum of money for doing good job then thatwill definitely boost my morale will not care whether am using an old workstation or forced to share rooms or cubicle with other people or have to put up with an annoying boss or whatever the fact that at the end of the day will walk off with large pile of money itself is enough for me to overcome all the obstacles put up with all the hard feelings and hurt egos tolerate slow computer and even endure ran the above command and set the isjunk to lambda the ratio is only
|
using your sample strings difflib sequencematcher lambda ratio interestingly if is also included as junk difflib sequencematcher lambda in ratio looks like the new lines are having much greater affect than the spaces
|
QA
|
how do manipulate bits in python in could for example zero out bit in bit unsigned value like so unsigned long value xdeadbeef value how do do that in python
|
bitwise operations on python ints work much like in the and operators in python work just like in the operator works as for signed integer in that is computes you have to be somewhat careful with left shifts since python integers are not fixed width use bit masks to obtain the low order bits for example to do the equivalent of shift of bit integer do xffffffff
|
QA
|
django vmware appliance does anyone know of django postgresql apache mod python vmware appliance vanilla django appliance where postgresql can be installed manually would also do
|
it might be little too heavy for your requirements but all of those items and whole lot more are included in the python web developer appliance
|
QA
|
character reading from file in python in text file there is string do not like this however when read it into string it becomes don xe like this understand that is the unicode representation of use open file text read command to do the reading now is it possible to read the string in such way that when it is read into the string it is do not like this instead of don xe like this like this second edit have seen some people use mapping to solve this problem but really is there no built in conversion that does this kind of ansi to unicode and vice versa conversion
|
actually you is the unicode representation of the special character if you want you can convert instances of that character to you with this code text text replace you in addition what are you using to write the file read should return string that looks like this don xe like this if it is returning this string the file is being written incorrectly don like this
|
QA
|
character reading from file in python in text file there is string do not like this however when read it into string it becomes don xe like this understand that is the unicode representation of use open file text read command to do the reading now is it possible to read the string in such way that when it is read into the string it is do not like this instead of don xe like this like this second edit have seen some people use mapping to solve this problem but really is there no built in conversion that does this kind of ansi to unicode and vice versa conversion
|
this is pythons way do show you unicode encoded strings but think you should be able to print the string on the screen or write it into new file without any problems test you don like this test you don like this print test don like this
|
QA
|
character reading from file in python in text file there is string do not like this however when read it into string it becomes don xe like this understand that is the unicode representation of use open file text read command to do the reading now is it possible to read the string in such way that when it is read into the string it is do not like this instead of don xe like this like this second edit have seen some people use mapping to solve this problem but really is there no built in conversion that does this kind of ansi to unicode and vice versa conversion
|
ref http docs python org howto unicode reading unicode from file is therefore simple import codecs codecs open unicode rst encoding utf for line in print repr line it is also possible to open files in update mode allowing both reading and writing codecs open test encoding utf mode write you blah blah blah seek print repr readline close edit am assuming that your intended goal is just to be able to read the file properly into string in python if you are trying to convert to an ascii string from unicode then there is really no direct way to do so since the unicode characters will not necessarily exist in ascii if you are trying to convert to an ascii string try one of the following replace the specific unicode chars with ascii equivalents if you are only looking to handle few special cases such as this particular example use the unicodedata module normalize and the string encode method to convert as best you can to the next closest ascii equivalent ref https web archive org web http techxplorer com converting unicode to ascii using python teststr you don xe like this unicodedata normalize nfkd teststr encode ascii ignore donat like this
|
QA
|
character reading from file in python in text file there is string do not like this however when read it into string it becomes don xe like this understand that is the unicode representation of use open file text read command to do the reading now is it possible to read the string in such way that when it is read into the string it is do not like this instead of don xe like this like this second edit have seen some people use mapping to solve this problem but really is there no built in conversion that does this kind of ansi to unicode and vice versa conversion
|
but it really is don like this and not do not like this the character you is completely different character than and visually should correspond more to if you are trying to convert encoded unicode into plain ascii you could perhaps keep mapping of unicode punctuation that you would like to translate into ascii punctuation you you for src dest in punctuation iteritems text text replace src dest there are an awful lot of punctuation characters in unicode however but suppose you can count on only few of them actually being used by whatever application is creating the documents you are reading
|
QA
|
debug pylons application through eclipse have eclipse setup with pydev and love being able to debug my scripts apps have just started playing around with pylons and was wondering if there is way to start up the paster server through eclipse so can debug my webapp
|
create new launch configuration python run main tab use paster script py as main module you can find it in the scripts sub directory in your python installation directory do not forget to add the root folder of your application in the pythonpath zone arguments set the base directory to the root folder also as program arguments use serve development ini or whatever you use to debug your app common tab check allocate console and launch in background
|
QA
|
character reading from file in python in text file there is string do not like this however when read it into string it becomes don xe like this understand that is the unicode representation of use open file text read command to do the reading now is it possible to read the string in such way that when it is read into the string it is do not like this instead of don xe like this like this second edit have seen some people use mapping to solve this problem but really is there no built in conversion that does this kind of ansi to unicode and vice versa conversion
|
there are few points to consider character may appear only as fragment of representation of unicode string in python if you write text you print repr text you now if you simply want to print the unicode string prettily just use unicode encode method text you don like this print text encode utf don like this to make sure that every line from any file would be read as unicode you would better use the codecs open function instead of just open which allows you to specify file encoding import codecs codecs open file utf text read print type text type unicode print text encode utf don like this
|
QA
|
difflib sequencematcher isjunk optional parameter query how to ignore whitespaces tabs empty lines am trying to use difflib sequencematcher to compute the similarities between two files these two files are almost identical except that one contains some extra whitespaces empty lines and other does not am trying to use difflib sequencematcher isjunk text text ratio ratio for this purpose so the question is how to write the lambda expression for this isjunk method so the sequencematcher method will discount all the whitespaces empty lines etc tried to use the parameter lambda but the result is not as great for two closely similar text the ratio is very low this is highly counter intuitive for testing purpose here are the two strings that you can use on testing what motivates jwovu to do your job well ok this is an entry trying to win worth of software development books despite the fact that don read programming books in order to win the prize you have to write an entry and what motivatesfggmum to do your job well hence this post first motivation money know this doesn sound like great inspiration to many and saying that money is one of the motivation factors might just blow my chances away as if money is taboo in programming world know there are people who can be motivated by money mme on the other hand am living in real world with house mortgage to pay myself to feed and bills to cover so can really exclude money from my consideration if can get large sum of money for doing good job then definitely boost my morale won care whether am using an old workstation or forced to share rooms or cubicle with other people or have to put up with an annoying boss or whatever the fact that at the end of the day will walk off with large pile of money itself is enough for me to overcome all the obstacles put up with all the hard feelings and hurt egos tolerate slow computer and even endure and here is another string what motivates you to do your job well ok this is an entry trying to win worth of software development books despite the fact that do not read programming books in order to win the prize you have to write an entry and describes what motivates you to do your job well hence this post first motivation money know this does not sound like great inspiration to many and saying that money is one of the motivation factors might just blow my chances away as if money is taboo in programming world know there are people who cannot be motivated by money kudos to them me on the other hand am living in real world with house mortgage to pay myself to feed and bills to cover so cannot really exclude money from my consideration if can get large sum of money for doing good job then thatwill definitely boost my morale will not care whether am using an old workstation or forced to share rooms or cubicle with other people or have to put up with an annoying boss or whatever the fact that at the end of the day will walk off with large pile of money itself is enough for me to overcome all the obstacles put up with all the hard feelings and hurt egos tolerate slow computer and even endure ran the above command and set the isjunk to lambda the ratio is only
|
if you match all whitespaces the similarity is better difflib sequencematcher lambda in doc doc ratio however difflib is not ideal to such problem because these are two nearly identical documents but typos and such produce differences for difflib where human would not see many try reading up on tf idf bayesian probability vector space models and shingling have written an implementation of tf idf applying it to vector space and using the dot product as distance measure to classify documents
|
QA
|
in django is there way to display choices as checkboxes in the admin interface and newforms there is the brilliant helper of being able to define choices you can use code like this approval choices yes yes no no cancelled cancelled client approved models charfield choices approval choices to create drop down box in your form and force the user to choose one of those options am just wondering if there is way to define set of choices where multiple can be chosen using checkboxes would also be nice to be able to say that the user can select maximum number of them it seems like it is feature that is probably implemented it is just cannot seem to find it in the documentation
|
in terms of the forms library you would use the multiplechoicefield field with checkboxselectmultiple widget to do that you could validate the number of choices which were made by writing validation method for the field class myform forms form my field forms multiplechoicefield choices some choices widget forms checkboxselectmultiple def clean my field self if len self cleaned data my field raise forms validationerror select no more than return self cleaned data my field to get this in the admin application you would need to customise modelform and override the form used in the appropriate modeladmin
|
QA
|
character reading from file in python in text file there is string do not like this however when read it into string it becomes don xe like this understand that is the unicode representation of use open file text read command to do the reading now is it possible to read the string in such way that when it is read into the string it is do not like this instead of don xe like this like this second edit have seen some people use mapping to solve this problem but really is there no built in conversion that does this kind of ansi to unicode and vice versa conversion
|
there is possibility that somehow you have non unicode string with unicode escape characters print repr text don like this this actually happened to me once before you can use unicode escape codec to decode the string to unicode and then encode it to any format you want uni text decode unicode escape print type uni type unicode print uni encode utf don like this
|
QA
|
preserving signatures of decorated functions suppose have written decorator that does something very generic for example it might convert all arguments to specific type perform logging implement memoization etc here is an example def args as ints def args kwargs args int for in args kwargs dict int for in kwargs items return args kwargs return args as ints def funny function computes return funny function everything well so far there is one problem however the decorated function does not retain the documentation of the original function help funny function help on function in module main args kwargs fortunately there is workaround def args as ints def args kwargs args int for in args kwargs dict int for in kwargs items return args kwargs name name doc doc return args as ints def funny function computes return this time the function name and documentation are correct help funny function help on function funny function in module main funny function args kwargs computes but there is still problem the function signature is wrong the information args kwargs is next to useless what to do can think of two simple but flawed workarounds include the correct signature in the docstring def funny function funny function computes return this is bad because of the duplication the signature will still not be shown properly in automatically generated documentation it is easy to update the function and forget about changing the docstring or to make typo and yes am aware of the fact that the docstring already duplicates the function body please ignore this funny function is just random example not use decorator or use special purpose decorator for every specific signature def funny functions decorator def return int int int name name doc doc return this works fine for set of functions that have identical signature but it is useless in general as said in the beginning want to be able to use decorators entirely generically am looking for solution that is fully general and automatic so the question is is there way to edit the decorated function signature after it has been created otherwise can write decorator that extracts the function signature and uses that information instead of kwargs kwargs when constructing the decorated function how do extract that information how should construct the decorated function with exec any other approaches
|
take look at the decorator module specifically the decorator decorator which solves this problem
|
QA
|
preserving signatures of decorated functions suppose have written decorator that does something very generic for example it might convert all arguments to specific type perform logging implement memoization etc here is an example def args as ints def args kwargs args int for in args kwargs dict int for in kwargs items return args kwargs return args as ints def funny function computes return funny function everything well so far there is one problem however the decorated function does not retain the documentation of the original function help funny function help on function in module main args kwargs fortunately there is workaround def args as ints def args kwargs args int for in args kwargs dict int for in kwargs items return args kwargs name name doc doc return args as ints def funny function computes return this time the function name and documentation are correct help funny function help on function funny function in module main funny function args kwargs computes but there is still problem the function signature is wrong the information args kwargs is next to useless what to do can think of two simple but flawed workarounds include the correct signature in the docstring def funny function funny function computes return this is bad because of the duplication the signature will still not be shown properly in automatically generated documentation it is easy to update the function and forget about changing the docstring or to make typo and yes am aware of the fact that the docstring already duplicates the function body please ignore this funny function is just random example not use decorator or use special purpose decorator for every specific signature def funny functions decorator def return int int int name name doc doc return this works fine for set of functions that have identical signature but it is useless in general as said in the beginning want to be able to use decorators entirely generically am looking for solution that is fully general and automatic so the question is is there way to edit the decorated function signature after it has been created otherwise can write decorator that extracts the function signature and uses that information instead of kwargs kwargs when constructing the decorated function how do extract that information how should construct the decorated function with exec any other approaches
|
there is decorator module with decorator decorator you can use decorator def args as ints args kwargs args int for in args kwargs dict int for in kwargs items return args kwargs then the signature and help of the method is preserved help funny function help on function funny function in module main funny function computes edit sebastian pointed out that did not modify args as ints function it is fixed now
|
QA
|
preserving signatures of decorated functions suppose have written decorator that does something very generic for example it might convert all arguments to specific type perform logging implement memoization etc here is an example def args as ints def args kwargs args int for in args kwargs dict int for in kwargs items return args kwargs return args as ints def funny function computes return funny function everything well so far there is one problem however the decorated function does not retain the documentation of the original function help funny function help on function in module main args kwargs fortunately there is workaround def args as ints def args kwargs args int for in args kwargs dict int for in kwargs items return args kwargs name name doc doc return args as ints def funny function computes return this time the function name and documentation are correct help funny function help on function funny function in module main funny function args kwargs computes but there is still problem the function signature is wrong the information args kwargs is next to useless what to do can think of two simple but flawed workarounds include the correct signature in the docstring def funny function funny function computes return this is bad because of the duplication the signature will still not be shown properly in automatically generated documentation it is easy to update the function and forget about changing the docstring or to make typo and yes am aware of the fact that the docstring already duplicates the function body please ignore this funny function is just random example not use decorator or use special purpose decorator for every specific signature def funny functions decorator def return int int int name name doc doc return this works fine for set of functions that have identical signature but it is useless in general as said in the beginning want to be able to use decorators entirely generically am looking for solution that is fully general and automatic so the question is is there way to edit the decorated function signature after it has been created otherwise can write decorator that extracts the function signature and uses that information instead of kwargs kwargs when constructing the decorated function how do extract that information how should construct the decorated function with exec any other approaches
|
install decorator module pip install decorator adapt definition of args as ints import decorator decorator decorator def args as ints args kwargs args int for in args kwargs dict int for in kwargs items return args kwargs args as ints def funny function computes return print funny function help funny function help on function funny function in module main funny function computes python functools wraps from stdlib preserves signatures since python import functools def args as ints func functools wraps func def wrapper args kwargs args int for in args kwargs dict int for in kwargs items return func args kwargs return wrapper args as ints def funny function computes return print funny function help funny function help on function funny function in module main funny function computes functools wraps is available at least since python but it does not preserve the signature there help funny function help on function funny function in module main funny function args kwargs computes notice args kwargs instead of
|
QA
|
using or comparisons with if statements when using if statements in python you have to do the following to make the cascade work correctly if job mechanic or job tech print awesome elif job tool or job rock print dolt is there way to make python accept multiple values when checking for equals to for example if job mechanic or tech print awesome elif job tool or rock print dolt
|
if job in mechanic tech print awesome elif job in tool rock print dolt the values in parentheses are tuple the in operator checks to see whether the left hand side item occurs somewhere inside the right handle tuple note that when python searches tuple or list using the in operator it does linear search if you have large number of items on the right hand side this could be performance bottleneck larger scale way of doing this would be to use frozenset awesomejobs frozenset mechanic tech lots of others def func if job in awesomejobs print awesome the use of frozenset over set is preferred if the list of awesome jobs does not need to be changed during the operation of your program
|
QA
|
using or comparisons with if statements when using if statements in python you have to do the following to make the cascade work correctly if job mechanic or job tech print awesome elif job tool or job rock print dolt is there way to make python accept multiple values when checking for equals to for example if job mechanic or tech print awesome elif job tool or rock print dolt
|
if job in mechanic tech print awesome elif job in tool rock print dolt
|
QA
|
using or comparisons with if statements when using if statements in python you have to do the following to make the cascade work correctly if job mechanic or job tech print awesome elif job tool or job rock print dolt is there way to make python accept multiple values when checking for equals to for example if job mechanic or tech print awesome elif job tool or rock print dolt
|
while do not think you can do what you want directly one alternative is if job in mechanic tech print awesome elif job in tool rock print dolt
|
QA
|
using or comparisons with if statements when using if statements in python you have to do the following to make the cascade work correctly if job mechanic or job tech print awesome elif job tool or job rock print dolt is there way to make python accept multiple values when checking for equals to for example if job mechanic or tech print awesome elif job tool or rock print dolt
|
in other languages would use switch select statement to get the job done you can do that in python too
|
QA
|
using or comparisons with if statements when using if statements in python you have to do the following to make the cascade work correctly if job mechanic or job tech print awesome elif job tool or job rock print dolt is there way to make python accept multiple values when checking for equals to for example if job mechanic or tech print awesome elif job tool or rock print dolt
|
you can use in if job in mechanic tech print awesome when checking very large numbers it may also be worth storing off set of the items to check as this will be faster eg awesomejobs set mechanic tech lots of others def func if job in awesomejobs print awesome
|
QA
|
difflib sequencematcher isjunk optional parameter query how to ignore whitespaces tabs empty lines am trying to use difflib sequencematcher to compute the similarities between two files these two files are almost identical except that one contains some extra whitespaces empty lines and other does not am trying to use difflib sequencematcher isjunk text text ratio ratio for this purpose so the question is how to write the lambda expression for this isjunk method so the sequencematcher method will discount all the whitespaces empty lines etc tried to use the parameter lambda but the result is not as great for two closely similar text the ratio is very low this is highly counter intuitive for testing purpose here are the two strings that you can use on testing what motivates jwovu to do your job well ok this is an entry trying to win worth of software development books despite the fact that don read programming books in order to win the prize you have to write an entry and what motivatesfggmum to do your job well hence this post first motivation money know this doesn sound like great inspiration to many and saying that money is one of the motivation factors might just blow my chances away as if money is taboo in programming world know there are people who can be motivated by money mme on the other hand am living in real world with house mortgage to pay myself to feed and bills to cover so can really exclude money from my consideration if can get large sum of money for doing good job then definitely boost my morale won care whether am using an old workstation or forced to share rooms or cubicle with other people or have to put up with an annoying boss or whatever the fact that at the end of the day will walk off with large pile of money itself is enough for me to overcome all the obstacles put up with all the hard feelings and hurt egos tolerate slow computer and even endure and here is another string what motivates you to do your job well ok this is an entry trying to win worth of software development books despite the fact that do not read programming books in order to win the prize you have to write an entry and describes what motivates you to do your job well hence this post first motivation money know this does not sound like great inspiration to many and saying that money is one of the motivation factors might just blow my chances away as if money is taboo in programming world know there are people who cannot be motivated by money kudos to them me on the other hand am living in real world with house mortgage to pay myself to feed and bills to cover so cannot really exclude money from my consideration if can get large sum of money for doing good job then thatwill definitely boost my morale will not care whether am using an old workstation or forced to share rooms or cubicle with other people or have to put up with an annoying boss or whatever the fact that at the end of the day will walk off with large pile of money itself is enough for me to overcome all the obstacles put up with all the hard feelings and hurt egos tolerate slow computer and even endure ran the above command and set the isjunk to lambda the ratio is only
|
given the texts above the test is indeed as suggested difflib sequencematcher lambda in doc doc ratio however to speed up things little you can take advantage of cpython method wrappers difflib sequencematcher contains doc doc ratio this avoids many python function calls
|
QA
|
adding cookie to zsi posts have added cookie support to soappy by overriding httptransport need functionality beyond that of soappy so was planning on moving to zsi but cannot figure out how to put the cookies on the zsi posts made to the service without these cookies the server will think it is an unauthorized request and it will fail how can add cookies from python cookiejar to zsi requests
|
additionally the binding class also allows any header to be added so figured out that can just add cookie header for each cookie need to add this worked well for the code generated by wsdl py just adding the cookies right after the binding is formed in the soap client class adding parameter to the generated class to take in the cookies as dictionary is easy and then they can easily be iterated through and added
|
QA
|
what is the simplest way to offer consume web services in jython have an application for tomcat which needs to offer consume web services since java web services are nightmare xml code generation etc compared with what is possible in python would like to learn from your experience using jython instead of java for offerring consuming web services what have done so far involves adapting http pywebsvcs sourceforge net to jython still get errors namespaces types and so although some of it is succesful for the simplest services
|
have put together more details on how to use webservices in jython using axis read about it here how to script webservices with jython and axis
|
QA
|
caching in urllib is there an easy way to cache things when using urllib that am over looking or do have to roll my own
|
this activestate python recipe might be helpful http code activestate com recipes
|
QA
|
keeping guis responsive during long running tasks keeping the gui responsive while the application does some cpu heavy processing is one of the challenges of effective gui programming here is good discussion of how to do this in wxpython to summarize there are ways use threads use wxyield chunk the work and do it in the idle event handler which method have you found to be the most effective techniques from other frameworks like qt gtk or windows api are also welcome
|
threads they are what always go for because you can do it in every framework you need and once you are used to multi threading and parallel processing in one language framework you are good on all frameworks
|
QA
|
keeping guis responsive during long running tasks keeping the gui responsive while the application does some cpu heavy processing is one of the challenges of effective gui programming here is good discussion of how to do this in wxpython to summarize there are ways use threads use wxyield chunk the work and do it in the idle event handler which method have you found to be the most effective techniques from other frameworks like qt gtk or windows api are also welcome
|
working with qt for win we divide the major work units into different processes the gui runs as separate process and is able to command receive data from the worker processes as needed works nicely in todays multi core world
|
QA
|
keeping guis responsive during long running tasks keeping the gui responsive while the application does some cpu heavy processing is one of the challenges of effective gui programming here is good discussion of how to do this in wxpython to summarize there are ways use threads use wxyield chunk the work and do it in the idle event handler which method have you found to be the most effective techniques from other frameworks like qt gtk or windows api are also welcome
|
threads or processes depending on the application sometimes it is actually best to have the gui be it is own program and just send asynchronous calls to other programs when it has work to do you will still end up having multiple threads in the gui to monitor for results but it can simplify things if the work being done is complex and not directly connected to the gui
|
QA
|
is there way to define which fields in the model are editable in the admin app assume the following models py class entry models model title models charfield max length slug models charfield max length unique true body models charfield max length admin py class entryadmin admin modeladmin prepopulated fields slug title want the slug to be pre populated by the title but do not want the user to be able to edit it from the admin assumed that adding the fields to the admin object and not including the slug would have worked but it did not also tried setting editable false in the model but that also did not work infact stops the page from rendering thoughts
|
am not sure what you are asking for is possible your best bet is probably to hide the slug from the admin interface completely by specifying your fieldsets and than overriding the save method to copy the slug from the tile and potentially slugifying it
|
QA
|
keeping guis responsive during long running tasks keeping the gui responsive while the application does some cpu heavy processing is one of the challenges of effective gui programming here is good discussion of how to do this in wxpython to summarize there are ways use threads use wxyield chunk the work and do it in the idle event handler which method have you found to be the most effective techniques from other frameworks like qt gtk or windows api are also welcome
|
this answer does not apply to the op question regarding python but is more of meta response the easy way is threads however not every platform has pre emptive threading brew some other embedded systems if possibly simply chunk the work and do it in the idle event handler another problem with using threads in brew is that it does not clean up stack objects so it is way too easy to leak memory if you simply kill the thread
|
QA
|
keeping guis responsive during long running tasks keeping the gui responsive while the application does some cpu heavy processing is one of the challenges of effective gui programming here is good discussion of how to do this in wxpython to summarize there are ways use threads use wxyield chunk the work and do it in the idle event handler which method have you found to be the most effective techniques from other frameworks like qt gtk or windows api are also welcome
|
use threads so the gui main event loop never blocks
|
QA
|
keeping guis responsive during long running tasks keeping the gui responsive while the application does some cpu heavy processing is one of the challenges of effective gui programming here is good discussion of how to do this in wxpython to summarize there are ways use threads use wxyield chunk the work and do it in the idle event handler which method have you found to be the most effective techniques from other frameworks like qt gtk or windows api are also welcome
|
for some types of operations using separate processes makes lot of sense back in the day spawning process incurred lot of overhead with modern hardware this overhead is hardly even blip on the screen this is especially true if you are spawning long running process one arguable advantage is that it is simpler conceptual model than threads that might lead to more maintainable code it can also make your code easier to test as you can write test scripts that exercise these external processes without having to involve the gui some might even argue that is the primary advantage in the case of some code once worked on switching from threads to separate processes led to net reduction of over lines of code while at the same time making the gui more responsive the code easier to maintain and test all while improving the total overall performance
|
QA
|
caching in urllib is there an easy way to cache things when using urllib that am over looking or do have to roll my own
|
if you do not mind working at slightly lower level httplib http code google com httplib is an excellent http library that includes caching functionality
|
QA
|
is there way to define which fields in the model are editable in the admin app assume the following models py class entry models model title models charfield max length slug models charfield max length unique true body models charfield max length admin py class entryadmin admin modeladmin prepopulated fields slug title want the slug to be pre populated by the title but do not want the user to be able to edit it from the admin assumed that adding the fields to the admin object and not including the slug would have worked but it did not also tried setting editable false in the model but that also did not work infact stops the page from rendering thoughts
|
this django snippet does what you want by defining custom read only widget so you define custom editor for the field which in fact does not allow any editing
|
QA
|
keeping guis responsive during long running tasks keeping the gui responsive while the application does some cpu heavy processing is one of the challenges of effective gui programming here is good discussion of how to do this in wxpython to summarize there are ways use threads use wxyield chunk the work and do it in the idle event handler which method have you found to be the most effective techniques from other frameworks like qt gtk or windows api are also welcome
|
definitely threads why the future is multi core almost any new cpu has more than one core or if it has just one it might support hyperthreading and thus pretending it has more than one to effectively make use of multi core cpus and intel is planing to go up to cores in the not so far future you need multiple threads if you run all in one main thread usually the ui thread is the main thread users will have cpus with and one day cores and your application never uses more than one of these iow it runs much much slower than it could run actual if you plan an application nowadays would go away of the classical design and think of master slave relationship your ui is the master it is only task is to interact with the user that is displaying data to the user and gathering user input whenever you app needs to process any data even small amounts and much more important big ones create task of any kind forward this task to background thread and make the thread perform the task providing feedback to the ui how many percent it has completed or just if the task is still running or not so the ui can show work in progress indicator if possible split the task into many small independent sub tasks and run more than one background process feeding one sub task to each of them that way your application can really benefit from multi core and get faster the more cores cpus have actually companies like apple and microsoft are already planing on how to make their still most single threaded uis themselves multithreaded even with the approach above you may one day have the situation that the ui is the bottleneck itself the background processes can process data much faster than the ui can present it to the user or ask the user for input today many ui frameworks are little thread safe many not thread safe at all but that will change serial processing doing one task after another is dying design parallel processing doing many task at once is where the future goes just look at graphic adapters even the most modern nvidia card has pitiful performance if you look at the processing speed in mhz ghz of the gpu alone how comes it can beat the crap out of cpus when it comes to calculations simple instead of calculating one polygon point or one texture pixel after another it calculates many of them in parallel actually whole bunch at the same time and that way it reaches throughput that still makes cpus cry the ati to name the competitor as well has shader units
|
QA
|
is there way to define which fields in the model are editable in the admin app assume the following models py class entry models model title models charfield max length slug models charfield max length unique true body models charfield max length admin py class entryadmin admin modeladmin prepopulated fields slug title want the slug to be pre populated by the title but do not want the user to be able to edit it from the admin assumed that adding the fields to the admin object and not including the slug would have worked but it did not also tried setting editable false in the model but that also did not work infact stops the page from rendering thoughts
|
for this particular case you can override your save method to slugify it is built in method look at django source the title and store it in slug field also from there you can easily check if this slug is indeed unique and change it somehow if it is not consider this example def save self from django template defaultfilters import slugify if not self slug self slug slugify self title super your model name self save
|
QA
|
background tasks on appengine how to run background tasks on appengine
|
gae is very useful tool to build scalable web applications few of the limitations pointed out by many are no support for background tasks lack of periodic tasks and strict limit on how much time each http request takes if request exceeds that time limit the operation is terminated which makes running time consuming tasks impossible how to run background task in gae the code is executed only when there is http request there is strict time limit think secs on how long the code can take so if there are no requests then code is not executed one of the suggested work around was use an external box to send requests continuously so kind of creating background task but for this we need an external box and now we dependent on one more element the other alternative was sending redirect response so that client re sends the request this also makes us dependent on external element which is client what if that external box is gae itself everyone who has used functional language which does not support looping construct in the language is aware of the alternative ie recursion is the replacement to loop so what if we complete part of the computation and do http get on the same url with very short time out say second this creates loop recursion on php code running on apache php if isset request request sleep ch curl init http localhost server php self curl setopt ch curlopt header curl setopt ch curlopt timeout curl exec ch print hello world some how this does not work on gae so what if we do http get on some other url say url which does http get on the first url this seem to work in gae code for this looks like this class firsturl webapp requesthandler def get self self response out write ok time sleep urlfetch fetch http self request headers host url class secondurl webapp requesthandler def get self self response out write ok time sleep urlfetch fetch http self request headers host url application webapp wsgiapplication url firsturl url secondurl def main run wsgi app application if name main main since we found out way to run background task let us build abstractions for periodic task timer and looping construct which spans across many http requests foreach timer now building timer is straight forward basic idea is to have list of timers and the interval at which each should be called once we reach that interval call the callback function we will use memcache to maintain the timer list to find out when to call callback we will store key in memcache with interval as expiration time we periodically say secs check if that key is present if not present then call the callback and again set that key with interval def timer func interval timerlist memcache get timer if none timerlist timerlist timerlist append func func interval interval memcache set timer func interval memcache set timer timerlist def checktimers timerlist memcache get timer if none timerlist return false for current in timerlist if none memcache get timer current func reset interval memcache set timer current func current interval invoke callback function try eval current func except pass return true return false foreach this is needed when we want to do long taking computation say doing some operation on database rows or fetch urls etc basic idea is to maintain list of callbacks and arguments in memcache and each time invoke callback with the argument def foreach func args looplist memcache get foreach if none looplist looplist looplist append func func args args memcache set foreach looplist def checkloops looplist memcache get foreach if none looplist return false if len looplist and len looplist args arg looplist args pop func looplist func if len looplist args looplist pop if len looplist and len looplist args memcache set foreach looplist else memcache delete foreach try eval func repr arg except pass return true else return false instead of foreach index in range someoperaton index we will say foreach someoperaton range now building program which fetches list of urls every one hour is straight forward here is the code def getone url try result urlfetch fetch url if result status code memcache set url process result content except pass def getallurl list of urls to be fetched urllist http www google com http www cnn com http www yahoo com http news google com fetchlist for url in urllist if memcache get url is none fetchlist append url this is equivalent to for url in fetchlist getone url if len fetchlist foreach getone fetchlist register the timer callback timer getallurl complete code is here http groups google com group httpmr discuss aa have been running this code on appengine for few days without much problem warning we make heavy use of urlfetch the limit on no of urlfetch per day is so be careful not to reach that limit
|
QA
|
python on windows how to wait for multiple child processes how to wait for multiple child processes in python on windows without active wait polling something like this almost works for me proc subprocess popen python mytest py proc subprocess popen python mytest py proc wait print finished proc wait print finished the problem is that when proc finishes before proc the parent process will still wait for proc on unix one would use waitpid in loop to get the child processes return codes as they finish how to achieve something like this in python on windows
|
twisted on windows will perform an active wait under the covers if you do not want to use threads you will have to use the win api to avoid polling something like this import win process import win event note createprocess args are somewhat cryptic look them up on msdn proc thread pid tid win process createprocess proc thread pid tid win process createprocess thread close thread close processes proc proc proc proc while processes handles processes keys note waitformultipleobjects supports at most processes at time index win event waitformultipleobjects handles false win event infinite finished handles index exitcode win process getexitcodeprocess finished procname processes pop finished finished close print subprocess finished with exit code procname exitcode
|
QA
|
using or comparisons with if statements when using if statements in python you have to do the following to make the cascade work correctly if job mechanic or job tech print awesome elif job tool or job rock print dolt is there way to make python accept multiple values when checking for equals to for example if job mechanic or tech print awesome elif job tool or rock print dolt
|
tuples with constant items are stored themselves as constants in the compiled function they can be loaded with single instruction lists and sets on the other hand are always constructed anew on each execution both tuples and lists use linear search for the in operator sets uses hash based look up so it will be faster for larger number of options
|
QA
|
beautifulsoup python compatibility does beautifulsoup work with python if not how soon will there be port will there be port at all google does not turn up anything to me maybe it is because am looking for the wrong thing
|
am guessing the answer is no according to python org python py and released as python is new version of the language that is incompatible with the line of releases the language is mostly the same but many details especially how built in objects like dictionaries and strings work have changed considerably and lot of deprecated features have finally been removed also the standard library has been reorganized in few prominent places better place for this particular question might be the beautifulsoup forum
|
QA
|
python desktop widgets am interested in making desktop widgets similar to apple dashboard or what vista has would like to make them cross platform if possible opera widgets are cross platform but require the user to have opera installed so that is big limitation know most widgets are made with html xml css and javascript is there way to create them using python update did find site talking about pyjamas does anyone have experience with it and if so what are its capabilities limitations
|
you can check out pygtk which will allow you to create desktop widgets but they will not be managed by osx dashboard if you would like to develop an osx widget you will want to stick with html css javascript
|
QA
|
python desktop widgets am interested in making desktop widgets similar to apple dashboard or what vista has would like to make them cross platform if possible opera widgets are cross platform but require the user to have opera installed so that is big limitation know most widgets are made with html xml css and javascript is there way to create them using python update did find site talking about pyjamas does anyone have experience with it and if so what are its capabilities limitations
|
take look at pyqt it has webkit integration was looking into this myself but have not really had time to dig into the api
|
QA
|
django vmware appliance does anyone know of django postgresql apache mod python vmware appliance vanilla django appliance where postgresql can be installed manually would also do
|
poulsenj is right the elastic server on demand django elastic server site is great place to configure and download free custom django vmware image in minutes the elastic server platform let us you assemble custom servers by choosing components from library of popular software stacks once assembled these custom application stacks can be configured to variety of virtualization and cloud ready formats downloaded and deployed in real time
|
QA
|
python desktop widgets am interested in making desktop widgets similar to apple dashboard or what vista has would like to make them cross platform if possible opera widgets are cross platform but require the user to have opera installed so that is big limitation know most widgets are made with html xml css and javascript is there way to create them using python update did find site talking about pyjamas does anyone have experience with it and if so what are its capabilities limitations
|
you should take look at what the guys at digsby are doing basically they have written port of webkit to wxwidgets and then use webkit to render the interface and wxpython for writing the rest of the app pretty neat but very alpha at the moment
|
QA
|
python desktop widgets am interested in making desktop widgets similar to apple dashboard or what vista has would like to make them cross platform if possible opera widgets are cross platform but require the user to have opera installed so that is big limitation know most widgets are made with html xml css and javascript is there way to create them using python update did find site talking about pyjamas does anyone have experience with it and if so what are its capabilities limitations
|
take look at gdesklets afaik they are unix only but mabybe porting them to other platforms make more sense than starting from scratch they use python to create widgets desklets
|
QA
|
caching in urllib is there an easy way to cache things when using urllib that am over looking or do have to roll my own
|
you could use decorator function such as class cache object def init self fun self fun fun self cache def call self args kwargs key str args str kwargs try return self cache key except keyerror self cache key rval self fun args kwargs return rval except typeerror incase key is not valid key do not cache return self fun args kwargs and define function along the lines of cache def get url src url return urllib urlopen url read this is assuming you are not paying attention to http cache controls but just want to cache the page for the duration of the application
|
QA
|
has anyone found good set of python plugins for vim specifically module completion am looking for suite of plugins that can help me finally switch over to vim full time right now am using komodo with some good success but their vim bindings have enough little errors that am tired of it what do love in komodo though is the code completion so here is what am looking for ordered by importance code completion meaning the ability to code complete modules functions etc in any module that is on the pythonpath not just system modules bonus points for showing docstrings when completing jump to class definition am guessing ctags will do this so how do you all manage automatically updating your tags files project type management for managing buffers ideally the ability to grep for filename in directory structure to open it bonus for showing an index of class definitions while buffer is open bzr integration not super important since most of it can just drop to the she will to do
|
code completion pysmell looks promising it is work in progress but alredy useful
|
QA
|
keeping guis responsive during long running tasks keeping the gui responsive while the application does some cpu heavy processing is one of the challenges of effective gui programming here is good discussion of how to do this in wxpython to summarize there are ways use threads use wxyield chunk the work and do it in the idle event handler which method have you found to be the most effective techniques from other frameworks like qt gtk or windows api are also welcome
|
threads let us use simple layer view gui application logic the application logic work should be done in separate python thread for asynchronous events that need to propagate up to the gui layer use wx event system to post custom events posting wx events is thread safe so you could conceivably do it from multiple contexts working in the other direction gui input events triggering application logic have found it best to home roll custom event system use the queue module to have thread safe way of pushing and popping event objects then for every synchronous member function pair it with an async version that pushes the sync function object and the parameters onto the event queue this works particularly well if only single application logic level operation can be performed at time the benefit of this model is that synchronization is simple each synchronous function works within it is own context sequentially from start to end without worry of pre emption or hand coded yielding you will not need locks to protect your critical sections at the end of the function post an event to the gui layer indicating that the operation is complete you could scale this to allow multiple application level threads to exist but the usual concerns with synchronization will re appear edit forgot to mention the beauty of this is that it is possible to completely decouple the application logic from the gui code the modularity helps if you ever decide to use different framework or use provide command line version of the app to do this you will need an intermediate event dispatcher application level gui that is implemented by the gui layer
|
QA
|
is there way to define which fields in the model are editable in the admin app assume the following models py class entry models model title models charfield max length slug models charfield max length unique true body models charfield max length admin py class entryadmin admin modeladmin prepopulated fields slug title want the slug to be pre populated by the title but do not want the user to be able to edit it from the admin assumed that adding the fields to the admin object and not including the slug would have worked but it did not also tried setting editable false in the model but that also did not work infact stops the page from rendering thoughts
|
this snippet gives you an autoslugfield with exactly the behavior you are seeking and adding it to your model is one liner
|
QA
|
is there way to define which fields in the model are editable in the admin app assume the following models py class entry models model title models charfield max length slug models charfield max length unique true body models charfield max length admin py class entryadmin admin modeladmin prepopulated fields slug title want the slug to be pre populated by the title but do not want the user to be able to edit it from the admin assumed that adding the fields to the admin object and not including the slug would have worked but it did not also tried setting editable false in the model but that also did not work infact stops the page from rendering thoughts
|
in addition to overriding save to provide the generated value you want you can also use the exclude option in your modeladmin class to prevent the field from being displayed in the admin class entryadmin admin modeladmin exclude slug
|
QA
|
what is the difference between reduce and reduce ex understand that these methods are for pickling unpickling and have no relation to the reduce built in function but what is the difference between the and why do we need both
|
the docs say that if provided at pickling time reduce will be called with no arguments and it must return either string or tuple on the other hand it is sometimes useful to know the protocol version when implementing reduce this can be done by implementing method named reduce ex instead of reduce reduce ex when it exists is called in preference over reduce you may still provide reduce for backwards compatibility the reduce ex method will be called with single integer argument the protocol version on the gripping hand guido says that this is an area that could be cleaned up
|
QA
|
what is the difference between reduce and reduce ex understand that these methods are for pickling unpickling and have no relation to the reduce built in function but what is the difference between the and why do we need both
|
reduce ex is what reduce should have been but never became reduce ex works like reduce but the pickle protocol is passed
|
QA
|
how do you break into the debugger from python source code what do you insert into python source code to have it break into pdb when execution gets to that spot
|
import pdb pdb set trace see python coding in the debugger for beginners for this and more helpful hints
|
QA
|
has anyone found good set of python plugins for vim specifically module completion am looking for suite of plugins that can help me finally switch over to vim full time right now am using komodo with some good success but their vim bindings have enough little errors that am tired of it what do love in komodo though is the code completion so here is what am looking for ordered by importance code completion meaning the ability to code complete modules functions etc in any module that is on the pythonpath not just system modules bonus points for showing docstrings when completing jump to class definition am guessing ctags will do this so how do you all manage automatically updating your tags files project type management for managing buffers ideally the ability to grep for filename in directory structure to open it bonus for showing an index of class definitions while buffer is open bzr integration not super important since most of it can just drop to the she will to do
|
use pydoc vim actually wrote it lot try it and tell me what you think another one that think is quite useful is the updated syntax file with all it is extensions that you can enable which you can find here
|
QA
|
how do manipulate bits in python in could for example zero out bit in bit unsigned value like so unsigned long value xdeadbeef value how do do that in python
|
if you are going to do lot of bit manipulation and you care much more about readability rather than performance for your application then you may want to create an integer wrapper to enable slicing like in verilog or vhdl import math class bitvector def init self val self val val def setslice self highindx lowindx newval assert math ceil math log newval math log highindx lowindx clear out bit slice clean mask highindx lowindx self val self val self val clean mask set new value self val self val newval lowindx def getslice self highindx lowindx return self val lowindx highindx lowindx bitvector xd xe xa xd for in xrange print outputs
|
QA
|
how does one read bytes from file in python similar to this question am trying to read in an id tag header and am having trouble figuring out how to get individual bytes in python first read all ten bytes into string then want to parse out the individual pieces of information can grab the two version number chars in the string but then have no idea how to take those two chars and get an integer out of them the struct package seems to be what want but cannot get it to work here is my code so far am very new to python by the way so take it easy on me def init self ten byte string self whole string ten byte string self file identifier self whole string self major version struct pack self whole string this self minor version struct pack self whole string and this self flags self whole string self len self whole string printing out any value except is obviously crap because they are not formatted correctly
|
was going to recommend the struct package but then you said you had tried it try this self major version struct unpack self whole string the pack function convers python data types to bits and the unpack function converts bits to python data types
|
QA
|
how does one read bytes from file in python similar to this question am trying to read in an id tag header and am having trouble figuring out how to get individual bytes in python first read all ten bytes into string then want to parse out the individual pieces of information can grab the two version number chars in the string but then have no idea how to take those two chars and get an integer out of them the struct package seems to be what want but cannot get it to work here is my code so far am very new to python by the way so take it easy on me def init self ten byte string self whole string ten byte string self file identifier self whole string self major version struct pack self whole string this self minor version struct pack self whole string and this self flags self whole string self len self whole string printing out any value except is obviously crap because they are not formatted correctly
|
if you have string with bytes that you wish to interpret as bit integer you can do so by struct unpack note that the is for big endian the largest part of the integer comes first this is the format id tags use for other sizes of integer you use different format codes eg for signed bit integer see help struct for details you can also unpack several elements at once eg for unsigned shorts followed by signed bit value struct unpack hhi some string going by your code you are looking for in order char string single byte values major and minor version byte flags variable bit length quantity the format string for this would be ident major minor flags len struct unpack sbbbi ten byte string
|
QA
|
how does one read bytes from file in python similar to this question am trying to read in an id tag header and am having trouble figuring out how to get individual bytes in python first read all ten bytes into string then want to parse out the individual pieces of information can grab the two version number chars in the string but then have no idea how to take those two chars and get an integer out of them the struct package seems to be what want but cannot get it to work here is my code so far am very new to python by the way so take it easy on me def init self ten byte string self whole string ten byte string self file identifier self whole string self major version struct pack self whole string this self minor version struct pack self whole string and this self flags self whole string self len self whole string printing out any value except is obviously crap because they are not formatted correctly
|
why write your own assuming you have not checked out these other options there is couple options out there for reading in id tag info from mp in python check out my answer over at this question
|
QA
|
how does one read bytes from file in python similar to this question am trying to read in an id tag header and am having trouble figuring out how to get individual bytes in python first read all ten bytes into string then want to parse out the individual pieces of information can grab the two version number chars in the string but then have no idea how to take those two chars and get an integer out of them the struct package seems to be what want but cannot get it to work here is my code so far am very new to python by the way so take it easy on me def init self ten byte string self whole string ten byte string self file identifier self whole string self major version struct pack self whole string this self minor version struct pack self whole string and this self flags self whole string self len self whole string printing out any value except is obviously crap because they are not formatted correctly
|
am trying to read in an id tag header fwiw there is already module for this
|
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
|
more general and simpler solution which allows non paired quotes find quoted string replace by in the string usr bin env python import re text axbx cxdxe fxgh ixj re sub lambda re sub group text print axbx cpdpe fxgh ipj true axbx cpdpe fxgh ipj
|
QA
|
is there any visual library alternative to wxpython that supports css style sheets have developed program that extensively uses wxpython the wxwindow port for python even though it is as mature library it is still very primitive and very programming oriented which is time consuming and not flexible at all would love to see if there is something like flex action script where all the visual dimensions are configured by style sheets any thoughts thanks
|
you could try xul the language the firefox gui uses it is xml styled with css and scripted with javascript http www mozilla org projects xul http en wikipedia org wiki xul http developer mozilla org en xul
|
QA
|
is there any visual library alternative to wxpython that supports css style sheets have developed program that extensively uses wxpython the wxwindow port for python even though it is as mature library it is still very primitive and very programming oriented which is time consuming and not flexible at all would love to see if there is something like flex action script where all the visual dimensions are configured by style sheets any thoughts thanks
|
pyqt with qt style sheets might be good fit naturally you would need to re write quite bit of your gui layer for the toolkit change
|
QA
|
prototyping with python code before compiling have been mulling over writing peak fitting library for while know python fairly well and plan on implementing everything in python to begin with but envisage that may have to re implement some core routines in compiled language eventually iirc one of python original remits was as prototyping language however python is pretty liberal in allowing functions functors objects to be passed to functions and methods whereas suspect the same is not true of say or fortran what should know about designing functions classes which envisage will have to interface into the compiled language and how much of these potential problems are dealt with by libraries such as ctypes bgen swig boost python cython or python sip for this particular use case fitting library imagine allowing users to define mathematical functions guassian lorentzian etc as python functions which can then to be passed an interpreted by the compiled code fitting library passing and returning arrays is also essential
|
py part of numpy is simpler alternative to swig and boost python for wrapping fortran number crunching code
|
QA
|
prototyping with python code before compiling have been mulling over writing peak fitting library for while know python fairly well and plan on implementing everything in python to begin with but envisage that may have to re implement some core routines in compiled language eventually iirc one of python original remits was as prototyping language however python is pretty liberal in allowing functions functors objects to be passed to functions and methods whereas suspect the same is not true of say or fortran what should know about designing functions classes which envisage will have to interface into the compiled language and how much of these potential problems are dealt with by libraries such as ctypes bgen swig boost python cython or python sip for this particular use case fitting library imagine allowing users to define mathematical functions guassian lorentzian etc as python functions which can then to be passed an interpreted by the compiled code fitting library passing and returning arrays is also essential
|
python is pretty liberal in allowing functions functors objects to be passed to functions and methods whereas suspect the same is not true of say or fortran in you cannot pass function as an argument to function but you can pass function pointer which is just as good function do not know how much that would help when you are trying to integrate and python code but just wanted to clear up one misconception
|
QA
|
how do calculate number of days betwen two dates using python if have two dates ex and what is the best way to get the difference measured in days
|
if you have two date objects you can just subtract them from datetime import date date date delta print delta days the relevant section of the docs https docs python org library datetime html
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.