prefix
stringclasses 1
value | input_text
stringlengths 19
27.3k
⌀ | target_text
stringlengths 2
24.8k
⌀ |
---|---|---|
QA
|
how to copy all properties of an object to another object in python is there library method to copy all the properties between two already present instances of the same class in python mean something like apache commons propertyutilsbean copyproperties thanks
|
try destination dict update source dict
|
QA
|
map two lists into one single list of dictionaries imagine have these python lists keys name age values monty matt frank is there direct or at least simple way to produce the following list of dictionaries name monty age name matt age name frank age
|
it is not pretty but here is one liner using list comprehension zip and stepping dict zip keys for in zip values values
|
QA
|
how to copy all properties of an object to another object in python is there library method to copy all the properties between two already present instances of the same class in python mean something like apache commons propertyutilsbean copyproperties thanks
|
know you down modded copy but disagree it is more clear to make another copy than to modify the existing in place with dict manipulation as others suggested if you lose existing copy by reassigning the variable it will get garbage collected immediately python is not meant to be fast it is meant to be readable though actually believe that copy will be faster than the other methods
|
QA
|
ajax console window with ansi vt support am planning to write gateway web application which would need terminal window with vt ansi escape code support are there any ajax based alternatives for such task am thinking something like this http tryruby hobix com my preferred backend for the system is python twisted pylons but since am just planning will explore every option
|
ajaxterm has terminal with mostly felicitous terminal emulation done on the python backend it just pushes display updates to the client javascript the ajaxterm website has been down for some time but you can still find it packaged in debian
|
QA
|
ajax console window with ansi vt support am planning to write gateway web application which would need terminal window with vt ansi escape code support are there any ajax based alternatives for such task am thinking something like this http tryruby hobix com my preferred backend for the system is python twisted pylons but since am just planning will explore every option
|
try anyterm ajaxterm webshell
|
QA
|
what would you recommend for high traffic ajax intensive website for website like reddit with lots of up down votes and lots of comments per topic what should go with lighttpd php or lighttpd cherrypy genshi sqlalchemy and for database what would scale better be fastest mysql or or postgresql
|
would go with nginx php xcache postgresql
|
QA
|
what is the ocaml idiom equivalent to python range function want to create list of integers from to can do this in python using range and in haskell using take iterate what is the right ocaml idiom for this
|
by the way in haskell you would rather use enumfromto these are just unnecessary take take iterate
|
QA
|
with lua and python embeddable is there place for basic started off programming in basic on the zx then basica gw basic and qbasic moved on to ah turbo hardly knew ye when got started in microcontrollers regressed with the basic stamp from parallax however basic is was awesome because it was so easy to understand and so hard to make mistake moved on to assembly and eventually because needed the additional power speed capacity resources etc but know that if the bar was much higher many people would never get into programming microcontrollers keep getting an itch to make my own on chip basic interpretor but wonder if there is need for basic now that lua and python are easily embeddable and just as approachable as basic what if any are the advantages basic has over other languages why is it still around if decide to make general purpose microcontroller board with an interpreter is there any reason to make version of basic plenty of other languages are considered dead but basic just keeps hanging on
|
well these people seem to think that not only basic still has place in the mobile space but also that they can make money off it http www nsbasic com symbian
|
QA
|
how do merge two python iterators have two iterators list and an itertools count object an infinite value generator would like to merge these two into resulting iterator that will alternate yield values between the two import itertools itertools count items foo bar merged imerge items the mythical imerge merged next foo merged next merged next bar merged next merged next traceback most recent call last stopiteration what is the simplest most concise way to do this
|
why is itertools needed def imerge for in zip yield yield in this case at least one of or must be of finite length because zip will return list not an iterator if you need an iterator as output then you can go for the claudiu solution
|
QA
|
which eclipse package to download for pydev am getting started with python eclipse and pydev which eclipse package should choose nothing on the eclipse homepage tells me what to choose and python documentation assumes have eclipse installed does which package choose matter
|
pydev was acquired by aptana so you might want to check that one out as well
|
QA
|
how do merge two python iterators have two iterators list and an itertools count object an infinite value generator would like to merge these two into resulting iterator that will alternate yield values between the two import itertools itertools count items foo bar merged imerge items the mythical imerge merged next foo merged next merged next bar merged next merged next traceback most recent call last stopiteration what is the simplest most concise way to do this
|
am not sure what your application is but you might find the enumerate function more useful items foo bar baz for item in enumerate items print item print foo bar baz
|
QA
|
unicode block of character in python is there way to get the unicode block of character in python the unicodedata module does not seem to have what need and could not find an external library for it basically need the same functionality as character unicodeblock of in java
|
could not find one either strange luckily the number of unicode blocks is quite manageably small this implementation accepts one character unicode string just like the functions in unicodedata if your inputs are mostly ascii this linear search might even be faster than binary search using bisect or whatever if were submitting this for inclusion in the python standard library would probably write it as binary search through an array of statically initialized structs in def block ch return the unicode block name for ch or none if ch has no block block you basic latin block unichr tamil block unichr xe assert isinstance ch unicode and len ch repr ch cp ord ch for start end name in blocks if start cp end return name def initblocks text global blocks blocks import re pattern re compile for line in text splitlines pattern match line if start end name groups blocks append int start int end name retrieved from http unicode org public unidata blocks txt initblocks blocks txt date pdt kw unicode character database copyright unicode inc for terms of use see http www unicode org terms of use html for documentation see ucd html note the casing of block names is not normative for example basic latin and basic latin are equivalent format start code end code block name note when comparing block names casing whitespace hyphens and underbars are ignored for example latin extended and latin extended are equivalent for more information on the comparison of property values see ucd html all code points not explicitly listed for block have the value no block property block missing ffff no block basic latin ff latin supplement latin extended latin extended af ipa extensions ff spacing modifier letters combining diacritical marks ff greek and coptic ff cyrillic cyrillic supplement armenian ff hebrew ff arabic syriac arabic supplement bf thaana ff nko devanagari ff bengali gurmukhi aff gujarati oriya bff tamil telugu cff kannada malayalam dff sinhala thai eff lao fff tibetan myanmar ff georgian ff hangul jamo ethiopic ethiopic supplement ff cherokee unified canadian aboriginal syllabics ogham ff runic tagalog hanunoo buhid tagbanwa ff khmer af mongolian limbu tai le df new tai lue ff khmer symbols buginese balinese bbf sundanese lepcha old chiki phonetic extensions dbf phonetic extensions supplement dc dff combining diacritical marks supplement eff latin extended additional fff greek extended general punctuation superscripts and subscripts cf currency symbols ff combining diacritical marks for symbols letterlike symbols number forms ff arrows ff mathematical operators ff miscellaneous technical control pictures optical character recognition ff enclosed alphanumerics box drawing block elements ff geometric shapes ff miscellaneous symbols bf dingbats ef miscellaneous mathematical symbols ff supplemental arrows ff braille patterns supplemental arrows ff miscellaneous mathematical symbols aff supplemental mathematical operators bff miscellaneous symbols and arrows glagolitic latin extended cff coptic georgian supplement tifinagh ddf ethiopic extended de dff cyrillic extended supplemental punctuation eff cjk radicals supplement fdf kangxi radicals ff fff ideographic description characters cjk symbols and punctuation hiragana ff katakana bopomofo hangul compatibility jamo kanbun bf bopomofo extended ef cjk strokes ff katakana phonetic extensions ff enclosed cjk letters and months ff cjk compatibility dbf cjk unified ideographs extension dc dff yijing hexagram symbols fff cjk unified ideographs yi syllables cf yi radicals vai cyrillic extended modifier tone letters ff latin extended syloti nagri phags pa df saurashtra kayah li rejang aa aa cham ac af hangul syllables db high surrogates db dbff high private use surrogates dc dfff low surrogates ff private use area faff cjk compatibility ideographs fb fb alphabetic presentation forms fb fdff arabic presentation forms fe fe variation selectors fe fe vertical forms fe fe combining half marks fe fe cjk compatibility forms fe fe small form variants fe feff arabic presentation forms ff ffef halfwidth and fullwidth forms fff ffff specials linear syllabary ff linear ideograms aegean numbers ancient greek numbers cf ancient symbols ff phaistos disc lycian df carian old italic gothic ugaritic df old persian deseret shavian af osmanya cypriot syllabary phoenician lydian kharoshthi ff cuneiform cuneiform numbers and punctuation ff byzantine musical symbols ff musical symbols ancient greek musical notation tai xuan jing symbols counting rod numerals ff mathematical alphanumeric symbols mahjong tiles domino tiles df cjk unified ideographs extension fa cjk compatibility ideographs supplement tags ef variation selectors supplement fffff supplementary private use area ffff supplementary private use area eof
|
QA
|
upgrading google application engine program to use unicode have simple google app engine app that wrote using ordinary strings realize want to make it handle unicode are there any gotchas with this am thinking of all the strings that currently already have in the live database from real users who do not want to upset
|
the datastore internally keeps all strings in unicode
|
QA
|
upgrading google application engine program to use unicode have simple google app engine app that wrote using ordinary strings realize want to make it handle unicode are there any gotchas with this am thinking of all the strings that currently already have in the live database from real users who do not want to upset
|
alexander kojevnikov said the datastore internally keeps all strings in unicode in other words your application is already using unicode everywhere thank the google folks for sensible api no further work required
|
QA
|
porting matlab functions to scilab how do use symbolic am porting some matlab functions to scilab the cool thing is that there is conversion toolbox that make things very easy the problem is did not find the counterpart to the syms function and the symbolic toolbox in general would like port of the control system toolbox too amd am still searching for some functions would may need the only thing about symbolic toolbox have found is this but it was little trcky and not so easy actually was not able to set up it correctly in minutes and gave up for now am going to try later and it needs maxima to be installed does anyone know anything about that scilab is not exactly must the project aims to give more free and open source alternative to matlab saw there is sympy for python and just could use it with scipy but would lost the conversion toolbox thing that said what should be better get scilab and maxima work together or move to python co this is the start of the project so the earlier choose this the better
|
not to discourage your project but if you just want free and open source alternative to matlab have you looked at the octave project contributing there might be more productive than building your own matlab alternative if your project requires the functionality of matlab symbolic then take look at http wiki octave org wiki pl categorysymbolic from my quick google search did not find anything comparable to matlab simulink also python and scipy do have most of the functionality of matlab and guess scilab conversion utility would be useful in porting your own files into scilab code your question seems to imply you want to port over matlab toolboxes the only thing about symbolic toolbox have found is this hope am just misinterpreting you if you are then there might be licensing issues if you were to distribute your system because the matlab toolbox just thought but perhaps you wish to port your matlab code to so that it does not not have the matlab dependency update for control system functionality octave just found that octave does have toolbox see octave control systems toolbox which has some of the functionality of simulink but it does not seem to have the graphical interface for building block diagrams
|
QA
|
what are first class objects when are objects or something else said to be first class in given programming language and why in what do they differ from languages where they are not edit when one says everything is an object like in python does he indeed mean that everything is first class
|
in short it means there are no restrictions on the object use it is the same as any other object first class object is an entity that can be dynamically created destroyed passed to function returned as value and have all the rights as other variables in the programming language have depending on the language this can imply being expressible as an anonymous literal value being storable in variables being storable in data structures having an intrinsic identity independent of any given name being comparable for equality with other entities being passable as parameter to procedure function being returnable as the result of procedure function being constructible at runtime being printable being readable being transmissible among distributed processes being storable outside running processes source in functions themselves are not first class objects however you can override the operator making it possible to have an object function which is first class function pointers are first class boost bind lambda and function do offer first class functions in classes are not first class objects but instances of those classes are in python both the classes and the objects are first class objects see this answer for more details about classes as objects here is an example of javascript first class functions function that takes number and returns number deltax small positive number returns function that is an approximate derivative of function makederivative deltax var deriv function return deltax deltax return deriv var cos makederivative math sin cos cos pi source entities that are not first class objects are referred to as second class objects functions in are second class because they cannot be dynamically created regarding the edit edit when one says everything is an object like in python does he indeed mean that everything is first class the term object can be used loosely and does not imply being first class and it would probably make more sense to call the whole concept first class entities but in python they do aim to make everything first class believe the intent of the person who made your statement meant first class
|
QA
|
what are first class objects when are objects or something else said to be first class in given programming language and why in what do they differ from languages where they are not edit when one says everything is an object like in python does he indeed mean that everything is first class
|
first class means you can operate on them in the usual manner most of the times this just means you can pass these first class citizens as arguments to functions or return them from functions this is self evident for objects but not always so evident for functions or even classes void int return void action int int return now call and pass this is an example in where functions actually are not first class objects the above code therefore uses small workaround namely generic delegate called action to pass function as an argument other languages such as ruby allow treating even classes and code blocks as normal variables or in the case of ruby constants
|
QA
|
what are first class objects when are objects or something else said to be first class in given programming language and why in what do they differ from languages where they are not edit when one says everything is an object like in python does he indeed mean that everything is first class
|
am going to this is one of those metaphors used to describe things in natural language the term is essentially used in context of describing functions as first class objects if you consider object oriented language we can impart various features to objects for eg inheritance class definition ability to pass to other sections of code method arguments ability to store in data structure etc if we can do the same with an entity which is not normally considered as object like functions in the case of java script such entities are considered to be first class objects first class essentially here means not handled as second class with degraded behaviour essentially the mocking is perfect or indistinguishable
|
QA
|
running django with fastcgi or with mod python which would you recommend which is faster reliable apache mod python or nginx lighttpd fastcgi
|
personally have had it working with fastcgi for some time now months or so and the response times seem quicker when loading page that way vs mod python the critical reason for me though is that could not see an obvious way to do multiple sites from the same apache mod python install whereas fastcgi was relative no brainer have not conducted any particularly thorough experiments though edit speaking from experience though setting up fastcgi can be bit of pain the first time around keep meaning to write guide
|
QA
|
running django with fastcgi or with mod python which would you recommend which is faster reliable apache mod python or nginx lighttpd fastcgi
|
lighttpd with fastcgi will be nominally faster but really the time it takes to run your python code and any database hits it does is going to absolutely dwarf any performance benefit you get between web servers mod python and apache will give you bit more flexibility feature wise if you want to write code outside of django that does stuff like digest auth or any fancy http header getting setting perhaps you want to use other builtin features of apache such as mod rewrite if memory is concern staying away form apache mod python will help lot apache tends to use lot of ram and the mod python code that glues into all of the apache functionality occupies lot of memory space as well not to mention the multiprocess nature of apache tends to eat up more ram as each process grows to the size of it is most intensive request
|
QA
|
which library should use to write an xls from linux python would love good native python library to write xls but it does not seem to exist happily jython does so am trying to decide between jexcelapi and apache hssf http www andykhan com jexcelapi tutorial html writing http poi apache org hssf quick guide html cannot use com automation because am not on windows and even if was could not afford office licenses my initial thoughts are that poi hssf is very thorough but also very java everything seems bit harder than it needs to be good documentation but my head hurts trying to bridge the gap between what it describes and what need to accomplish jexcepapi seems to have simpler nicer for me interface but does not have very good documentation or community which would you use and why
|
excel exposes the same ole automation api used by vba to anything that supports com you can use win com which is included with activestate python by default to manipulate spreadsheets in much the same way that you would do in vba
|
QA
|
which library should use to write an xls from linux python would love good native python library to write xls but it does not seem to exist happily jython does so am trying to decide between jexcelapi and apache hssf http www andykhan com jexcelapi tutorial html writing http poi apache org hssf quick guide html cannot use com automation because am not on windows and even if was could not afford office licenses my initial thoughts are that poi hssf is very thorough but also very java everything seems bit harder than it needs to be good documentation but my head hurts trying to bridge the gap between what it describes and what need to accomplish jexcepapi seems to have simpler nicer for me interface but does not have very good documentation or community which would you use and why
|
would use jexcelapi but only because have used it before never have touched hssf biggest show stopper can recall is jexcelapi does not support multiple formats in one cell half the text in bold the other half in italic or something like that think in general jexcelapi is more limited than hssf but the limitations never got in my way and yes documentation is sparse for the interface and nonexistent for the underlying mechanisms but thought it was doable
|
QA
|
which library should use to write an xls from linux python would love good native python library to write xls but it does not seem to exist happily jython does so am trying to decide between jexcelapi and apache hssf http www andykhan com jexcelapi tutorial html writing http poi apache org hssf quick guide html cannot use com automation because am not on windows and even if was could not afford office licenses my initial thoughts are that poi hssf is very thorough but also very java everything seems bit harder than it needs to be good documentation but my head hurts trying to bridge the gap between what it describes and what need to accomplish jexcepapi seems to have simpler nicer for me interface but does not have very good documentation or community which would you use and why
|
what is wrong with xlwt
|
QA
|
what are first class objects when are objects or something else said to be first class in given programming language and why in what do they differ from languages where they are not edit when one says everything is an object like in python does he indeed mean that everything is first class
|
when one says everything is an object like in python does he indeed mean that everything is first class yes everything in python is proper object even things that are primitive types in other languages you find that an object like actually has fairly rich and sophisticated interface dir abs add and class cmp coerce delattr div divmod doc float floordiv getattribute getnewargs hash hex index init int invert long lshift mod mul neg new nonzero oct or pos pow radd rand rdiv rdivmod reduce reduce ex repr rfloordiv rlshift rmod rmul ror rpow rrshift rshift rsub rtruediv rxor setattr str sub truediv xor because everything first class object in python there are relatively few obscure special cases in java for example there are primitive types int bool double char that are not proper objects that is why java has to introduce integer boolean double and character as first class types this can be hard to teach to beginners it is not obvious why both primitive type and an class have to exist side by side it also means that an object class is itself an object this is different from where the classes do not always have distinct existence at run time the type of is the type int object which has methods attributes and type type type int the type of built in type like int is the type type object this has methods and attributes also type type type type
|
QA
|
how do get the name of function or method from within python function or method feel like should know this but have not been able to figure it out want to get the name of method which happens to be an integration test from inside it so it can print out some diagnostic text can of course just hard code the method name in the string but would like to make the test little more dry if possible
|
think the traceback module might have what you are looking for in particular the extract stack function looks like it will do the job
|
QA
|
how do get the name of function or method from within python function or method feel like should know this but have not been able to figure it out want to get the name of method which happens to be an integration test from inside it so it can print out some diagnostic text can of course just hard code the method name in the string but would like to make the test little more dry if possible
|
this decorator makes the name of the method available inside the function by passing it as keyword argument from functools import wraps def pass func name func name of decorated function will be passed as keyword arg func name wraps func def pass name args kwds kwds func name func func name return func args kwds return pass name you would use it this way pass func name def sum func name print running function func name return print sum but maybe you would want to write what you want directly inside the decorator itself then the code is an example of way to get the function name in decorator if you give more details about what you want to do in the function that requires the name maybe can suggest something else
|
QA
|
how do get the name of function or method from within python function or method feel like should know this but have not been able to figure it out want to get the name of method which happens to be an integration test from inside it so it can print out some diagnostic text can of course just hard code the method name in the string but would like to make the test little more dry if possible
|
this seems to be the simplest way using module inspect import inspect def somefunc print my name is inspect stack you could generalise this with def funcname return inspect stack def somefunc print my name is funcname credit to stefaan lippens which was found via google
|
QA
|
running django with fastcgi or with mod python which would you recommend which is faster reliable apache mod python or nginx lighttpd fastcgi
|
am using it with nginx not sure if it is really faster but certainly less ram cpu load also it is easier to run several django processes and have nginx map each url prefix to different socket still not taking full advantage of nginx memcached module but first tests show huge speed advantage
|
QA
|
running django with fastcgi or with mod python which would you recommend which is faster reliable apache mod python or nginx lighttpd fastcgi
|
there is also mod wsgi it seems to be faster than mod python and the daemon mode operates similar to fastcgi
|
QA
|
how does one add svn repository build number to python code edit this question duplicates http stackoverflow com questions how to access the current subversion build number thanks for the heads up charles hi there this question is similar to http stackoverflow com questions getting the subversion repository number into code the differences being would like to add the revision number to python want the revision of the repository not the checked out file would like to extract the revision number from the return from svn info likeso svn info path url svn localhost trunk repository root svn localhost revision node kind directory schedule normal last changed author bmh last changed rev last changed date mon oct want variable with the revision it is easy enough with put rev into variable to keep track of changes on file however would like to keep track of the repository version and understand and it seems based on my tests that rev only updates when the file changes my initial thoughts turn to using the svn libsvn module built in to python though cannot find any documentation on or examples of how to use them alternatively have thought calling svn info and regex ing the code out though that seems rather brutal help would be most appreciated thanks cheers
|
based on cesarb response and the link charles provided have done the following try from subprocess import popen pipe popen svnversion stdout pipe revision communicate none otherwise we get wild exception when django auto reloads except exception print could not get revision number revision unknown golly python is cool
|
QA
|
how do get the name of function or method from within python function or method feel like should know this but have not been able to figure it out want to get the name of method which happens to be an integration test from inside it so it can print out some diagnostic text can of course just hard code the method name in the string but would like to make the test little more dry if possible
|
file foo py import sys import os def line back return sys getframe back lineno def file back return sys getframe back code co filename def func back return sys getframe back code co name def where back frame sys getframe back return os path basename frame code co filename frame lineno frame code co name def testit print here in file line func file line print where says where testit output python foo py here in testit file foo py line where says foo py testit use back to find info regarding two levels back down the stack etc
|
QA
|
how do get the name of function or method from within python function or method feel like should know this but have not been able to figure it out want to get the name of method which happens to be an integration test from inside it so it can print out some diagnostic text can of course just hard code the method name in the string but would like to make the test little more dry if possible
|
the answers involving introspection via inspect and the like are reasonable but there may be another option depending on your situation if your integration test is written with the unittest module then you could use self id within your testcase
|
QA
|
which library should use to write an xls from linux python would love good native python library to write xls but it does not seem to exist happily jython does so am trying to decide between jexcelapi and apache hssf http www andykhan com jexcelapi tutorial html writing http poi apache org hssf quick guide html cannot use com automation because am not on windows and even if was could not afford office licenses my initial thoughts are that poi hssf is very thorough but also very java everything seems bit harder than it needs to be good documentation but my head hurts trying to bridge the gap between what it describes and what need to accomplish jexcepapi seems to have simpler nicer for me interface but does not have very good documentation or community which would you use and why
|
for xlwt see matt harrison blog for posts on how to use xlwt and how to deal with large spreadsheets also check out the python excel group on google if you use python to read write or otherwise manipulate excel files
|
QA
|
running django with fastcgi or with mod python which would you recommend which is faster reliable apache mod python or nginx lighttpd fastcgi
|
have done both and apache mod python tended to be easier to work with and more stable but these days have jumped over to apache mod wsgi which is everything have ever wanted and more easy management of daemon processes as result much better process isolation running multiple sites in the same apache config with mod python almost always ends in trouble environment variables and extensions leak across sites when you do that easy code reloads set it up right and you can just touch the wsgi file to reload instead of restarting apache more predictable resource usage with mod python given apache child process memory use can jump around lot with mod wsgi it is pretty stable once everything loaded you know that is how much memory it will use
|
QA
|
when is not good time to use python generators this is rather the inverse of what can you use python generator functions for python generators generator expressions and the itertools module are some of my favorite features of python these days they are especially useful when setting up chains of operations to perform on big pile of data often use them when processing dsv files so when is it not good time to use generator or generator expression or an itertools function when should prefer zip over itertools izip or range over xrange or for in foo over for in foo obviously we eventually need to resolve generator into actual data usually by creating list or iterating over it with non generator loop sometimes we just need to know the length this is not what am asking we use generators so that we are not assigning new lists into memory for interim data this especially makes sense for large datasets does it make sense for small datasets too is there noticeable memory cpu trade off am especially interested if anyone has done some profiling on this in light of the eye opening discussion of list comprehension performance vs map and filter alt link
|
you should never favor zip over izip range over xrange or list comprehensions over generator comprehensions in python range has xrange like semantics and zip has izip like semantics list comprehensions are actually clearer like list frob for in foo for those times you need an actual list
|
QA
|
upload file in django and then send it somewhere else through rest am building simple django app that will use scribd to display documents would like to have page where the administrator can upload documents to scribd through the website since need to know few things about it before it gets to scribd what is the best easiest way to do this display an upload page and then take the file that is uploaded and send it to scribd through the docs upload method of their api am little new at this python django rest api thing so sorry if this is too many questions at once
|
what you want to do at least from what read here and on the django documentation site is create custom storage system this should give you exactly what you need it is the motivation they use to start the example after all
|
QA
|
when is not good time to use python generators this is rather the inverse of what can you use python generator functions for python generators generator expressions and the itertools module are some of my favorite features of python these days they are especially useful when setting up chains of operations to perform on big pile of data often use them when processing dsv files so when is it not good time to use generator or generator expression or an itertools function when should prefer zip over itertools izip or range over xrange or for in foo over for in foo obviously we eventually need to resolve generator into actual data usually by creating list or iterating over it with non generator loop sometimes we just need to know the length this is not what am asking we use generators so that we are not assigning new lists into memory for interim data this especially makes sense for large datasets does it make sense for small datasets too is there noticeable memory cpu trade off am especially interested if anyone has done some profiling on this in light of the eye opening discussion of list comprehension performance vs map and filter alt link
|
in general do not use generator when you need list operations like len reversed and so on there may also be times when you do not want lazy evaluation to do all the calculation up front so you can release resource in that case list expression might be better
|
QA
|
upload file in django and then send it somewhere else through rest am building simple django app that will use scribd to display documents would like to have page where the administrator can upload documents to scribd through the website since need to know few things about it before it gets to scribd what is the best easiest way to do this display an upload page and then take the file that is uploaded and send it to scribd through the docs upload method of their api am little new at this python django rest api thing so sorry if this is too many questions at once
|
that is quite few questions handling the file upload is pretty straight forward with django see the file uploads documentation for examples in short you can access the uploaded file via request files file to call the scribd api you can use urllib see this hackoarama page for instructions urllib can be little convoluted but it works once you get hang of it you can call the scribd api directly from within your django view but it would be better practice to separate it out from within your django view save the file somewhere on disk and put an upload this message on messaging system eg beanstalkd have separate process pick up the message and upload the file to scribd that way you shield your http process and user from any issues accessing the api and the associated delays
|
QA
|
how do draw text at an angle using python pil using python want to be able to draw text at different angles using pil for example imagine you were drawing the number around the face of clock the number would appear as expected whereas would we drawn rotated counter clockwise degrees therefore need to be able to draw many different strings at many different angles
|
am not saying this is going to be easy or that this solution will necessarily be perfect for you but look at the documentation here http effbot org imagingbook pil index htm and especially pay attention to the image imagedraw and imagefont modules here is an example to help you out import image am image new rgb import imagedraw draw imagedraw draw am draw text hey am rotate show to do what you really want you may need to make bunch of separate correctly rotated text images and then compose them all together with some more fancy manipulation and after all that it still may not look great am not sure how antialiasing and such is handled for instance but it might not be good good luck and if anyone has an easier way would be interested to know as well
|
QA
|
how do draw text at an angle using python pil using python want to be able to draw text at different angles using pil for example imagine you were drawing the number around the face of clock the number would appear as expected whereas would we drawn rotated counter clockwise degrees therefore need to be able to draw many different strings at many different angles
|
draw text into temporary blank image rotate that then paste that onto the original image you could wrap up the steps in function good luck figuring out the exact coordinates to use my cold fogged brain is not up to it right now this demo writes yellow text on slant over an image demo to add rotated text to an image using pil import image import imagefont imagedraw imageops am image open stormy jpg imagefont load default txt image new imagedraw draw txt text someplace near boulder font fill txt rotate expand am paste imageops colorize
|
QA
|
when is not good time to use python generators this is rather the inverse of what can you use python generator functions for python generators generator expressions and the itertools module are some of my favorite features of python these days they are especially useful when setting up chains of operations to perform on big pile of data often use them when processing dsv files so when is it not good time to use generator or generator expression or an itertools function when should prefer zip over itertools izip or range over xrange or for in foo over for in foo obviously we eventually need to resolve generator into actual data usually by creating list or iterating over it with non generator loop sometimes we just need to know the length this is not what am asking we use generators so that we are not assigning new lists into memory for interim data this especially makes sense for large datasets does it make sense for small datasets too is there noticeable memory cpu trade off am especially interested if anyone has done some profiling on this in light of the eye opening discussion of list comprehension performance vs map and filter alt link
|
as you mention this especially makes sense for large datasets think this answers your question if your not hitting any walls performance wise would stick to lists and standard functions then when you run into problems with performance make the switch
|
QA
|
can call and set the python gettext module in library and module using it at the same time am coding library inluding textual feedback that need to translate put the following lines in config py module that import everywhere in my app import gettext os sys pathname os path dirname sys argv localdir os path abspath pathname locale gettext install messages localdir have the mo files in locale lang lang lc messages and apply the function to all the strings that need to be translated now just added feature for the user supposedly programmer to be able to create his own messages do not want him to care about the underlying implementation so want him to be apple to make it something straightforward like lib object message my message used properties to make it clean but what if my user what is to translate his own code that uses mine and does something like import gettext os sys pathname os path dirname sys argv localdir os path abspath pathname locale gettext install user app localdir lib object message my message is it problem what can do to avoid troubles without bothering my user
|
you can only gettext install once in general it is useless for library work gettext install will only do the right thing if the module calling it is in charge of the whole program since it will only provide you with one catalog to load from library code should do something akin to what mailman does have their own wrapper for gettext that passes the right arguments for this module then imports that as in each module that wants to use it
|
QA
|
with lua and python embeddable is there place for basic started off programming in basic on the zx then basica gw basic and qbasic moved on to ah turbo hardly knew ye when got started in microcontrollers regressed with the basic stamp from parallax however basic is was awesome because it was so easy to understand and so hard to make mistake moved on to assembly and eventually because needed the additional power speed capacity resources etc but know that if the bar was much higher many people would never get into programming microcontrollers keep getting an itch to make my own on chip basic interpretor but wonder if there is need for basic now that lua and python are easily embeddable and just as approachable as basic what if any are the advantages basic has over other languages why is it still around if decide to make general purpose microcontroller board with an interpreter is there any reason to make version of basic plenty of other languages are considered dead but basic just keeps hanging on
|
as an architecture the main claim to fame of basic is that you could make basic interpreters very small just few kb in the days of dg nova this was win as you could use systems like business basic to build multiuser application on machine with of ram or even less basic vb in particular is legacy system and has large existing code base arguably vb is really language some would say thin wrapper over com that has basic like syntax these days see little reason to keep the language around apart from people familiarity with it and to maintain the existing code base certainly would not advocate new development in it note that vb net is not really basic but just has vb like syntax the type system is not broken in the way that vb was what is missing from the computing world is relevant language that is easy to learn and tinker with and has mind share in mainstream application development grew up in the days of bit machines and the entry barrier to programming on those systems was very low the architecture of the machines was very simple and you could learn to program and write more or less relevant applications on these machines very easily modern architectures are much more complex and have bigger hump to learn you can see people pontificating on how kids cannot learn to program as easily as they could back in the days of basic and bit computers and think that argument has some merit there is something of hole left that makes programming just that bit harder to get into toy languages are not much use here for programming to be attractive it has to be possible to aspire to build something relevant with the language you are learning this leads to the problem of language that is easy for kids to learn but still allows them to write relevant programmes or even games that they might actually want it also has to be widely perceived as relevant the closest thing can think of to this is python it is not the only example of language of that type but it is the one with the most mind share and am going to perception of relevance is necessary to play in this niche it is also one of the easiest languages to learn that have experienced of the or so that have used over the years
|
QA
|
porting matlab functions to scilab how do use symbolic am porting some matlab functions to scilab the cool thing is that there is conversion toolbox that make things very easy the problem is did not find the counterpart to the syms function and the symbolic toolbox in general would like port of the control system toolbox too amd am still searching for some functions would may need the only thing about symbolic toolbox have found is this but it was little trcky and not so easy actually was not able to set up it correctly in minutes and gave up for now am going to try later and it needs maxima to be installed does anyone know anything about that scilab is not exactly must the project aims to give more free and open source alternative to matlab saw there is sympy for python and just could use it with scipy but would lost the conversion toolbox thing that said what should be better get scilab and maxima work together or move to python co this is the start of the project so the earlier choose this the better
|
see bye matlab hello python thanks sage for first hand experience of migrating from matlab to python
|
QA
|
when is not good time to use python generators this is rather the inverse of what can you use python generator functions for python generators generator expressions and the itertools module are some of my favorite features of python these days they are especially useful when setting up chains of operations to perform on big pile of data often use them when processing dsv files so when is it not good time to use generator or generator expression or an itertools function when should prefer zip over itertools izip or range over xrange or for in foo over for in foo obviously we eventually need to resolve generator into actual data usually by creating list or iterating over it with non generator loop sometimes we just need to know the length this is not what am asking we use generators so that we are not assigning new lists into memory for interim data this especially makes sense for large datasets does it make sense for small datasets too is there noticeable memory cpu trade off am especially interested if anyone has done some profiling on this in light of the eye opening discussion of list comprehension performance vs map and filter alt link
|
profile profile profile profiling your code is the only way to know if what you are doing has any effect at all most usages of xrange generators etc are over static size small datasets it is only when you get to large datasets that it really makes difference range vs xrange is mostly just matter of making the code look tiny little bit more ugly and not losing anything and maybe gaining something profile profile profile
|
QA
|
when is not good time to use python generators this is rather the inverse of what can you use python generator functions for python generators generator expressions and the itertools module are some of my favorite features of python these days they are especially useful when setting up chains of operations to perform on big pile of data often use them when processing dsv files so when is it not good time to use generator or generator expression or an itertools function when should prefer zip over itertools izip or range over xrange or for in foo over for in foo obviously we eventually need to resolve generator into actual data usually by creating list or iterating over it with non generator loop sometimes we just need to know the length this is not what am asking we use generators so that we are not assigning new lists into memory for interim data this especially makes sense for large datasets does it make sense for small datasets too is there noticeable memory cpu trade off am especially interested if anyone has done some profiling on this in light of the eye opening discussion of list comprehension performance vs map and filter alt link
|
as far as performance is concerned cannot think of any times that you would want to use list over generator
|
QA
|
how can draw bezier curve using python pil am using python imaging library and would like to draw some bezier curves guess could calculate pixel by pixel but am hoping there is something simpler
|
bezier curve is not that hard to draw yourself given three points you require three linear interpolations in order to draw the curve we use the scalar as the parameter for the linear interpolation this interpolates between two edges we have created edge ab and edge because the only thing we now have to do to calculate the point we have to draw is interpolate between and using the same like so pfinal there are couple of things that need to be done before we actually draw the curve first off we have will walk some dt delta and we need to be aware that as you might be able to imagine this will not give us smooth curve instead it yields only discrete set of positions at which to plot the easiest way to solve this is to simply draw line between the current point and the previous point
|
QA
|
how do add tab completion to the python she will when starting django application using python manage py she will get an interactiveconsole she will can use tab completion etc python apr gcc apple inc build on darwin type help copyright credits or license for more information interactiveconsole when just starting python interpreter using python it does not offer tab completion can someone tell me what django is doing to give me an interactive console or what need to do to start an interactive console without django app
|
think django does something like https docs python org library rlcompleter html if you want to have really good interactive interpreter have look at http ipython scipy org
|
QA
|
how do add tab completion to the python she will when starting django application using python manage py she will get an interactiveconsole she will can use tab completion etc python apr gcc apple inc build on darwin type help copyright credits or license for more information interactiveconsole when just starting python interpreter using python it does not offer tab completion can someone tell me what django is doing to give me an interactive console or what need to do to start an interactive console without django app
|
may have found way to do it create file pythonrc pythonrc enable syntax completion try import readline except importerror print module readline not available else import rlcompleter readline parse and bind tab complete then in your bashrc file add export pythonstartup pythonrc that seems to work
|
QA
|
opengl with python am currently in course that is using opengl and have been using for all the programs so far have python installed on fedora as well as opengl however the minute call an opengl command in my python code get segmentation fault have no idea why this is just to avoid the just use comments here is why want to use python there are couple reasons am wanting to switch from to python but the main one is because we are about to start writing raytracer and would like to use classes to make it easier on me since hate classes in and structs in seems little crazy thought would give python try at it have also been looking for reason to use python again as it has been while thanks for any help
|
you may also want to consider using pyglet instead of pyopengl it is ctypes wrapper around the native opengl libs on the local platform along with windowing support should handle most of the stuff you want to use glut for the pyglet users list is pretty active and very helpful
|
QA
|
opengl with python am currently in course that is using opengl and have been using for all the programs so far have python installed on fedora as well as opengl however the minute call an opengl command in my python code get segmentation fault have no idea why this is just to avoid the just use comments here is why want to use python there are couple reasons am wanting to switch from to python but the main one is because we are about to start writing raytracer and would like to use classes to make it easier on me since hate classes in and structs in seems little crazy thought would give python try at it have also been looking for reason to use python again as it has been while thanks for any help
|
perhaps you are calling an opengl function that requires an active opengl context without having one that should not necessarily crash but guess it might how to set up such context depends on the platform and it is been while since used gl from python and when did also used gtk which complicates matters
|
QA
|
how can draw bezier curve using python pil am using python imaging library and would like to draw some bezier curves guess could calculate pixel by pixel but am hoping there is something simpler
|
you can use the aggdraw on top of pil bezier curves are supported edit made an example only to discover there is bug in the path class regarding curveto here is the example anyway from pil import image import aggdraw img image new rgb white canvas aggdraw draw img pen aggdraw pen black path aggdraw path path moveto path curveto canvas path path coords path pen canvas flush img save curve png png img show this should fix the bug if you are up for recompiling the module
|
QA
|
opengl set texture color with vertex color because need to display huge number of labels that move independently need to render label in pyglet to texture otherwise updating the vertex list for each glyph is too slow have solution to do this but my problem is that the texture that contains the glyphs is black but would like it to be red see the example below from pyglet gl import def label texture label vertex list label vertex lists vertices xpos map int vertex list ypos map int vertex list glyphs label get glyphs xstart xpos xend xpos glyphs width width xend xstart ystart min ypos yend max ystart glyph height for glyph in glyphs height yend ystart texture pyglet image texture create width height pyglet gl gl rgba for glyph in zip glyphs xpos ypos data glyph get image data xstart height glyph height ystart texture blit into data return texture get transform flip true window pyglet window window label pyglet text label hello world font size texture label texture label window event def on draw hoff window width texture width voff window height texture height glclear gl color buffer bit glenable gl blend glblendfunc gl src alpha gl one minus src alpha glclearcolor window clear glenable gl texture glbindtexture gl texture texture id glcolor would like the font to be red glbegin gl quads gltexcoord glvertex hoff voff gltexcoord glvertex hoff texture width voff gltexcoord glvertex hoff texture width voff texture height gltexcoord glvertex hoff voff texture height glend pyglet app run any idea how could color this
|
is not that when you use decaling through gltexenv
|
QA
|
microphone access in python can access users microphone in python sorry forgot not everyone is mind reader windows at minimum xp but vista support would be very good
|
got the job done with pyaudio it comes with binary installer for windows and there is even an example on how to record through the microphone and save to wave file nice used it on windows xp not sure how it will do on vista though sorry
|
QA
|
alternatives to wizard am making program that fits the wizard concept ideally the user is walked through the steps to create character for game however am realizing that the limitations of the wizard are making it difficult to design elegant logic flow for example because all pages of the wizard are initalized at the same time cannot have the values entered in one page available to the next one have to put button on each page to get the values from previous page rather than simply having fields auto populated have thought about alternatives to using the wizard think the best idea is to have some buttons on one panel that change the information on another panel splitter window however cannot find any documentation in wxpython on how to dynamically change the panel everything have found so far is really pretty static hence the use of the wizard even the wxpython in action book does not mention it are there any tutorials for making dynamic panels or better management of wizard
|
the wxpython demo has an example of dynamic wizard pages override getnext and getprev to show pages dynamically this shows the basic technique you can extend it to add and remove pages change pages on the fly and rearrange pages dynamically the wizard class is just convenience though you can modify it or create your own implementation style that seems popular nowadays is to use an html based presentation you can emulate this with the wxhtml control or the iehtmlwindow control if your app is windows only
|
QA
|
how do add tab completion to the python she will when starting django application using python manage py she will get an interactiveconsole she will can use tab completion etc python apr gcc apple inc build on darwin type help copyright credits or license for more information interactiveconsole when just starting python interpreter using python it does not offer tab completion can someone tell me what django is doing to give me an interactive console or what need to do to start an interactive console without django app
|
for the record this is covered in the tutorial http docs python org tutorial interactive html
|
QA
|
when is not good time to use python generators this is rather the inverse of what can you use python generator functions for python generators generator expressions and the itertools module are some of my favorite features of python these days they are especially useful when setting up chains of operations to perform on big pile of data often use them when processing dsv files so when is it not good time to use generator or generator expression or an itertools function when should prefer zip over itertools izip or range over xrange or for in foo over for in foo obviously we eventually need to resolve generator into actual data usually by creating list or iterating over it with non generator loop sometimes we just need to know the length this is not what am asking we use generators so that we are not assigning new lists into memory for interim data this especially makes sense for large datasets does it make sense for small datasets too is there noticeable memory cpu trade off am especially interested if anyone has done some profiling on this in light of the eye opening discussion of list comprehension performance vs map and filter alt link
|
have never found situation where generators would hinder what you are trying to do there are however plenty of instances where using generators would not help you any more than not using them for example sorted xrange does not offer any improvement over sorted range
|
QA
|
speeding up python this is really two questions but they are so similar and to keep it simple figured would just roll them together firstly given an established python project what are some decent ways to speed it up beyond just plain in code optimization secondly when writing program from scratch in python what are some good ways to greatly improve performance for the first question imagine you are handed decently written project and you need to improve performance but you cannot seem to get much of gain through refactoring optimization what would you do to speed it up in this case short of rewriting it in something like
|
it is often possible to achieve near speeds close enough for any project using python in the first place by replacing explicit algorithms written out longhand in python with an implicit algorithm using built in python call this works because most python built ins are written in anyway well in cpython of course https www python org doc essays list str
|
QA
|
alternatives to wizard am making program that fits the wizard concept ideally the user is walked through the steps to create character for game however am realizing that the limitations of the wizard are making it difficult to design elegant logic flow for example because all pages of the wizard are initalized at the same time cannot have the values entered in one page available to the next one have to put button on each page to get the values from previous page rather than simply having fields auto populated have thought about alternatives to using the wizard think the best idea is to have some buttons on one panel that change the information on another panel splitter window however cannot find any documentation in wxpython on how to dynamically change the panel everything have found so far is really pretty static hence the use of the wizard even the wxpython in action book does not mention it are there any tutorials for making dynamic panels or better management of wizard
|
would get rid of wizard in whole they are the most unpleasant things have ever used the problem that requires wizard application where you click next is perhaps problem where you could apply better user interface in bit different manner instead of bringing up dialog with annoying next button do this bring up page when the user inserts the information to the page extend or shorten it according to the input if your application needs to do some processing to continue and it is impossible to revert after that write new page or disable the earlier section of the current page when you do not need any input from the user anymore or the app is finished you can show button or enable an existing such do not mean you should implement it all in browser make simply scrolling container that can contain buttons and labels in flat list benefit the user can just click tab and you are encouraged to put all the processing into the end of filling the page
|
QA
|
speeding up python this is really two questions but they are so similar and to keep it simple figured would just roll them together firstly given an established python project what are some decent ways to speed it up beyond just plain in code optimization secondly when writing program from scratch in python what are some good ways to greatly improve performance for the first question imagine you are handed decently written project and you need to improve performance but you cannot seem to get much of gain through refactoring optimization what would you do to speed it up in this case short of rewriting it in something like
|
the canonical reference to how to improve python code is here performancetips would recommend against optimizing in unless you really need to though for most applications you can get the performance you need by following the rules posted in that link
|
QA
|
alternatives to wizard am making program that fits the wizard concept ideally the user is walked through the steps to create character for game however am realizing that the limitations of the wizard are making it difficult to design elegant logic flow for example because all pages of the wizard are initalized at the same time cannot have the values entered in one page available to the next one have to put button on each page to get the values from previous page rather than simply having fields auto populated have thought about alternatives to using the wizard think the best idea is to have some buttons on one panel that change the information on another panel splitter window however cannot find any documentation in wxpython on how to dynamically change the panel everything have found so far is really pretty static hence the use of the wizard even the wxpython in action book does not mention it are there any tutorials for making dynamic panels or better management of wizard
|
it should be noted that wizard should be the interface for mutli step infrequently performed tasks the wizard is used to guide the user through something they do not really understand because they almost never do it and if some users might do the task frequently you want to give those power users lightweight interface to do the same thing even if it less self explanatory see windows vista user experience guidelines top violations wizards consider lightweight alternatives first such as dialog boxes task panes or single pages wizards are heavy ui best used for multi step infrequently performed task you do not have to use wizards you can provide helpful information and assistance in any ui
|
QA
|
how can launch an instance of an application using python am creating python script where it does bunch of tasks and one of those tasks is to launch and open an instance of excel what is the ideal way of accomplishing that in my script
|
os system open file xls
|
QA
|
how can launch an instance of an application using python am creating python script where it does bunch of tasks and one of those tasks is to launch and open an instance of excel what is the ideal way of accomplishing that in my script
|
or os system start excel exe path to file presuming it is in the path and you are on windows and also on windows just start filename works too if it is an associated extension already as xls would be
|
QA
|
how can launch an instance of an application using python am creating python script where it does bunch of tasks and one of those tasks is to launch and open an instance of excel what is the ideal way of accomplishing that in my script
|
like popen for the ability to monitor the process excelprocess popen popen start excel excelfile status excelprocess wait http www python org doc lib module popen html edit be aware that calling wait will block until the process returns depending on your script this may not be your desired behavior
|
QA
|
map two lists into one single list of dictionaries imagine have these python lists keys name age values monty matt frank is there direct or at least simple way to produce the following list of dictionaries name monty age name matt age name frank age
|
dict zip keys values len keys for in xrange len values len keys ug leee would hate to see code that looks like that but it looks right def dictizer keys values steps xrange len values len keys bites values len keys for in steps return dict zip keys bite for bite in bites still little ugly but the names help make sense of it
|
QA
|
retrieving python module path want to detect whether module has changed now using inotify is simple you just need to know the directory you want to get notifications from how do retrieve module path in python
|
this was trivial each module has file variable that shows its relative path from where you are right now therefore getting directory for the module to notify it is simple as os path dirname file
|
QA
|
how can launch an instance of an application using python am creating python script where it does bunch of tasks and one of those tasks is to launch and open an instance of excel what is the ideal way of accomplishing that in my script
|
while the popen answers are reasonable for the general case would recommend win api for this specific case if you want to do something useful with it it goes something like this from win com client import dispatch xl dispatch excel application wb xl workbooks open documents and settings gradebook xls xl visible true optional if you want to see the spreadsheet taken from mailing list post but there are plenty of examples around
|
QA
|
is it possible to get the value of an item contained in django changed data list have the following code in my django application if book in authorform changed data do something here realize django can tell me which values have changed in my form by utilizing the changed data list object but would like to know the new values of the fields that have changed any thoughts
|
hmm try this if authorform is valid and book in authorform changed data new value authorform cleaned data book
|
QA
|
is there something between normal user account and root am developing an application that manages network interfaces on behalf of the user and it calls out to several external programs such as ifconfig that requires root to make changes specifically changing the ip address of local interface etc during development have been running the ide as root ugh and the debugger as root double ugh is there nice way for the end user to run these under non root account strongly dislike the size of the attack surface presented by gtk wxpython python and my application when it runs as root have looked into capabilities but they look half baked and am not sure if would be able to use them in python especially if they are on thread basis the only option have not explored is daemon that has the setuid bit set and does all the root type stuff on behalf of the ui am hesitant to introduce that complexity this early in the project as running as root is not dealbreaker for the users
|
there is no single user that is halfway between normal user and root you have root and then you have users users can have differing levels of capabilities if you want something that is more powerful than normal user but not as powerful as root you just create new user with the capabilities you want but do not give it the privileges you do not want it to have
|
QA
|
is there something between normal user account and root am developing an application that manages network interfaces on behalf of the user and it calls out to several external programs such as ifconfig that requires root to make changes specifically changing the ip address of local interface etc during development have been running the ide as root ugh and the debugger as root double ugh is there nice way for the end user to run these under non root account strongly dislike the size of the attack surface presented by gtk wxpython python and my application when it runs as root have looked into capabilities but they look half baked and am not sure if would be able to use them in python especially if they are on thread basis the only option have not explored is daemon that has the setuid bit set and does all the root type stuff on behalf of the ui am hesitant to introduce that complexity this early in the project as running as root is not dealbreaker for the users
|
you could create and distribute selinux policy for your application selinux allows the kind of fine grained access that you need if you cannot or will not use selinux then the daemon is the way to go
|
QA
|
is there something between normal user account and root am developing an application that manages network interfaces on behalf of the user and it calls out to several external programs such as ifconfig that requires root to make changes specifically changing the ip address of local interface etc during development have been running the ide as root ugh and the debugger as root double ugh is there nice way for the end user to run these under non root account strongly dislike the size of the attack surface presented by gtk wxpython python and my application when it runs as root have looked into capabilities but they look half baked and am not sure if would be able to use them in python especially if they are on thread basis the only option have not explored is daemon that has the setuid bit set and does all the root type stuff on behalf of the ui am hesitant to introduce that complexity this early in the project as running as root is not dealbreaker for the users
|
would not run the application full time as root but you might want to explore making your application setuid root or setuid to some id that can become root using something like sudo for particular applications you might be able to set up an account that cannot login use setuid to change your program id temporarily when needed and have sudo set up to not prompt for password but always allow access to that account for specific tasks this way your program has no special privileges when running normally only elevates it is privileges when needed and is restricted by sudo to only running certain programs it is been awhile since have done much unix development so am not really sure whether it is possible to set up sudo to not prompt for password or even if there is an api for it but as fallback you could enable setuid to root only when needed edit looks like sudo has nopasswd mode so think it should work since you are running the programs as external commands
|
QA
|
is there something between normal user account and root am developing an application that manages network interfaces on behalf of the user and it calls out to several external programs such as ifconfig that requires root to make changes specifically changing the ip address of local interface etc during development have been running the ide as root ugh and the debugger as root double ugh is there nice way for the end user to run these under non root account strongly dislike the size of the attack surface presented by gtk wxpython python and my application when it runs as root have looked into capabilities but they look half baked and am not sure if would be able to use them in python especially if they are on thread basis the only option have not explored is daemon that has the setuid bit set and does all the root type stuff on behalf of the ui am hesitant to introduce that complexity this early in the project as running as root is not dealbreaker for the users
|
your idea about the daemon has much merit despite the complexity it introduces as long as the actions do not require some user interface interaction as root daemon allows you to control what operations are allowed and disallowed however you can use sudo to create controlled compromise between root and normal users simply grant sudo access to the users in question for the specific tools they need that reduces the attack surface by allowing only permitted root launches
|
QA
|
is there something between normal user account and root am developing an application that manages network interfaces on behalf of the user and it calls out to several external programs such as ifconfig that requires root to make changes specifically changing the ip address of local interface etc during development have been running the ide as root ugh and the debugger as root double ugh is there nice way for the end user to run these under non root account strongly dislike the size of the attack surface presented by gtk wxpython python and my application when it runs as root have looked into capabilities but they look half baked and am not sure if would be able to use them in python especially if they are on thread basis the only option have not explored is daemon that has the setuid bit set and does all the root type stuff on behalf of the ui am hesitant to introduce that complexity this early in the project as running as root is not dealbreaker for the users
|
what you want is group you create group specify that the account wanting to do the action belongs to the group then you specify that the resource you want access to is member of that group sometimes group management can be kind of irritating but it should allow you to do anything you want and it is the user that is authorized not your program if you want your program authorized you can create specific user to run it as and give that user the proper group membership then su to that group within your program to execute the operation without giving the running user the ability
|
QA
|
http compliance testing what would you use to perform compliance testing of an http proxy have seen two projects so far web polygraph the feedback got from coworker is mostly negative funkload
|
take look here http www measurement factory com the co advisor product might be what you are after note that this is by the same mob that created web polygraph
|
QA
|
is it possible to implement python code completion in textmate pysmell seems like good starting point think it should be possible pysmell idehelper py does majority of the complex stuff it should just be case of giving it the current line offering up the completions the bit am not sure about and then replacing the line with the selected one import idehelper the path is where my pysmelltags file is located pysmelldict idehelper findpysmelldict users dbr desktop pysmell options idehelper detectcompletiontype pysmelldict completions idehelper findcompletions proc pysmelldict options print completions dup menu pysmell pysmell kind word process abbr process arglist excluded output verbose false it will never be perfect but it would be extremely useful even if just for completing the stdlib modules which should never change so you will not have to constantly regenerate the pysmelltags file whenever you add function progressing have the utter basics of completion in place barely works but it is close ran python pysmells py system library frameworks python framework versions lib python py library python site packages pysmell pysmelltags place the following in textmate bundle script set input entire document output insert as text activation key equivalent alt esc scope selector source python usr bin env python import os import sys from pysmell import idehelper cur word os environ get tm current word cur file os environ get tm filepath orig source sys stdin read line no int os environ get tm line number cur col int os environ get tm line index pysmells is currently in site packages pysmell pysmelldict idehelper findpysmelldict library python site packages pysmell blah options idehelper detectcompletiontype cur file orig source line no cur col pysmelldict completions idehelper findcompletions cur word pysmelldict options if len completions new word completions word new word new word replace cur word remove what user has already typed print new word then made new python document typed import urll and hit alt escape and it completed it to import urllib as said it is entirely work in progress so do not use it yet last update orestis has integrated this into the pysmell project code any further fiddling will happen on github
|
edit have actually took your code above and integrated into command it will properly show completion list for you to choose you can grab it here http github com orestis pysmell tree master hit download and do python setup py install it is rough but it works please report any errors on http code google com pysmell hi am the developer of pysmell also use mac so if you can send me an email contact info is in the source code with your progress so far can try to integrate it oh by the way it is called pysmell no trailing
|
QA
|
python using recursive algorithm as generator recently wrote function to generate certain sequences with nontrivial constraints the problem came with natural recursive solution now it happens that even for relatively small input the sequences are several thousands thus would prefer to use my algorithm as generator instead of using it to fill list with all the sequences here is an example suppose we want to compute all the permutations of string with recursive function the following naive algorithm takes an extra argument storage and appends permutation to it whenever it finds one def getpermutations string storage prefix if len string storage append prefix string else for in range len string getpermutations string string storage prefix string storage getpermutations abcd storage for permutation in storage print permutation please do not care about inefficiency this is only an example now want to turn my function into generator to yield permutation instead of appending it to the storage list def getpermutations string prefix if len string yield prefix string else for in range len string getpermutations string string prefix string for permutation in getpermutations abcd print permutation this code does not work the function behaves like an empty generator am missing something is there way to turn the above recursive algorithm into generator without replacing it with an iterative one
|
def getpermutations string prefix if len string yield prefix string else for in xrange len string for perm in getpermutations string string prefix string yield perm or without an accumulator def getpermutations string if len string yield string else for in xrange len string for perm in getpermutations string string yield string perm
|
QA
|
python using recursive algorithm as generator recently wrote function to generate certain sequences with nontrivial constraints the problem came with natural recursive solution now it happens that even for relatively small input the sequences are several thousands thus would prefer to use my algorithm as generator instead of using it to fill list with all the sequences here is an example suppose we want to compute all the permutations of string with recursive function the following naive algorithm takes an extra argument storage and appends permutation to it whenever it finds one def getpermutations string storage prefix if len string storage append prefix string else for in range len string getpermutations string string storage prefix string storage getpermutations abcd storage for permutation in storage print permutation please do not care about inefficiency this is only an example now want to turn my function into generator to yield permutation instead of appending it to the storage list def getpermutations string prefix if len string yield prefix string else for in range len string getpermutations string string prefix string for permutation in getpermutations abcd print permutation this code does not work the function behaves like an empty generator am missing something is there way to turn the above recursive algorithm into generator without replacing it with an iterative one
|
the interior call to getpermutations it is generator too def getpermutations string prefix if len string yield prefix string else for in range len string getpermutations string string prefix string you need to iterate through that with for loop see mizardx posting which edged me out by seconds
|
QA
|
retrieving python module path want to detect whether module has changed now using inotify is simple you just need to know the directory you want to get notifications from how do retrieve module path in python
|
import module print module file will actually give you the path to the pyc file that was loaded at least on mac os so guess you can do import os path os path dirname amodule file you can also try path os path abspath amodule file to get the directory to look for changes
|
QA
|
is there something between normal user account and root am developing an application that manages network interfaces on behalf of the user and it calls out to several external programs such as ifconfig that requires root to make changes specifically changing the ip address of local interface etc during development have been running the ide as root ugh and the debugger as root double ugh is there nice way for the end user to run these under non root account strongly dislike the size of the attack surface presented by gtk wxpython python and my application when it runs as root have looked into capabilities but they look half baked and am not sure if would be able to use them in python especially if they are on thread basis the only option have not explored is daemon that has the setuid bit set and does all the root type stuff on behalf of the ui am hesitant to introduce that complexity this early in the project as running as root is not dealbreaker for the users
|
am not familiar enough with python to tell you what the necessary commands would be in that language but you should be able to accomplish this by forking and using pipe to communicate between the parent and child processes something along the lines of run the program as root via sudo or suid on startup the program immediately forks and establishes pipe for communication between the parent and child processes the child process retains root power but just sits there waiting for input from the pipe the parent process drops root changes its uid back to that of the user running it then displays the gui interacts with the user and handles all operations which are available to non privileged user when an operation is to be performed which requires root privileges the non root parent process sends command down the pipe to the root child process which executes it and optionally reports back to the parent this is likely to be bit easier to write than an independent daemon as well as more convenient to run since you do not need to worry about whether the daemon is running or not while also allowing the gui and other things which do not need root powers to be run as non root
|
QA
|
is there something between normal user account and root am developing an application that manages network interfaces on behalf of the user and it calls out to several external programs such as ifconfig that requires root to make changes specifically changing the ip address of local interface etc during development have been running the ide as root ugh and the debugger as root double ugh is there nice way for the end user to run these under non root account strongly dislike the size of the attack surface presented by gtk wxpython python and my application when it runs as root have looked into capabilities but they look half baked and am not sure if would be able to use them in python especially if they are on thread basis the only option have not explored is daemon that has the setuid bit set and does all the root type stuff on behalf of the ui am hesitant to introduce that complexity this early in the project as running as root is not dealbreaker for the users
|
the traditional way would be to create and use setuid helper to do whatever you need note that however properly writing setuid helper is tricky there are several attack vectors you have to protect against the modern way would be to use daemon running as root started on boot which listens to requests from the rest of the application this way your attack surface is mostly limited to whichever ipc you chose would suggest bus which seems to be the modern way finally if you are managing network interfaces what you doing is very similar to what network manager does on modern distribution it would be good idea to either try to somehow integrate what you are doing with network manager so it will not conflict with your manipulations or at least looks at how it works
|
QA
|
python leopard fink mac ports python org idiot broken python fresh start have been enjoying learning the basics of python but before started reading things tried to install various python versions and modules clumsily now that have some ideas of what want to do and how to do it am finding that various aspects are broken for instance idle will not launch and when try to import modules they usually do not work my question is how would you recommend clean this up and start fresh have read information about modifying the install but still cannot get it to work idle works and when launch python from the terminal am running python
|
macports should be easy to get rid of just delete opt local think that fink does something similar you can do which python to see what python is the default one the system python should be in system library frameworks python framework versions bin python the macpython you may have downloaded would either be in library frameworks python framework you can delete this as well also both macpython and macports edit your profile and change the pythonpath make sure to edit it and remove the extra paths there
|
QA
|
sanitising user input using python what is the best way to sanitise user input for python based web application is there single function to remove html characters and any other necessary characters combinations to prevent an xss or sql injection attack
|
edit bleach is wrapper around html lib which makes it even easier to use as whitelist based sanitiser html lib comes with whitelist based html sanitiser it is easy to subclass it to restrict the tags and attributes users are allowed to use on your site and it even attempts to sanitise css if you are allowing use of the style attribute here is now am using it in my stack overflow clone sanitize html utility function http code google com soclone source browse trunk soclone utils html py have thrown all the attacks listed in ha ckers org xss cheatsheet which are handily available in xml format at it after performing markdown to html conversion using python markdown and it seems to have held up ok the wmd editor component which stackoverflow currently uses is problem though actually had to disable javascript in order to test the xss cheatsheet attacks as pasting them all into wmd ended up giving me alert boxes and blanking out the page
|
QA
|
need really good reason to use python have been trying to make case for using python at my work we use and asp net for basically all of our development or more of our projects are web applications it seems natural that we would look at some of the nice dynamic web languages ruby python etc and with things like ironruby and ironpython started seriously investigating love python it is beautiful expressive language it is joy to code in for sure the multitude of python modules and frameworks make it very appealing problem is cannot think of any specific problems any specific hurdles that would require language like python asp net gives us rad it gives us full featured framework and all that good stuff also we all already know and have lots of projects in learning new language just because does not quite work can you guys help me think of something to finally convince my boss to really learn python and start using it on projects edit know that no problem requires only one language just meant are there any specific problems in which dynamic languages excel over static languages edit again let me also mention that my boss prompted me to investigate this he has put aside hours to research these languages find good one learn it and then figure out how we can use it am at the last step here do not need lecture on why should consider my motivation for changing something my company does because they do it for reason
|
almost no problem requires specific programming language that is just not how things work the easiest way to get new language into an environment like yours is to start new work project in your own time in the new language make it do something you need doing and write it on your own time use it yourself and other people will probably notice it they then say can you send me that program and boom they are using your new language if you really want to something would probably write site in django simply because its admin interface blows everyone away the main point to remember is that if you start using python that is one more thing everyone else has to learn and it is another bullet point that will need to be on every prospective employee resume that can get expensive and management will not like it
|
QA
|
need really good reason to use python have been trying to make case for using python at my work we use and asp net for basically all of our development or more of our projects are web applications it seems natural that we would look at some of the nice dynamic web languages ruby python etc and with things like ironruby and ironpython started seriously investigating love python it is beautiful expressive language it is joy to code in for sure the multitude of python modules and frameworks make it very appealing problem is cannot think of any specific problems any specific hurdles that would require language like python asp net gives us rad it gives us full featured framework and all that good stuff also we all already know and have lots of projects in learning new language just because does not quite work can you guys help me think of something to finally convince my boss to really learn python and start using it on projects edit know that no problem requires only one language just meant are there any specific problems in which dynamic languages excel over static languages edit again let me also mention that my boss prompted me to investigate this he has put aside hours to research these languages find good one learn it and then figure out how we can use it am at the last step here do not need lecture on why should consider my motivation for changing something my company does because they do it for reason
|
can you guys help me think of something to finally convince my boss to really learn python and start using it on projects nope nothing succeeds like success use python be successful make people jealous when asked why you are successful you can talk about python not before choose projects wisely things where dynamic language has significant advantages things where the requirements are not nailed down in detail things like data transformations log file scraping and super sophisticated replacements for bat files use python to get started doing something useful while everyone else is standing around trying to get enough business and domain information to launch project to develop complicated mvc design edit some python to the rescue stories exploratory programming tooling to build test cases what is central here control break reporting one more cool thing about python is in praise of serialization and that is just me edit boss prompted me to investigate figure out how we can use it changes everything the finally convince my boss to really learn python is misleading you are not swimming upstream see how do make the business case for python for the convince my boss problem the edit says you are past this phase dynamic languages offer flexibility exploit that my two sets of examples above are two areas where flexibility matters requirements are not totally nailed down with dynamic language you can get started rework will not be deal breaker with java and and you are reluctant to tackle devastating design changes because it is hard to break everything and get it to compile and work again in python devastating changes are not as expensive design is in flux because you cannot pick components you can write wrappers and facades very easily in python it is scripting language and python modules compose into larger aggregates very simply coding is in flux because requirements and design keep changing it is scripted not compiled you just make change to the code and you are off and running testing is easier because the work cycle is shorter it is not code compile build test it is code test testing is in flux because the requirements keep changing same as above the work cycle is shorter and faster
|
QA
|
need really good reason to use python have been trying to make case for using python at my work we use and asp net for basically all of our development or more of our projects are web applications it seems natural that we would look at some of the nice dynamic web languages ruby python etc and with things like ironruby and ironpython started seriously investigating love python it is beautiful expressive language it is joy to code in for sure the multitude of python modules and frameworks make it very appealing problem is cannot think of any specific problems any specific hurdles that would require language like python asp net gives us rad it gives us full featured framework and all that good stuff also we all already know and have lots of projects in learning new language just because does not quite work can you guys help me think of something to finally convince my boss to really learn python and start using it on projects edit know that no problem requires only one language just meant are there any specific problems in which dynamic languages excel over static languages edit again let me also mention that my boss prompted me to investigate this he has put aside hours to research these languages find good one learn it and then figure out how we can use it am at the last step here do not need lecture on why should consider my motivation for changing something my company does because they do it for reason
|
can you guys help me think of something to finally convince my boss to really learn python and start using it on projects unfortunately the answer is no as harley said no problem is going to require specific language the approach harley suggested is also good one learn on your time build an useful app on your time and maybe just maybe someone at your work will want to use it like it love it then want to learn more about it another approach you could take is to get better understanding of why your company uses net therefore windows server and probably sql server for nearly all development once you have good understanding of why they are not open to other languages then you have some fire power to build business case for the why not why pay licensing costs when you have tools that can accomplish the same things there are free alternatives out there like python that run on free servers why not give your team the chance to grow their professional tool belt this is my opinion but good developer is developer that is not afraid to learn new ways of doing the same thing they have done before but in the end would not get your hopes up bottom line it costs money to introduce new language environment into an it shop whether it is software training or employee rollover there is business reason behind utilizing single language for company and sticking to it am in the exact scenario you are in work in net shop and that is not going to change any time soon get by by working on my own projects in my free time enjoy it and it makes for good balance hope this helps
|
QA
|
need really good reason to use python have been trying to make case for using python at my work we use and asp net for basically all of our development or more of our projects are web applications it seems natural that we would look at some of the nice dynamic web languages ruby python etc and with things like ironruby and ironpython started seriously investigating love python it is beautiful expressive language it is joy to code in for sure the multitude of python modules and frameworks make it very appealing problem is cannot think of any specific problems any specific hurdles that would require language like python asp net gives us rad it gives us full featured framework and all that good stuff also we all already know and have lots of projects in learning new language just because does not quite work can you guys help me think of something to finally convince my boss to really learn python and start using it on projects edit know that no problem requires only one language just meant are there any specific problems in which dynamic languages excel over static languages edit again let me also mention that my boss prompted me to investigate this he has put aside hours to research these languages find good one learn it and then figure out how we can use it am at the last step here do not need lecture on why should consider my motivation for changing something my company does because they do it for reason
|
take step back and look at your approach know what want the answer to be but cannot find any evidence to support it despite the fact that python is my current first choice language am afraid find myself on the side of your boss sorry think you should open your mind and consider all the options from the stance of your organisation best interest and see if you do not come to different conclusion about the best language there are many factors in the choice of language and how pretty it is is fairly minor one the availability of staff is key one the cost of retraining availability of the libraries and meta tools performance etc etc once you have taken into consideration all the different factors and not just oooh it would be fun and made balanced assessment rather than predetermined answer you may find that your boss is more willing to listen the suggestion to secretly use python for work code and leaving the company with terrible code debt in language they are not prepared for seems very unprofessional to me
|
QA
|
need really good reason to use python have been trying to make case for using python at my work we use and asp net for basically all of our development or more of our projects are web applications it seems natural that we would look at some of the nice dynamic web languages ruby python etc and with things like ironruby and ironpython started seriously investigating love python it is beautiful expressive language it is joy to code in for sure the multitude of python modules and frameworks make it very appealing problem is cannot think of any specific problems any specific hurdles that would require language like python asp net gives us rad it gives us full featured framework and all that good stuff also we all already know and have lots of projects in learning new language just because does not quite work can you guys help me think of something to finally convince my boss to really learn python and start using it on projects edit know that no problem requires only one language just meant are there any specific problems in which dynamic languages excel over static languages edit again let me also mention that my boss prompted me to investigate this he has put aside hours to research these languages find good one learn it and then figure out how we can use it am at the last step here do not need lecture on why should consider my motivation for changing something my company does because they do it for reason
|
sneaking language in is often done by automating tedious manual tasks especially dynamic scripting languages like python ruby etc set it up so something like deploying builds or shuffling backups or whatever is done with python then casually slip in how easy it was to do and try to spread some of the enthusiasm around acceptance and awareness should slowly grow from that and before you know it management is seriously considering python for new project
|
QA
|
need really good reason to use python have been trying to make case for using python at my work we use and asp net for basically all of our development or more of our projects are web applications it seems natural that we would look at some of the nice dynamic web languages ruby python etc and with things like ironruby and ironpython started seriously investigating love python it is beautiful expressive language it is joy to code in for sure the multitude of python modules and frameworks make it very appealing problem is cannot think of any specific problems any specific hurdles that would require language like python asp net gives us rad it gives us full featured framework and all that good stuff also we all already know and have lots of projects in learning new language just because does not quite work can you guys help me think of something to finally convince my boss to really learn python and start using it on projects edit know that no problem requires only one language just meant are there any specific problems in which dynamic languages excel over static languages edit again let me also mention that my boss prompted me to investigate this he has put aside hours to research these languages find good one learn it and then figure out how we can use it am at the last step here do not need lecture on why should consider my motivation for changing something my company does because they do it for reason
|
the best leverage you are likely going to have is tools and libraries as others have pointed out no language is required to solve any particular program so let us look at things you can leverage using python google app engine scipy pywinauto django those are off the top of my head finding what is applicable to your team and your company is left as an exercise for the questioner
|
QA
|
need really good reason to use python have been trying to make case for using python at my work we use and asp net for basically all of our development or more of our projects are web applications it seems natural that we would look at some of the nice dynamic web languages ruby python etc and with things like ironruby and ironpython started seriously investigating love python it is beautiful expressive language it is joy to code in for sure the multitude of python modules and frameworks make it very appealing problem is cannot think of any specific problems any specific hurdles that would require language like python asp net gives us rad it gives us full featured framework and all that good stuff also we all already know and have lots of projects in learning new language just because does not quite work can you guys help me think of something to finally convince my boss to really learn python and start using it on projects edit know that no problem requires only one language just meant are there any specific problems in which dynamic languages excel over static languages edit again let me also mention that my boss prompted me to investigate this he has put aside hours to research these languages find good one learn it and then figure out how we can use it am at the last step here do not need lecture on why should consider my motivation for changing something my company does because they do it for reason
|
well here is view of why python programmers make better java programmers the concepts are much the same as for your situation essentially people who learn language because they want to show that they enjoy programming like to learn new things and are more likely to think outside the box if company chooses to write its software in comparatively esoteric language they will be able to hire better programmers because they will attract only those who cared enough to learn it and for programmers the paradox is even more pronounced the language to learn if you want to get good job is language that people do not learn merely to get job not only that but python enforces good looking code and you do not have to do the whole code compile routine with ironpython you can simply code in python and use it as is just another net tool
|
QA
|
need really good reason to use python have been trying to make case for using python at my work we use and asp net for basically all of our development or more of our projects are web applications it seems natural that we would look at some of the nice dynamic web languages ruby python etc and with things like ironruby and ironpython started seriously investigating love python it is beautiful expressive language it is joy to code in for sure the multitude of python modules and frameworks make it very appealing problem is cannot think of any specific problems any specific hurdles that would require language like python asp net gives us rad it gives us full featured framework and all that good stuff also we all already know and have lots of projects in learning new language just because does not quite work can you guys help me think of something to finally convince my boss to really learn python and start using it on projects edit know that no problem requires only one language just meant are there any specific problems in which dynamic languages excel over static languages edit again let me also mention that my boss prompted me to investigate this he has put aside hours to research these languages find good one learn it and then figure out how we can use it am at the last step here do not need lecture on why should consider my motivation for changing something my company does because they do it for reason
|
the language is almost never the key to success good programmers can be successful in variety of languages and you will find successful projects in almost any language you will not find the failures that much because those projects just go away never to be heard of again if you are looking for new language because you do not have good programmers even the best language in the world is not going to help and you have not said anything about the sort of work you are doing python might be good choice because it has well supported and widely used libraries that are critical for you on the other hand might have better support for the stuff that you want to do tool outside of context has no intrinsic merit you might love screwdrivers but that does not help you row boat if you want to use python or any other language just because you like it be honest with yourself and those around you it looks like you have made decision to switch do not know why you are switching and now need to rationalize it with reasons that had nothing to do with your desire to switch if you had good reason you would not be asking here that is not entirely bad thing though programming is human enterprise if the programmers at whatever level insanely love particular language no matter how stupid the reason they are probably going to produce more it is just not technological solution though good luck
|
QA
|
jython howto move file shutils move is non existant use jython import shutil print dir shutil there is no shutil move how does one move file with jython and while we at it how does one delete file with jython
|
os rename to move and os unlink to delete just like python pre shutil
|
QA
|
virtualenv on ubuntu with no site packages have been using virtualenv lately while developing in python like the idea of segregated development environment using the no site packages option but doing this while developing pygtk app can be bit tricky the pygtk modules are installed on ubuntu by default and would like to make virtualenv with no site packages aware of specific modules that are located elsewhere on the system what is the best way to do this or should just suck it up and drop the no site packages option
|
one way is to add the paths to your code using sys path import sys sys path append somepath another way is to use site which processes pth files in addition to adding to sys path import site site addsitedir sitedir known paths none https docs python org library site html but you probably do not want to add this to all your related code have seen mention of sitecustomize py being used to perform something like this but after some testing could not get it to work as might be expected here it mentions that auto import of sitecustomize py ended in if your not on try it out just add one of the path add methods above to the file and drop it in the directory your program is run work around method is mentioned in the post for users of and up http code activestate com recipes
|
QA
|
python with pil and libjpeg on leopard am having trouble getting pictures supported with pil it throws me this ioerror decoder jpeg not available installed pil from binary not realizing needed libjpeg installed libjpeg and freetype through fink tried to reinstall pil using instructions from http timhatch com bottom of the page download pil source package and have the developer tools already installed patch setup py with this patch so it can find the freetype you already have patch leopard freetype different sudo apt get install libjpeg if you have fink otherwise build by hand and adjust paths but am still getting the same error am on leopard ppc
|
is the python path still looking at the old binary version of libjpeg you will need to modify it to point to the new place if it is when you compiled the new version of the pil did it say that it found libjpeg it will compile happily without it iirc and the first sign of trouble you will see is at include time you will need to adjust the path at configure time the different might just not work for you you should test some more and then perhaps file bug
|
QA
|
python with pil and libjpeg on leopard am having trouble getting pictures supported with pil it throws me this ioerror decoder jpeg not available installed pil from binary not realizing needed libjpeg installed libjpeg and freetype through fink tried to reinstall pil using instructions from http timhatch com bottom of the page download pil source package and have the developer tools already installed patch setup py with this patch so it can find the freetype you already have patch leopard freetype different sudo apt get install libjpeg if you have fink otherwise build by hand and adjust paths but am still getting the same error am on leopard ppc
|
had the similar jpeg decoder problem recently when deploying django project on product rhel box that required pil downloaded pil and ran python setup py install instantly and was happy that everything was working until bumped into the problem solution libjpeg was already installed on the system so installed libjpeg devel went back into the source of pil and ran python setup py build at the end of which in the output where it shows whether pil configure was able to detect support for jpeg gif freetype etc it said that jpeg support was ok after installing pil it worked fine
|
QA
|
translate svn path to local file system path in python am writing utility in python that will attach changed files in subversion to an email and send it when subset of folders that are under source control in svn have been changed am using the pysvn library to access the repository have copy of the files on my local file system and do an update to check if the files have changed since the last time the utility was run am at the point where am translating the path names in svn to the path names on my local copy currently have written the following to do the job def formatpaths self paths newpaths list for path in paths path path len self basepath path path replace newpaths append path return newpaths self basepath would be something like trunk project and am looking to just get the relative path of subset of folders folder under trunk project is this good way to solve this problem or is there some magical function missed
|
hm that would do it baselen len self basepath for path in paths path path baselen replace newpaths append path return newpaths if you like you can do it like this baselen len self basepath return path baselen replace for path in paths not calculating baselen in every loop iteration is also good practice
|
QA
|
django and python am just starting to get into django and of course as of last night one of the two new python versions went final obviously so am wondering if plus django is ready for actual use or do the django team need more time to finish with tweaks cleanup all the google searches did were inconclusive saw bits about some initial test runs on beta but nothing more recent seemed to show up edit http groups google com group django developers browse thread thread they have confirmed here works fine as far as they know
|
note that there is currently no python mysql adapter for python if you need mysql stick with for now
|
QA
|
django arbitrary number of unnamed urls py parameters have django model with large number of fields and table rows to facilitate human readable urls and the ability to break down the large list into arbitrary sublists would like to have url that looks like this browse name value name value etc where name maps to model attribute and value is the search criteria for that attribute each name will be treated like category to return subsets of the model instances where the categories match now this could be handled with get parameters but prefer more readable urls for both the user sake and the search engines these urls subsets will be embedded on each page that displays this model so it seems worth the effort to make pretty urls ideally each name value pair will be passed to the view function as parameter named name name etc however do not believe it is possible to defined named patterns via regex matched text am wrong there so it seems need to do something like this urlpatterns patterns url browse app views view name model browse it seems this should match any sets of two name value pairs while it matches it successfully it only passes the last name value pair as parameters to the view function my guess is that each match is overwriting the previous match under the guess that the containing is causing it tried simple repeating pattern instead urlpatterns patterns url browse app views view name model browse and got the same problem but this time args only includes the last matched pattern is this limitation of django url dispatcher and or python regex support it seems either of these methods should work is there way to achieve this without hardcoding each possible model attribute in the url as an optional pattern
|
possibility that you might consider is matching the entire string of possible values within the url pattern portion and pull out the specific pieces within your view as an example urlpatterns patterns url browse match app views view name model browse def view request match pieces match split even indexed pieces are the names odd are values no promises about the regexp used but think you understand what mean edited to try and fix the regexp
|
QA
|
how can launch an instance of an application using python am creating python script where it does bunch of tasks and one of those tasks is to launch and open an instance of excel what is the ideal way of accomplishing that in my script
|
the subprocess module intends to replace several other older modules and functions such as os system os spawn os popen popen commands import subprocess process one subprocess popen gqview home toto my images print process one pid
|
QA
|
translate svn path to local file system path in python am writing utility in python that will attach changed files in subversion to an email and send it when subset of folders that are under source control in svn have been changed am using the pysvn library to access the repository have copy of the files on my local file system and do an update to check if the files have changed since the last time the utility was run am at the point where am translating the path names in svn to the path names on my local copy currently have written the following to do the job def formatpaths self paths newpaths list for path in paths path path len self basepath path path replace newpaths append path return newpaths self basepath would be something like trunk project and am looking to just get the relative path of subset of folders folder under trunk project is this good way to solve this problem or is there some magical function missed
|
stay with the slice operator but do not change the loop variable inside the loop for fun try the generator expression or keep the listcomp baselen len self basepath return path baselen replace for path in paths edit lstrip is not relevant here from the manual str lstrip chars return copy of the string with leading characters removed if chars is omitted or none whitespace characters are removed if given and not none chars must be string the characters in the string will be stripped from the beginning of the string this method is called on
|
QA
|
virtualenv on ubuntu with no site packages have been using virtualenv lately while developing in python like the idea of segregated development environment using the no site packages option but doing this while developing pygtk app can be bit tricky the pygtk modules are installed on ubuntu by default and would like to make virtualenv with no site packages aware of specific modules that are located elsewhere on the system what is the best way to do this or should just suck it up and drop the no site packages option
|
find in this situation symlinks or even copying specific files packages modules extensions works really well it allows the program to emulate being run in the target environment rather than changing the application to suit the development environment same deal for something like appengine
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.