prefix
stringclasses
1 value
input_text
stringlengths
19
27.3k
target_text
stringlengths
2
24.8k
QA
using kwargs with simplexmlrpcserver in python have class that wish to expose as remote service using pythons simplexmlrpcserver the server startup looks like this server simplexmlrpcserver serversettings listen ip serversettings listen port service service server register instance service server serve forever then have serviceremote class that looks like this def init self ip port self rpcclient xmlrpclib server http ip port def getattr self name forward all calls to the rpc client return getattr self rpcclient name so all calls on the serviceremote object will be forwarded to xmlrpclib server which then forwards it to the remote server the problem is method in the service that takes named varargs usedb def select self db fields kwargs pass the usedb decorator wraps the function creating the db before the call and opening it then closing it after the call is done before returning the result when call this method get the error call got an unexpected keyword argument name so is it possible to call methods taking variable named arguments remotely or will have to create an override for each method variation need thanks for the responses changed my code around bit so the question is no longer an issue however now know this for future reference if indeed do need to implement positional arguments and support remote invocation think combination of thomas and praptaks approaches would be good turning kwargs into positional args on the client through xmlrpclient and having wrapper on methods serverside to unpack positional arguments
xml rpc does not really have concept of keyword arguments so xmlrpclib does not try to support them you would need to pick convention then modify xmlrpclib method to accept keyword arguments and pass them along using that convention for instance used to work with an xml rpc server that passed keyword arguments as two arguments keyword followed by the actual argument in flat list no longer have access to the code wrote to access that xml rpc server from python but it was fairly simple along the lines of import xmlrpclib orig method xmlrpclib method class keywordargmethod orig method def call self args kwargs if args and kwargs raise typeerror cannot pass both positional and keyword args args list args for key in kwargs args append key upper args append kwargs key return orig method call self args xmlrpclib method keywordargmethod it uses monkeypatching because that is by far the easiest method to do this because of some clunky uses of module globals and name mangled attributes request for instance in the serverproxy class
QA
dynamically create variables inside function want to create variables inside function from dictionary let us say have dictionary bar and function def foo pass what want to do is to create inside function foo variables with names of each dictionary item name and values as dictionary item values so in the end it should be similar to def foo is it possible at all and if it does how to do such thing
why would you want to do such thing unless you actually do anything with the variables inside the function function that just assigns several variables and then discards them is indistinguishable to def foo pass an optimiser would be justified in generating exactly the same bytecode if you also want to dynamically append code that uses the values then you could do this by using exec though unless this is really user input code there are almost certainly better ways to do what you want eg some code return exec def foo join for in bar items some code note that your code must be indented to the same level on the other hand if you want to actually assign these values to the function object so you can do foo and get note that your sample code does not do this you can do this by for key val in bar items setattr foo key val
QA
using kwargs with simplexmlrpcserver in python have class that wish to expose as remote service using pythons simplexmlrpcserver the server startup looks like this server simplexmlrpcserver serversettings listen ip serversettings listen port service service server register instance service server serve forever then have serviceremote class that looks like this def init self ip port self rpcclient xmlrpclib server http ip port def getattr self name forward all calls to the rpc client return getattr self rpcclient name so all calls on the serviceremote object will be forwarded to xmlrpclib server which then forwards it to the remote server the problem is method in the service that takes named varargs usedb def select self db fields kwargs pass the usedb decorator wraps the function creating the db before the call and opening it then closing it after the call is done before returning the result when call this method get the error call got an unexpected keyword argument name so is it possible to call methods taking variable named arguments remotely or will have to create an override for each method variation need thanks for the responses changed my code around bit so the question is no longer an issue however now know this for future reference if indeed do need to implement positional arguments and support remote invocation think combination of thomas and praptaks approaches would be good turning kwargs into positional args on the client through xmlrpclient and having wrapper on methods serverside to unpack positional arguments
as thomas wouters said xml rpc does not have keyword arguments only the order of arguments matters as far as the protocol is concerned and they can be called anything in xml arg arg arg is perfectly fine as is cheese candy and bacon for the same arguments perhaps you should simply rethink your use of the protocol using something like document literal soap would be much better than workaround such as the ones presented in other answers here of course this may not be feasible
QA
dynamically create variables inside function want to create variables inside function from dictionary let us say have dictionary bar and function def foo pass what want to do is to create inside function foo variables with names of each dictionary item name and values as dictionary item values so in the end it should be similar to def foo is it possible at all and if it does how to do such thing
your question is not clear if you want to set said variables when foo is not running no you cannot there is no frame object yet to set the local variables in if you want to do that in the function body you should not check the python documentation for locals however you could do foo dict update bar and then you could access those variables even from inside the function as foo foo and foo the question is why do you want to do that and why is not class more suitable for your purposes
QA
how do you use the ellipsis slicing syntax in python this came up in hidden features of python but cannot see good documentation or examples that explain how the feature works
this is another use for ellipsis which has nothing to do with slices often use it in intra thread communication with queues as mark that signals done it is there it is an object it is singleton and its name means lack of and it is not the overused none which could be put in queue as part of normal data flow ymmv do not mind downvotes when what say in an answer is not useful in relation to the question then try to improve my answer but sure cannot understand how one can downvote any of the answers in this question when the question is how do you use the ellipsis in python it seems that people think that downvoting means disagree or do not like this
QA
fetch wikipedia article with python try to fetch wikipedia article with python urllib urllib urlopen http en wikipedia org index php title albert einstein printable yes read close however instead of the html page get the following response error wikimedia foundation request get http en wikipedia org index php title albert einstein printable yes from via knsq knams wikimedia org squid stable to error err access denied errno no error at tue sep gmt wikipedia seems to block request which are not from standard browser anybody know how to work around this
try changing the user agent header you are sending in your request to something like user agent mozilla you linux en us rv gecko ubuntu hardy firefox linux mint
QA
dynamically create variables inside function want to create variables inside function from dictionary let us say have dictionary bar and function def foo pass what want to do is to create inside function foo variables with names of each dictionary item name and values as dictionary item values so in the end it should be similar to def foo is it possible at all and if it does how to do such thing
thanks guys got the point should not do such thing but if your curios what tried to do is to somehow short number of lines in my view function in django have form with many fields and instead of receive every field in form of first name form cleaned data first name last name form cleaned data last name was thinking to take every attribute name of my form class and loop over it like so for name in profileregistration base fields dict keyorder and here the variables that tried to assign
QA
fetch wikipedia article with python try to fetch wikipedia article with python urllib urllib urlopen http en wikipedia org index php title albert einstein printable yes read close however instead of the html page get the following response error wikimedia foundation request get http en wikipedia org index php title albert einstein printable yes from via knsq knams wikimedia org squid stable to error err access denied errno no error at tue sep gmt wikipedia seems to block request which are not from standard browser anybody know how to work around this
you do not need to impersonate browser user agent any user agent at all will work just not blank one
QA
python passing variable between classes am trying to create character generation wizard for game in one class calculate the attributes of the character in different class am displaying to the user which specialties are available based on the attributes of the character however cannot remember how to pass variables between different classes here is an example of what have class basicinfopage wx wizard wizardpagesimple def init self parent title wiz wizardpagesimple init self parent self next self prev none self sizer makepagetitle self title snip self intelligence self genattribs class mos wx wizard wizardpagesimple def init self parent title wiz wizardpagesimple init self parent self next self prev none self sizer makepagetitle self title def eligiblemos self event if self intelligence self mos list append analyst the problem is that cannot figure out how to use the intelligence variable from the basicinfopage class to the mos class have tried several different things from around the internet but nothing seems to work what am missing edit realized after posted this that did not explain it that well am trying to create computer version of the twilight rpg from the am using wxpython to create wizard the parent class of my classes is the wizard from wxpython that wizard will walk user through the creation of character so the basic information page class basicinfopage let us the user give the character name and roll for the character attributes that is where the self intelligence comes from am trying to use the attributes created her for page further on in the wizard where the user selects the speciality of the character the specialities that are available depend on the attributes the character has if the intelligence is high enough the character can be an intel anaylst it is been several years since have programmed especially with oop ideas that is why am confused on how to create what is essentially global variable with classes and methods
my problem was indeed the confusion of classes vs instances was trying to do everything via classes without ever creating an actual instance plus was forcing the basicinfopage class to do too much work ultimately created new class baseattribs to hold all the variables need then created in instance of that class when run the wizard and pass that instance as an argument to the classes that need it as shown below run the wizard if name main app wx pysimpleapp wizard wiz wizard none tw character creation attribs baseattribs create each page page intropage wizard introduction page basicinfopage wizard basic info attribs page ethnicity wizard ethnicity page mos wizard military occupational specialty attribs then used the information lott provided and created individual instances if that is what it is called within each class each class is accessing the same variables though everything works as far as can tell thanks
QA
fetch wikipedia article with python try to fetch wikipedia article with python urllib urllib urlopen http en wikipedia org index php title albert einstein printable yes read close however instead of the html page get the following response error wikimedia foundation request get http en wikipedia org index php title albert einstein printable yes from via knsq knams wikimedia org squid stable to error err access denied errno no error at tue sep gmt wikipedia seems to block request which are not from standard browser anybody know how to work around this
it is not solution to the specific problem but it might be intersting for you to use the mwclient library http botwiki sno cc wiki python mwclient instead that would be so much easier especially since you will directly get the article contents which removes the need for you to parse the html have used it myself for two projects and it works very well
QA
fetch wikipedia article with python try to fetch wikipedia article with python urllib urllib urlopen http en wikipedia org index php title albert einstein printable yes read close however instead of the html page get the following response error wikimedia foundation request get http en wikipedia org index php title albert einstein printable yes from via knsq knams wikimedia org squid stable to error err access denied errno no error at tue sep gmt wikipedia seems to block request which are not from standard browser anybody know how to work around this
you need to use the urllib that superseedes urllib in the python std library in order to change the user agent straight from the examples import urllib opener urllib build opener opener addheaders user agent mozilla infile opener open http en wikipedia org index php title albert einstein printable yes page infile read
QA
fetch wikipedia article with python try to fetch wikipedia article with python urllib urllib urlopen http en wikipedia org index php title albert einstein printable yes read close however instead of the html page get the following response error wikimedia foundation request get http en wikipedia org index php title albert einstein printable yes from via knsq knams wikimedia org squid stable to error err access denied errno no error at tue sep gmt wikipedia seems to block request which are not from standard browser anybody know how to work around this
the general solution use for any site is to access the page using firefox and using an extension such as firebug record all details of the http request including any cookies in your program in this case in python you should try to send http request as similar as necessary to the one that worked from firefox this often includes setting the user agent referer and cookie fields but there may be others
QA
dynamically create variables inside function want to create variables inside function from dictionary let us say have dictionary bar and function def foo pass what want to do is to create inside function foo variables with names of each dictionary item name and values as dictionary item values so in the end it should be similar to def foo is it possible at all and if it does how to do such thing
from your comment perhaps what you are really looking for is something like bunch object class bunch object def init self kwargs self dict update kwargs bunch form cleaned data print first name last name the syntax is because bunch type objects are usually used like bunch foo bar blah not used in your case but have left it for consistency with normal usage this does require prefix to access your variables but if you think about it this is no bad thing consider what would happen if someone crafted post request to overwrite variables you are not expecting to be overwritten it makes it easy to produce crashes and dos attacks and could easily introduce more serious security vulnerabilities
QA
does an application wide exception handler make sense long story short have substantial python application that among other things does outcalls to losetup mount etc on linux essentially consuming system resources that must be released when complete if my application crashes want to ensure these system resources are properly released does it make sense to do something like the following def main todo main application entry point pass def cleanup todo release system resources here pass if name main try main except cleanup raise is this something that is typically done is there better way perhaps the destructor in singleton class
consider writing context manager and using the with statement
QA
using kwargs with simplexmlrpcserver in python have class that wish to expose as remote service using pythons simplexmlrpcserver the server startup looks like this server simplexmlrpcserver serversettings listen ip serversettings listen port service service server register instance service server serve forever then have serviceremote class that looks like this def init self ip port self rpcclient xmlrpclib server http ip port def getattr self name forward all calls to the rpc client return getattr self rpcclient name so all calls on the serviceremote object will be forwarded to xmlrpclib server which then forwards it to the remote server the problem is method in the service that takes named varargs usedb def select self db fields kwargs pass the usedb decorator wraps the function creating the db before the call and opening it then closing it after the call is done before returning the result when call this method get the error call got an unexpected keyword argument name so is it possible to call methods taking variable named arguments remotely or will have to create an override for each method variation need thanks for the responses changed my code around bit so the question is no longer an issue however now know this for future reference if indeed do need to implement positional arguments and support remote invocation think combination of thomas and praptaks approaches would be good turning kwargs into positional args on the client through xmlrpclient and having wrapper on methods serverside to unpack positional arguments
using the above advice created some working code server method wrapper def unwrap kwargs func def wrapper args kwargs print args if args and isinstance args list and len args and kwargs args func args args else func args kwargs return wrapper client setup do once orig method xmlrpclib method class keywordargmethod orig method def call self args kwargs args list args if kwargs args append kwargs kwargs return orig method call self args xmlrpclib method keywordargmethod tested this and it supports method with fixed positional and keyword arguments
QA
short integers in python python allocates integers automatically based on the underlying system architecture unfortunately have huge dataset which needs to be fully loaded into memory so is there way to force python to use only bytes for some integers equivalent of short
nope but you can use short integers in arrays from array import array array signed short unsigned short as long as the value stays in that array it will be short integer documentation for the array module
QA
tabs versus spaces in python programming have always used tabs for indentation when do python programming but then came across question here on so where someone pointed out that most python programmers use spaces instead of tabs to minimize editor to editor mistakes how does that make difference are there other reasons why one would use spaces instead of tabs for python or is it simply not true should switch my editor to insert spaces instead of tabs right away or keep on going like used to
use an editor that allows you to insert spaces up to the tabstop when you press the tab key instead of inserting character and then forget about it
QA
using kwargs with simplexmlrpcserver in python have class that wish to expose as remote service using pythons simplexmlrpcserver the server startup looks like this server simplexmlrpcserver serversettings listen ip serversettings listen port service service server register instance service server serve forever then have serviceremote class that looks like this def init self ip port self rpcclient xmlrpclib server http ip port def getattr self name forward all calls to the rpc client return getattr self rpcclient name so all calls on the serviceremote object will be forwarded to xmlrpclib server which then forwards it to the remote server the problem is method in the service that takes named varargs usedb def select self db fields kwargs pass the usedb decorator wraps the function creating the db before the call and opening it then closing it after the call is done before returning the result when call this method get the error call got an unexpected keyword argument name so is it possible to call methods taking variable named arguments remotely or will have to create an override for each method variation need thanks for the responses changed my code around bit so the question is no longer an issue however now know this for future reference if indeed do need to implement positional arguments and support remote invocation think combination of thomas and praptaks approaches would be good turning kwargs into positional args on the client through xmlrpclient and having wrapper on methods serverside to unpack positional arguments
you cannot do this with plain xmlrpc since it has no notion of keyword arguments however you can superimpose this as protocol on top of xmlrpc that would always pass list as first argument and dictionary as second and then provide the proper support code so this becomes transparent for your usage example below server from simplexmlrpcserver import simplexmlrpcserver class server object def init self hostport self server simplexmlrpcserver hostport def register function self function name none def function args kwargs return function args kwargs function name function name self server register function function name def serve forever self self server serve forever example usage server server localhost def test arg arg print arg arg arg arg return server register function test server serve forever client import xmlrpclib class serverproxy object def init self url self xmlrpc server proxy xmlrpclib serverproxy url def getattr self name call proxy getattr self xmlrpc server proxy name def call args kwargs return call proxy args kwargs return call example usage server serverproxy http localhost server test server test arg arg server test arg server test server test arg arg
QA
short integers in python python allocates integers automatically based on the underlying system architecture unfortunately have huge dataset which needs to be fully loaded into memory so is there way to force python to use only bytes for some integers equivalent of short
thanks to armin for pointing out the array module also found the struct module that packs style structs in string from the documentation https docs python org library struct html from struct import pack hhl unpack hhl calcsize hhl
QA
short integers in python python allocates integers automatically based on the underlying system architecture unfortunately have huge dataset which needs to be fully loaded into memory so is there way to force python to use only bytes for some integers equivalent of short
armin suggestion of the array module is probably best two possible alternatives you can create an extension module yourself that provides the data structure that you are after if it is really just something like collection of shorts then that is pretty simple to do you can cheat and manipulate bits so that you are storing one number in the lower half of the python int and another one in the upper half you would write some utility functions to convert to from these within your data structure ugly but it can be made to work it is also worth realising that python integer object is not bytes there is additional overhead so if you have really large number of shorts then you can save more than two bytes per number by using short in some way the array module had to keep large set of integers in memory while ago and dictionary with integer keys and values was too large had gb available for the data structure iirc switched to using iibtree from zodb and managed to fit it the ints in iibtree are real ints not python integers and hacked up an automatic switch to iobtree when the number was larger than bits
QA
short integers in python python allocates integers automatically based on the underlying system architecture unfortunately have huge dataset which needs to be fully loaded into memory so is there way to force python to use only bytes for some integers equivalent of short
armin how come the python documentation said the minimum size for that array of short integer is bytes and the actual representation of values is determined by the machine architecture strictly speaking by the implementation the actual size can be accessed through the itemsize attribute arnav suggest that your code should check the size of each type code and choose the corresponding byte type that is specific to the underlying system
QA
find matching sequences in two binary files let me start off with bit of background this morning one of our users reported that testuff setup file has been reported as infected with virus by the ca antivirus confident that this was false positive looked on the web and found that users of another program spybot have reported the same problem now for the actual question assuming the antivirus is looking for specific binary signature in the file would like to find the matching sequences in both files and hopefully find way to tweak the setup script to prevent that sequence from appearing tried the following in python but it is been running for long time now and was wondering if there was better or faster way from difflib import sequencematcher spybot open spybotsd exe rb read testuff open testuffsetup exe rb read sequencematcher none spybot testuff print find longest match len spybot len testuff is there better library for python or for another language that can do this completely different way to tackle the problem is welcome as well
suspect that looking for binary strings is not going to help you an install program is likely to be doing some suspicious things you probably need to talk to ca and spybot about white listing your installer or about what is triggering the alert
QA
directory listing in python how do get list of all files and directories in given directory in python
you can use os listdir path for reference and more os functions look here python docs https docs python org library os html os listdir python docs https docs python org library os html os listdir
QA
directory listing in python how do get list of all files and directories in given directory in python
import os for filename in os listdir temp print filename
QA
directory listing in python how do get list of all files and directories in given directory in python
try this import os for top dirs files in os walk for nm in files print os path join top nm
QA
directory listing in python how do get list of all files and directories in given directory in python
this is way to traverse every file and directory in directory tree import os for dirname dirnames filenames in os walk print path to all subdirectories first for subdirname in dirnames print os path join dirname subdirname print path to all filenames for filename in filenames print os path join dirname filename advanced usage editing the dirnames list will stop os walk from recursing into there if git in dirnames do not go into any git directories dirnames remove git
QA
python subprocess issue with ampersands am currently having major issue with python script the script runs arbitrary commands through handler to convert incorrect error reporting into correct error reporting the issue am having is getting the script to work correctly on windows with command that contains ampersands in it is path have attempted quoting the command escaping the ampersand with and neither works am now out of ideas any suggestions to clarify from current responses am using the subprocess module am passing the command line arguments in as list the issue is with the path to the command itself not any of the arguments have tried quoting the command it causes error the filename directory name or volume label syntax is incorrect error am using no she will argument so she will false in case it matters am grabbing pipe to stderr for processing it but ignoring stdout and stdin it is only for use on windows currently and works as expected in all other cases that have tested so far the command that is failing is subprocess popen prog stderr subprocess pipe bufsize when the first element of the list prog contains any ampersands quoting this first string does not work
proper answer will need more information than that what are you actually doing how does it fail are you using the subprocess module are you passing list of arguments and she will false or no she will argument or are you actually invoking the she will
QA
python subprocess issue with ampersands am currently having major issue with python script the script runs arbitrary commands through handler to convert incorrect error reporting into correct error reporting the issue am having is getting the script to work correctly on windows with command that contains ampersands in it is path have attempted quoting the command escaping the ampersand with and neither works am now out of ideas any suggestions to clarify from current responses am using the subprocess module am passing the command line arguments in as list the issue is with the path to the command itself not any of the arguments have tried quoting the command it causes error the filename directory name or volume label syntax is incorrect error am using no she will argument so she will false in case it matters am grabbing pipe to stderr for processing it but ignoring stdout and stdin it is only for use on windows currently and works as expected in all other cases that have tested so far the command that is failing is subprocess popen prog stderr subprocess pipe bufsize when the first element of the list prog contains any ampersands quoting this first string does not work
make sure you are using lists and no she will expansion subprocess popen command argument argument she will false
QA
python subprocess issue with ampersands am currently having major issue with python script the script runs arbitrary commands through handler to convert incorrect error reporting into correct error reporting the issue am having is getting the script to work correctly on windows with command that contains ampersands in it is path have attempted quoting the command escaping the ampersand with and neither works am now out of ideas any suggestions to clarify from current responses am using the subprocess module am passing the command line arguments in as list the issue is with the path to the command itself not any of the arguments have tried quoting the command it causes error the filename directory name or volume label syntax is incorrect error am using no she will argument so she will false in case it matters am grabbing pipe to stderr for processing it but ignoring stdout and stdin it is only for use on windows currently and works as expected in all other cases that have tested so far the command that is failing is subprocess popen prog stderr subprocess pipe bufsize when the first element of the list prog contains any ampersands quoting this first string does not work
try quoting the argument that contains the wget http foo com bar baz amp baz bar is usually what has to be done in linux she will
QA
python subprocess issue with ampersands am currently having major issue with python script the script runs arbitrary commands through handler to convert incorrect error reporting into correct error reporting the issue am having is getting the script to work correctly on windows with command that contains ampersands in it is path have attempted quoting the command escaping the ampersand with and neither works am now out of ideas any suggestions to clarify from current responses am using the subprocess module am passing the command line arguments in as list the issue is with the path to the command itself not any of the arguments have tried quoting the command it causes error the filename directory name or volume label syntax is incorrect error am using no she will argument so she will false in case it matters am grabbing pipe to stderr for processing it but ignoring stdout and stdin it is only for use on windows currently and works as expected in all other cases that have tested so far the command that is failing is subprocess popen prog stderr subprocess pipe bufsize when the first element of the list prog contains any ampersands quoting this first string does not work
to answer my own question quoting the actual command when passing the parameters as list does not work correctly command is first item of list so to solve the issue turned the list into space separated string and passed that into subprocess instead better solutions still welcomed
QA
svg rendering in pygame application in pygame application would like to render resolution free gui widgets described in svg what tool and or library can use to reach this goal like the ocemp gui toolkit but it seems to be bitmap dependent for its rendering
you can use cairo with pycairo which has support for rendering svgs the pygame webpage has howto for rendering into buffer with cairo and using that buffer directly with pygame
QA
short integers in python python allocates integers automatically based on the underlying system architecture unfortunately have huge dataset which needs to be fully loaded into memory so is there way to force python to use only bytes for some integers equivalent of short
if you are doing any sort of manipulation of this huge dataset you will probably want to use numpy which has support for wide variety of numeric types and efficient operations on arrays of them
QA
directory listing in python how do get list of all files and directories in given directory in python
here is helper function use quite often import os def listdir fullpath return os path join for in os listdir
QA
why does python pep strongly recommend spaces over tabs for indentation see on stack overflow and pep that the recommendation is to use spaces only for indentation in python programs can understand the need for consistent indentation and have felt that pain is there an underlying reason for spaces to be preferred would have thought that tabs were far easier to work with
the problem with tabs is that they are invisible and people can never agree on the width of tabs when you mix tabs and spaces and you set tabstops at something other than python which uses tabstops every spaces you will be seeing the code in different layout than python sees it and because the layout determines blocks you will be seeing different logic it leads to subtle bugs if you insist on defying pep and using tabs or worse mixing tabs and spaces at least always run python with the tt argument which makes inconsistent indentation sometimes tab sometimes space for the same indentation level an error also if possible set your editor to display tabs differently but really the best approach is not to use tabs period
QA
how can normalize url in python would like to know do normalize url in python for example if have url string like http www example com foo goo bar html need library in python that will transform the extra space or any other non normalized character to proper url
import urlparse urllib def myquote url parts urlparse urlparse url return urlparse urlunparse parts urllib quote parts parts this quotes only the path component otherwise you could do urllib quote url safe
QA
how can normalize url in python would like to know do normalize url in python for example if have url string like http www example com foo goo bar html need library in python that will transform the extra space or any other non normalized character to proper url
use urllib quote or urllib quote plus from the urllib documentation quote string safe replace special characters in string using the xx escape letters digits and the characters are never quoted the optional safe parameter specifies additional characters that should not be quoted its default value is example quote connolly yields econnolly quote plus string safe like quote but also replaces spaces by plus signs as required for quoting html form values plus signs in the original string are escaped unless they are included in safe it also does not have safe default to edit using urllib quote or urllib quote plus on the whole url will mangle it as points out quoted url urllib quote http www example com foo goo bar html quoted url http www example com foo goo bar html urllib urlopen quoted url traceback most recent call last file stdin line in module file python lib urllib py line in urlopen return opener open url data file python lib urllib py line in open protocol req get type file python lib urllib py line in get type raise valueerror unknown url type self original valueerror unknown url type http www example com foo goo bar html provides function that uses urlparse urlparse and urlparse urlunparse to parse the url and only encode the path this may be more useful for you although if you are building the url from known protocol and host but with suspect path you could probably do just as well to avoid urlparse and just quote the suspect part of the url concatenating with known safe parts
QA
parse dicom files in native python what is the simplest and most pythonic way to parse dicom file native python implementation without the use of non python libraries would be much preferred dicom is the standard file format in digital medical imaging look here for more information there are some libraries that support reading subset of dicom files two or three of them even have python bindings native python parser would serve two purposes for me no need to build any external libraries learn about the dicom file format
there are some libraries most often implemented in with python bindings pydicomlib gdcmpython however am looking for native python implementation to learn more about the dicom file format
QA
python subprocess issue with ampersands am currently having major issue with python script the script runs arbitrary commands through handler to convert incorrect error reporting into correct error reporting the issue am having is getting the script to work correctly on windows with command that contains ampersands in it is path have attempted quoting the command escaping the ampersand with and neither works am now out of ideas any suggestions to clarify from current responses am using the subprocess module am passing the command line arguments in as list the issue is with the path to the command itself not any of the arguments have tried quoting the command it causes error the filename directory name or volume label syntax is incorrect error am using no she will argument so she will false in case it matters am grabbing pipe to stderr for processing it but ignoring stdout and stdin it is only for use on windows currently and works as expected in all other cases that have tested so far the command that is failing is subprocess popen prog stderr subprocess pipe bufsize when the first element of the list prog contains any ampersands quoting this first string does not work
escaping the ampersand with are you sure is an escape character to windows should not you use
QA
why does python pep strongly recommend spaces over tabs for indentation see on stack overflow and pep that the recommendation is to use spaces only for indentation in python programs can understand the need for consistent indentation and have felt that pain is there an underlying reason for spaces to be preferred would have thought that tabs were far easier to work with
the most significant advantage can tell of spaces over tabs is that lot of programmers and projects use set number of columns for the source code and if someone commits change with their tabstop set to spaces and the project uses spaces as the tabstop the long lines are going to be too long for other people editor window agree that tabs are easier to work with but think spaces are easier for collaboration which is important on large open source project like python
QA
how can normalize url in python would like to know do normalize url in python for example if have url string like http www example com foo goo bar html need library in python that will transform the extra space or any other non normalized character to proper url
have look at this module werkzeug utils now in werkzeug urls the function you are looking for is called url fix and works like this url fix you http de wikipedia org wiki elf begriffskl rung http de wikipedia org wiki elf begriffskl rung it is implemented in werkzeug as follows import urllib import urlparse def url fix charset utf sometimes you get an url by user that just is not real url because it contains unsafe characters like and so on this function can fix some of the problems in similar way browsers handle data entered by the user url fix you http de wikipedia org wiki elf begriffskl rung http de wikipedia org wiki elf begriffskl rung param charset the target charset for the url if the url was given as unicode string if isinstance unicode encode charset ignore scheme netloc path qs anchor urlparse urlsplit path urllib quote path qs urllib quote plus qs return urlparse urlunsplit scheme netloc path qs anchor
QA
why does python pep strongly recommend spaces over tabs for indentation see on stack overflow and pep that the recommendation is to use spaces only for indentation in python programs can understand the need for consistent indentation and have felt that pain is there an underlying reason for spaces to be preferred would have thought that tabs were far easier to work with
since python relies on indentation in order to recognize program structure clear way to identify identation is required this is the reason to pick either spaces or tabs however python also has strong philosophy of only having one way to do things therefore there should be an official recommendation for one way to do indentation both spaces and tabs pose unique challenges for an editor to handle as indentation the handling of tabs themselves is not uniform across editors or even user settings since spaces are not configurable they pose the more logical choice as they guarantee that the outcome will look everywhere the same
QA
parse dicom files in native python what is the simplest and most pythonic way to parse dicom file native python implementation without the use of non python libraries would be much preferred dicom is the standard file format in digital medical imaging look here for more information there are some libraries that support reading subset of dicom files two or three of them even have python bindings native python parser would serve two purposes for me no need to build any external libraries learn about the dicom file format
some years ago was looking for the same thing and found this python dicom lib was not too impressed with the code but it is native python reading dicom files
QA
why does python pep strongly recommend spaces over tabs for indentation see on stack overflow and pep that the recommendation is to use spaces only for indentation in python programs can understand the need for consistent indentation and have felt that pain is there an underlying reason for spaces to be preferred would have thought that tabs were far easier to work with
you can have your cake and eat it to set your editor to expand tabs into spaces automatically that would be set expandtab in vim
QA
how do develop and create self contained pygtk application bundle for macos with native looking widgets have read that it is possible to build gtk on macos know that it is possible to create bundle of gtk application on macos also know that it is possible to create widgets that look sort of native however searching around am not really clear on how to create bundle that includes the native theme stuff and uses python rather than its own main point there are also rumors that it is possible to build pygtk but it sounds like there might still be some wrinkles in that process however there is no step by step guide that explains how one can set up an environment where an application might be run from python source then built and deployed in an app bundle how can go about doing that
am not sure if am grokking all the details of your question but looking at your problem in general how do deploy python app on mac am inclined to say that the answer is py app basically this will bundle python interpreter and all relevant python files for you and give you scriptable system that you can use to add in whatever other resources dependencies you need
QA
accessing object memory address when you call the object repr method in python you get something like this back main test object at aba cf is there any way to get hold of the memory address if you overload repr other then calling super class obj repr and regexing it out
just use id object
QA
accessing object memory address when you call the object repr method in python you get something like this back main test object at aba cf is there any way to get hold of the memory address if you overload repr other then calling super class obj repr and regexing it out
you can get something suitable for that purpose with id self
QA
accessing object memory address when you call the object repr method in python you get something like this back main test object at aba cf is there any way to get hold of the memory address if you overload repr other then calling super class obj repr and regexing it out
the python manual has this to say about id return the identity of an object this is an integer or long integer which is guaranteed to be unique and constant for this object during its lifetime two objects with non overlapping lifetimes may have the same id value implementation note this is the address of the object so in cpython this will be the address of the object no such guarantee for any other python interpreter though note that if you are writing extension you have full access to the internals of the python interpreter including access to the addresses of objects directly
QA
how do include stacktrace in my django html page am running django and am close to deploying my app as such will be changing the debug setting to false with that being said would still like to include the stacktrace on my html page when errors occur by doing so users can copy and paste the errors and easily email them to the developers any thoughts on how best to approach this issue
automatically log your that way you know when they occur you do not need to rely on users sending you stacktraces joel recommends even going so far as automatically creating tickets in your bug tracker when your application experiences failure personally create private rss feed with the stacktraces urls etc that the developers can subscribe to showing stack traces to your users on the other hand could possibly leak information that malicious users could use to attack your site overly detailed error messages are one of the classic stepping stones to sql injection attacks edit added code sample to capture traceback you can get the exception information from the sys exc info call while formatting the traceback for display comes from the traceback module import traceback import sys try raise exception message except type value tb sys exc info print sys stderr type name value print sys stderr join traceback format tb tb prints exception message file exception py line in module raise exception message
QA
why does python pep strongly recommend spaces over tabs for indentation see on stack overflow and pep that the recommendation is to use spaces only for indentation in python programs can understand the need for consistent indentation and have felt that pain is there an underlying reason for spaces to be preferred would have thought that tabs were far easier to work with
the reason for spaces is that tabs are optional spaces are the actual lowest common denominator in punctuation every decent text editor has replace tabs with spaces and many people use this but not always while some text editors might replace run of spaces with tab this is really rare bottom line you cannot go wrong with spaces you might go wrong with tabs so do not use tabs and reduce the risk of mistakes
QA
how do include stacktrace in my django html page am running django and am close to deploying my app as such will be changing the debug setting to false with that being said would still like to include the stacktrace on my html page when errors occur by doing so users can copy and paste the errors and easily email them to the developers any thoughts on how best to approach this issue
you could call sys exc info in custom exception handler but do not recommend that django can send you emails for exceptions
QA
accessing object memory address when you call the object repr method in python you get something like this back main test object at aba cf is there any way to get hold of the memory address if you overload repr other then calling super class obj repr and regexing it out
you could reimplement the default repr this way def repr self return object at self class module self class name hex id self
QA
accessing object memory address when you call the object repr method in python you get something like this back main test object at aba cf is there any way to get hold of the memory address if you overload repr other then calling super class obj repr and regexing it out
with ctypes you can achieve the same thing with import ctypes ctypes addressof documentation addressof instance integer return the address of the instance internal buffer note that in cpython currently id ctypes addressof but ctypes addressof should return the real address for each python implementation if ctypes is supported memory pointers are valid notion edit added information about interpreter independence of ctypes
QA
svg rendering in pygame application in pygame application would like to render resolution free gui widgets described in svg what tool and or library can use to reach this goal like the ocemp gui toolkit but it seems to be bitmap dependent for its rendering
realise this does not exactly answer your question but there is library called squirtle that will render svg files using either pyglet or pyopengl
QA
svg rendering in pygame application in pygame application would like to render resolution free gui widgets described in svg what tool and or library can use to reach this goal like the ocemp gui toolkit but it seems to be bitmap dependent for its rendering
cairo cannot render svg out of the box it seems we have to use librsvg just found those two pages rendering svg with librsvg python and types how to use librsvg from python something like this should probably work render test svg to test png import cairo import rsvg width height surface cairo imagesurface cairo format argb width height ctx cairo context surface svg rsvg handle file test svg svg render cairo ctx surface write to png test png
QA
why does python pep strongly recommend spaces over tabs for indentation see on stack overflow and pep that the recommendation is to use spaces only for indentation in python programs can understand the need for consistent indentation and have felt that pain is there an underlying reason for spaces to be preferred would have thought that tabs were far easier to work with
the answer was given right there in the pep ed this passage has been edited out in quote the most popular way of indenting python is with spaces only what other underlying reason do you need to put it less bluntly consider also the scope of the pep as stated in the very first paragraph this document gives coding conventions for the python code comprising the standard library in the main python distribution the intention is to make all code that goes in the official python distribution consistently formatted hope we can agree that this is universally good thing since the decision between spaces and tabs for an individual programmer is really matter of taste and easily dealt with by technical means editors conversion scripts etc there is clear way to end all discussion chose one guido was the one to choose he did not even have to give reason but he still did by referring to empirical data for all other purposes you can either take this pep as recommendation or you can ignore it your choice or your team or your team leaders but if may give you one advice do not mix them ed mixing tabs and spaces is no longer an option
QA
how can join list into string caveat along the lines of my previous question how can join list of strings into string such that values get quoted cleanly something like one two three foo bar both into one two three foo bar both suspect that the csv module will come into play here but am not sure how to get the output want
on related note python builtin encoders can also do string escaping print that is interesting encode string escape that interesting
QA
where can save confirmation page be hooked into the django admin similar to delete confirmation want to emulate the delete confirmation page behavior before saving certain models in the admin in my case if change one object certain others should be deleted as they depend upon the object now out of date state understand where to implement the actual cascaded updates inside the parent model save method but do not see quick way to ask the user for confirmation and then rollback if they decide not to save suppose could implement some weird confirmation logic directly inside the save method sort of two phase save but that seems ugly any thoughts even general pointers into the django codebase thanks
have you considered overriding the administrative templates for the models in question this link provides an excellent overview of the process in this particular situation having finer grained level of control may be the best way to achieve the desired result
QA
accessing object memory address when you call the object repr method in python you get something like this back main test object at aba cf is there any way to get hold of the memory address if you overload repr other then calling super class obj repr and regexing it out
while it is true that id object gets the object address in the default cpython implementation this is generally useless you cannot do anything with the address from pure python code the only time you would actually be able to use the address is from extension library in which case it is trivial to get the object address since python objects are always passed around as pointers
QA
how do write this in ruby python or can you translate my linq to ruby python yesterday asked this question and never really got an answer was really happy with really would like to know how to generate list of unique random numbers using functional language such as ruby without having to be extremely imperative in style since did not see anything really liked have written the solution was looking for in linq static void main string args var temp from in getrandomnumbers distinct take select private static ienumerable getrandomnumbers int max random are new random while true yield return next max can you translate my linq to ruby python any other functional programming language note please try not to use too many loops and conditionals otherwise the solution is trivial also would rather see solution where you do not have to generate an array much bigger than so you can then just remove the duplicates and trim it down to know am being picky but would really like to see some elegant solutions to this problem thanks edit why all the downvotes originally my code sample had the distinct after the take which as many pointed out could leave me with an empty list have changed the order in which those methods are called to reflect what meant in the first place apology have been told this post came across as rather snobbish was not trying to imply that linq is better than ruby python or that my solution is much better than everyone else my intent is just to learn how to do this with certain constraints in ruby am sorry if came across as jerk
python with numeric python from numpy import random random integers unique voil sure you could do something similar in functional programming style but why
QA
how do write this in ruby python or can you translate my linq to ruby python yesterday asked this question and never really got an answer was really happy with really would like to know how to generate list of unique random numbers using functional language such as ruby without having to be extremely imperative in style since did not see anything really liked have written the solution was looking for in linq static void main string args var temp from in getrandomnumbers distinct take select private static ienumerable getrandomnumbers int max random are new random while true yield return next max can you translate my linq to ruby python any other functional programming language note please try not to use too many loops and conditionals otherwise the solution is trivial also would rather see solution where you do not have to generate an array much bigger than so you can then just remove the duplicates and trim it down to know am being picky but would really like to see some elegant solutions to this problem thanks edit why all the downvotes originally my code sample had the distinct after the take which as many pointed out could leave me with an empty list have changed the order in which those methods are called to reflect what meant in the first place apology have been told this post came across as rather snobbish was not trying to imply that linq is better than ruby python or that my solution is much better than everyone else my intent is just to learn how to do this with certain constraints in ruby am sorry if came across as jerk
will forgo the simplest solutions using the random module since take it that is not really what you are after here is what think you are looking for in python import random def getuniquerandomnumbers num highest seen set while len seen num random randrange highest if not in seen seen add yield to show you how it works list getuniquerandomnumbers
QA
how do write this in ruby python or can you translate my linq to ruby python yesterday asked this question and never really got an answer was really happy with really would like to know how to generate list of unique random numbers using functional language such as ruby without having to be extremely imperative in style since did not see anything really liked have written the solution was looking for in linq static void main string args var temp from in getrandomnumbers distinct take select private static ienumerable getrandomnumbers int max random are new random while true yield return next max can you translate my linq to ruby python any other functional programming language note please try not to use too many loops and conditionals otherwise the solution is trivial also would rather see solution where you do not have to generate an array much bigger than so you can then just remove the duplicates and trim it down to know am being picky but would really like to see some elegant solutions to this problem thanks edit why all the downvotes originally my code sample had the distinct after the take which as many pointed out could leave me with an empty list have changed the order in which those methods are called to reflect what meant in the first place apology have been told this post came across as rather snobbish was not trying to imply that linq is better than ruby python or that my solution is much better than everyone else my intent is just to learn how to do this with certain constraints in ruby am sorry if came across as jerk
import random print random sample xrange this should yield unique values in the range the xrange object generates values as requested so no memory is used for values that are not sampled
QA
how do write this in ruby python or can you translate my linq to ruby python yesterday asked this question and never really got an answer was really happy with really would like to know how to generate list of unique random numbers using functional language such as ruby without having to be extremely imperative in style since did not see anything really liked have written the solution was looking for in linq static void main string args var temp from in getrandomnumbers distinct take select private static ienumerable getrandomnumbers int max random are new random while true yield return next max can you translate my linq to ruby python any other functional programming language note please try not to use too many loops and conditionals otherwise the solution is trivial also would rather see solution where you do not have to generate an array much bigger than so you can then just remove the duplicates and trim it down to know am being picky but would really like to see some elegant solutions to this problem thanks edit why all the downvotes originally my code sample had the distinct after the take which as many pointed out could leave me with an empty list have changed the order in which those methods are called to reflect what meant in the first place apology have been told this post came across as rather snobbish was not trying to imply that linq is better than ruby python or that my solution is much better than everyone else my intent is just to learn how to do this with certain constraints in ruby am sorry if came across as jerk
hmm how about python set while len update random random
QA
how do write this in ruby python or can you translate my linq to ruby python yesterday asked this question and never really got an answer was really happy with really would like to know how to generate list of unique random numbers using functional language such as ruby without having to be extremely imperative in style since did not see anything really liked have written the solution was looking for in linq static void main string args var temp from in getrandomnumbers distinct take select private static ienumerable getrandomnumbers int max random are new random while true yield return next max can you translate my linq to ruby python any other functional programming language note please try not to use too many loops and conditionals otherwise the solution is trivial also would rather see solution where you do not have to generate an array much bigger than so you can then just remove the duplicates and trim it down to know am being picky but would really like to see some elegant solutions to this problem thanks edit why all the downvotes originally my code sample had the distinct after the take which as many pointed out could leave me with an empty list have changed the order in which those methods are called to reflect what meant in the first place apology have been told this post came across as rather snobbish was not trying to imply that linq is better than ruby python or that my solution is much better than everyone else my intent is just to learn how to do this with certain constraints in ruby am sorry if came across as jerk
in ruby entries sort by rand slice update here is slightly different way entries sort by rand edit and in ruby you can do this array sample
QA
how do write this in ruby python or can you translate my linq to ruby python yesterday asked this question and never really got an answer was really happy with really would like to know how to generate list of unique random numbers using functional language such as ruby without having to be extremely imperative in style since did not see anything really liked have written the solution was looking for in linq static void main string args var temp from in getrandomnumbers distinct take select private static ienumerable getrandomnumbers int max random are new random while true yield return next max can you translate my linq to ruby python any other functional programming language note please try not to use too many loops and conditionals otherwise the solution is trivial also would rather see solution where you do not have to generate an array much bigger than so you can then just remove the duplicates and trim it down to know am being picky but would really like to see some elegant solutions to this problem thanks edit why all the downvotes originally my code sample had the distinct after the take which as many pointed out could leave me with an empty list have changed the order in which those methods are called to reflect what meant in the first place apology have been told this post came across as rather snobbish was not trying to imply that linq is better than ruby python or that my solution is much better than everyone else my intent is just to learn how to do this with certain constraints in ruby am sorry if came across as jerk
here is another ruby solution collect rand think with your linq statement the distinct will remove duplicates after have already been taken so you are not guaranteed to get back someone can correct me if am wrong though
QA
how do write this in ruby python or can you translate my linq to ruby python yesterday asked this question and never really got an answer was really happy with really would like to know how to generate list of unique random numbers using functional language such as ruby without having to be extremely imperative in style since did not see anything really liked have written the solution was looking for in linq static void main string args var temp from in getrandomnumbers distinct take select private static ienumerable getrandomnumbers int max random are new random while true yield return next max can you translate my linq to ruby python any other functional programming language note please try not to use too many loops and conditionals otherwise the solution is trivial also would rather see solution where you do not have to generate an array much bigger than so you can then just remove the duplicates and trim it down to know am being picky but would really like to see some elegant solutions to this problem thanks edit why all the downvotes originally my code sample had the distinct after the take which as many pointed out could leave me with an empty list have changed the order in which those methods are called to reflect what meant in the first place apology have been told this post came across as rather snobbish was not trying to imply that linq is better than ruby python or that my solution is much better than everyone else my intent is just to learn how to do this with certain constraints in ruby am sorry if came across as jerk
import random def makerand rand random random while yield rand randint yield rand randint gen makerand terms gen next for in range print raw list print terms print de duped list print list set terms produces output similar to this raw list de duped list
QA
how do write this in ruby python or can you translate my linq to ruby python yesterday asked this question and never really got an answer was really happy with really would like to know how to generate list of unique random numbers using functional language such as ruby without having to be extremely imperative in style since did not see anything really liked have written the solution was looking for in linq static void main string args var temp from in getrandomnumbers distinct take select private static ienumerable getrandomnumbers int max random are new random while true yield return next max can you translate my linq to ruby python any other functional programming language note please try not to use too many loops and conditionals otherwise the solution is trivial also would rather see solution where you do not have to generate an array much bigger than so you can then just remove the duplicates and trim it down to know am being picky but would really like to see some elegant solutions to this problem thanks edit why all the downvotes originally my code sample had the distinct after the take which as many pointed out could leave me with an empty list have changed the order in which those methods are called to reflect what meant in the first place apology have been told this post came across as rather snobbish was not trying to imply that linq is better than ruby python or that my solution is much better than everyone else my intent is just to learn how to do this with certain constraints in ruby am sorry if came across as jerk
well first you rewrite linq in python then your solution is one liner from random import randrange def distinct items set for in items if not set has key yield set def take num items for in items if num yield num num else break def toarray items return for in items def getrandomnumbers max while yield randrange max print toarray take distinct getrandomnumbers if you put all the simple methods above into module called linq py you can impress your friends disclaimer of course this is not actually rewriting linq in python people have the misconception that linq is just bunch of trivial extension methods and some new syntax the really advanced part of linq however is automatic sql generation so that when you are querying database it is the database that implements distinct rather than the client side
QA
tabs versus spaces in python programming have always used tabs for indentation when do python programming but then came across question here on so where someone pointed out that most python programmers use spaces instead of tabs to minimize editor to editor mistakes how does that make difference are there other reasons why one would use spaces instead of tabs for python or is it simply not true should switch my editor to insert spaces instead of tabs right away or keep on going like used to
use two space indentation and an editor kwrite that inserts spaces instead of tabs when hit the tab key
QA
how do write this in ruby python or can you translate my linq to ruby python yesterday asked this question and never really got an answer was really happy with really would like to know how to generate list of unique random numbers using functional language such as ruby without having to be extremely imperative in style since did not see anything really liked have written the solution was looking for in linq static void main string args var temp from in getrandomnumbers distinct take select private static ienumerable getrandomnumbers int max random are new random while true yield return next max can you translate my linq to ruby python any other functional programming language note please try not to use too many loops and conditionals otherwise the solution is trivial also would rather see solution where you do not have to generate an array much bigger than so you can then just remove the duplicates and trim it down to know am being picky but would really like to see some elegant solutions to this problem thanks edit why all the downvotes originally my code sample had the distinct after the take which as many pointed out could leave me with an empty list have changed the order in which those methods are called to reflect what meant in the first place apology have been told this post came across as rather snobbish was not trying to imply that linq is better than ruby python or that my solution is much better than everyone else my intent is just to learn how to do this with certain constraints in ruby am sorry if came across as jerk
edit ok just for fun shorter and faster one and still using iterators def getrandomnumbers max size pool set return lambda pool add or random randrange max for in xrange size if len size print for in gen yeah know one liners should be left to perl lovers but think this one is quite powerful is not it old message here my god how complicated is all that let us be pythonic import random def getrandomnumber max size min using and xrange using iterators return random randrange min max for in xrange size print set getrandomnumber set removes duplicates set enjoy edit as commentators noticed this is an exact translation of the question code to avoid the problem we got by removing duplicates after generating the list resulting in too little data you can choose another way def getrandomnumbers max size pool while len pool size tmp random randrange max if tmp not in pool yield pool append tmp or tmp print for in getrandomnumbers
QA
how do write this in ruby python or can you translate my linq to ruby python yesterday asked this question and never really got an answer was really happy with really would like to know how to generate list of unique random numbers using functional language such as ruby without having to be extremely imperative in style since did not see anything really liked have written the solution was looking for in linq static void main string args var temp from in getrandomnumbers distinct take select private static ienumerable getrandomnumbers int max random are new random while true yield return next max can you translate my linq to ruby python any other functional programming language note please try not to use too many loops and conditionals otherwise the solution is trivial also would rather see solution where you do not have to generate an array much bigger than so you can then just remove the duplicates and trim it down to know am being picky but would really like to see some elegant solutions to this problem thanks edit why all the downvotes originally my code sample had the distinct after the take which as many pointed out could leave me with an empty list have changed the order in which those methods are called to reflect what meant in the first place apology have been told this post came across as rather snobbish was not trying to imply that linq is better than ruby python or that my solution is much better than everyone else my intent is just to learn how to do this with certain constraints in ruby am sorry if came across as jerk
here is transliteration from your solution to python first generator that creates random numbers this is not very pythonic but it is good match with your sample code import random def getrandomnumbers max while true yield random randrange max here is client loop that collects set of distinct values this is again not the most pythonic implementation distinctset set for in getrandomnumbers distinctset add are if len distinctset break distinctset set it is not clear why you want to use generator for random numbers that is one of the few things that is so simple that generator does not simplify it more pythonic version might be something like distinctset set while len distinctset distinctset add random randrange if the requirements are to generate values and find distinct among those then something like distinctset set random randrange for in range
QA
how do write this in ruby python or can you translate my linq to ruby python yesterday asked this question and never really got an answer was really happy with really would like to know how to generate list of unique random numbers using functional language such as ruby without having to be extremely imperative in style since did not see anything really liked have written the solution was looking for in linq static void main string args var temp from in getrandomnumbers distinct take select private static ienumerable getrandomnumbers int max random are new random while true yield return next max can you translate my linq to ruby python any other functional programming language note please try not to use too many loops and conditionals otherwise the solution is trivial also would rather see solution where you do not have to generate an array much bigger than so you can then just remove the duplicates and trim it down to know am being picky but would really like to see some elegant solutions to this problem thanks edit why all the downvotes originally my code sample had the distinct after the take which as many pointed out could leave me with an empty list have changed the order in which those methods are called to reflect what meant in the first place apology have been told this post came across as rather snobbish was not trying to imply that linq is better than ruby python or that my solution is much better than everyone else my intent is just to learn how to do this with certain constraints in ruby am sorry if came across as jerk
maybe this will suit your needs and look bit more linqish from numpy import random unique def getrandomnumbers total while true yield unique random random total total randomgenerator getrandomnumbers myrandomnumbers randomgenerator next
QA
how do you translate this regular expression idiom from perl into python switched from perl to python about year ago and have not looked back there is only one idiom that have ever found can do more easily in perl than in python if var foo do something with elsif var bar do something with elsif var baz do something with the corresponding python code is not so elegant since the if statements keep getting nested re search foo var if do something with group else re search bar var if do something with group else re search baz var if do something with group does anyone have an elegant way to reproduce this pattern in python have seen anonymous function dispatch tables used but those seem kind of unwieldy to me for small number of regular expressions
using named groups and dispatch table are re compile cmd foo bar baz data def do foo data def do bar data def do baz data dispatch foo do foo bar do bar baz do baz match var if dispatch group cmd group data with little bit of introspection you can auto generate the regexp and the dispatch table
QA
how do find the location of my python site packages directory how do find the location of my site packages directory
from how to install django documentation though this is useful to more than just django installation execute the following from the she will python from distutils sysconfig import get python lib print get python lib formatted for readability rather than use as one liner that looks like the following from distutils sysconfig import get python lib print get python lib
QA
how do you translate this regular expression idiom from perl into python switched from perl to python about year ago and have not looked back there is only one idiom that have ever found can do more easily in perl than in python if var foo do something with elsif var bar do something with elsif var baz do something with the corresponding python code is not so elegant since the if statements keep getting nested re search foo var if do something with group else re search bar var if do something with group else re search baz var if do something with group does anyone have an elegant way to reproduce this pattern in python have seen anonymous function dispatch tables used but those seem kind of unwieldy to me for small number of regular expressions
alternatively something not using regular expressions at all prefix data var var if prefix foo do something with data elif prefix bar do something with data elif prefix baz do something with data else do something with var whether that is suitable depends on your actual problem do not forget regular expressions are not the swiss army knife that they are in perl python has different constructs for doing string manipulation
QA
how do find the location of my python site packages directory how do find the location of my site packages directory
from distutils sysconfig import get python lib print get python lib
QA
how do you translate this regular expression idiom from perl into python switched from perl to python about year ago and have not looked back there is only one idiom that have ever found can do more easily in perl than in python if var foo do something with elsif var bar do something with elsif var baz do something with the corresponding python code is not so elegant since the if statements keep getting nested re search foo var if do something with group else re search bar var if do something with group else re search baz var if do something with group does anyone have an elegant way to reproduce this pattern in python have seen anonymous function dispatch tables used but those seem kind of unwieldy to me for small number of regular expressions
def find first match string regexes for regex handler in regexes re search regex string if handler return else raise valueerror find first match foo foo handle foo bar handle bar baz handle baz to speed it up one could turn all regexes into one internally and create the dispatcher on the fly ideally this would be turned into class then
QA
how do find the location of my python site packages directory how do find the location of my site packages directory
as others have noted distutils sysconfig has the relevant settings import distutils sysconfig print distutils sysconfig get python lib though the default site py does something bit more crude paraphrased below import sys os print os sep join sys prefix lib python sys version site packages it also adds sys prefix lib site python and adds both paths for sys exec prefix as well should that constant be different that said what is the context you should not be messing with your site packages directly setuptools distutils will work for installation and your program may be running in virtualenv where your pythonpath is completely user local so it should not assume use of the system site packages directly either
QA
how do find the location of my python site packages directory how do find the location of my site packages directory
an additional note to the get python lib function mentioned already on some platforms different directories are used for platform specific modules eg modules that require compilation if you pass plat specific true to the function you get the site packages for platform specific packages
QA
how do include stacktrace in my django html page am running django and am close to deploying my app as such will be changing the debug setting to false with that being said would still like to include the stacktrace on my html page when errors occur by doing so users can copy and paste the errors and easily email them to the developers any thoughts on how best to approach this issue
as zacherates says you really do not want to display stacktrace to your users the easiest approach to this problem is what django does by default if you have yourself and your developers listed in the admins setting with email addresses it sends an email to everyone in that list with the full stack trace and more everytime there is error with debug false
QA
is there an eclipse add on to build python executable for distribution want to build an executable to distribute to people without python installed on their machines is there an add on to eclipse that allows this could not find one if not do you have builder that you recommend that would make it easy to go to my python project directory created in eclipse and bundle it all up thanks mark
it is not eclipse but activestate activepython faq mentions the freeze utility which sounds like it might be close to what you are asking for
QA
does anyone know of widget for desktop toolkit gtk qt wx for displaying map of us states am specifically looking for one that let us me display map of us states with each one as it is own object in the sense that can control the color on click and on mouseover of each one individually gtk is my personal preference but at this point would settle for just about anything the application itself will be written in python fwiw
quick tip if you color each state differently you can identify which one to pick from the color under mouse cursor rather than doing complex point in polygon routine
QA
need to create layered dict from flat one have dict that looks like this foo opt opt foo bar opt opt foo bar baz opt opt and need to get it to look like foo opt opt bar opt opt baz opt opt should point out that there can and will be multiple top level keys foo in this case could probably throw something together to get what need but was hoping that there is solution that is more efficient
like this def nest rv for key value in iteritems node rv for part in key split node node setdefault part node update value return rv
QA
need to create layered dict from flat one have dict that looks like this foo opt opt foo bar opt opt foo bar baz opt opt and need to get it to look like foo opt opt bar opt opt baz opt opt should point out that there can and will be multiple top level keys foo in this case could probably throw something together to get what need but was hoping that there is solution that is more efficient
def layer dict for in dict if in del dict subdict dict get find subdict find layer subdict
QA
is there an eclipse add on to build python executable for distribution want to build an executable to distribute to people without python installed on their machines is there an add on to eclipse that allows this could not find one if not do you have builder that you recommend that would make it easy to go to my python project directory created in eclipse and bundle it all up thanks mark
for windows there is the py exe project there is bbfreeze and pyinstaller and py app also
QA
how do you translate this regular expression idiom from perl into python switched from perl to python about year ago and have not looked back there is only one idiom that have ever found can do more easily in perl than in python if var foo do something with elsif var bar do something with elsif var baz do something with the corresponding python code is not so elegant since the if statements keep getting nested re search foo var if do something with group else re search bar var if do something with group else re search baz var if do something with group does anyone have an elegant way to reproduce this pattern in python have seen anonymous function dispatch tables used but those seem kind of unwieldy to me for small number of regular expressions
yeah it is kind of annoying perhaps this will work for your case import re class recheck object def init self self result none def check self pattern text self result re search pattern text return self result var bar stuff recheck if check foo var print result group elif check bar var print result group elif check baz var print result group edit brian correctly pointed out that my first attempt did not work unfortunately this attempt is longer
QA
class views in django django view points to function which can be problem if you want to change only bit of functionality yes could have million keyword arguments and even more if statements in the function but was thinking more of an object oriented approach for example have page that displays user this page is very similar to page that displays group but it is still not so similar to just use another data model group also has members etc one way would be to point views to class methods and then extend that class has anyone tried this approach or has any other idea
generic views will usually be the way to go but ultimately you are free to handle urls however you want formwizard does things in class based way as do some apps for restful apis basically with url you are given bunch of variables and place to provide callable what callable you provide is completely up to you the standard way is to provide function but ultimately django puts no restrictions on what you do do agree that few more examples of how to do this would be good formwizard is probably the place to start though
QA
any experiences with protocol buffers was just looking through some information about google protocol buffers data interchange format has anyone played around with the code or even created project around it am currently using xml in python project for structured content created by hand in text editor and was wondering what the general opinion was on protocol buffers as user facing input format the speed and brevity benefits definitely seem to be there but there are so many factors when it comes to actually generating and processing the data
from your brief description it sounds like protocol buffers is not the right fit the phrase structured content created by hand in text editor pretty much screams for xml but if you want efficient low latency communications with data structures that are not shared outside your organization binary serialization such as protocol buffers can offer huge win
QA
how do copy file in python how do copy file in python could not find anything under os
shutil has many methods you can use one of which is from shutil import copyfile copyfile src dst copy the contents of the file named src to file named dst the destination location must be writable otherwise an ioerror exception will be raised if dst already exists it will be replaced special files such as character or block devices and pipes cannot be copied with this function src and dst are path names given as strings
QA
how do copy file in python how do copy file in python could not find anything under os
shutil may have what you re looking for
QA
how do copy file in python how do copy file in python could not find anything under os
look at module shutil it contains function copyfile src dst
QA
how do copy file in python how do copy file in python could not find anything under os
use the shutil module copyfile src dst copy the contents of the file named src to file named dst the destination location must be writable otherwise an ioerror exception will be raised if dst already exists it will be replaced special files such as character or block devices and pipes cannot be copied with this function src and dst are path names given as strings take look at filesys for all the file and directory handling functions available in standard python modules
QA
how do copy file in python how do copy file in python could not find anything under os
import shutil shutil copy dir file ext new dir newname ext or shutil copy dir file ext new dir copy is also often useful it preserves the original modification and access info mtime and atime in the file metadata
QA
how do write this in ruby python or can you translate my linq to ruby python yesterday asked this question and never really got an answer was really happy with really would like to know how to generate list of unique random numbers using functional language such as ruby without having to be extremely imperative in style since did not see anything really liked have written the solution was looking for in linq static void main string args var temp from in getrandomnumbers distinct take select private static ienumerable getrandomnumbers int max random are new random while true yield return next max can you translate my linq to ruby python any other functional programming language note please try not to use too many loops and conditionals otherwise the solution is trivial also would rather see solution where you do not have to generate an array much bigger than so you can then just remove the duplicates and trim it down to know am being picky but would really like to see some elegant solutions to this problem thanks edit why all the downvotes originally my code sample had the distinct after the take which as many pointed out could leave me with an empty list have changed the order in which those methods are called to reflect what meant in the first place apology have been told this post came across as rather snobbish was not trying to imply that linq is better than ruby python or that my solution is much better than everyone else my intent is just to learn how to do this with certain constraints in ruby am sorry if came across as jerk
here is another python version more closely matching the structure of your code there is not builtin for giving distinct results so have added function to do this import itertools random def distinct seq seen set for item in seq if item not in seen seen add item yield item def getrandomnumbers max while yield random randint max for item in itertools islice distinct getrandomnumbers print item
QA
passing apache digest authentication information to wsgi script run by mod wsgi have got the directive virtualhost location authtype digest authname global authdigestdomain authuserfile root apache users limit get require valid user limit location wsgiscriptalias some script wsgi wsgidaemonprocess mywsgi user someuser group somegroup processes threads wsgiprocessgroup mywsgi servername some example org virtualhost would like to know in the some script wsgi def application environ start response start response ok content type text plain return hello what user is logged in how do do that
add wsgipassauthorization on virtualhost location authtype digest authname global authdigestdomain authuserfile root apache users limit get require valid user limit location wsgipassauthorization on wsgiscriptalias some script wsgi wsgidaemonprocess mywsgi user someuser group somegroup processes threads wsgiprocessgroup mywsgi servername some example org virtualhost then just read environ remote user def application environ start response start response ok content type text plain return hello environ remote user more information at mod wsgi documentation
QA
iron python beautiful soup win app does beautiful soup work with iron python if so with which version of iron python how easy is it to distribute windows desktop app on net using iron python mostly calling some python code for parsing html
regarding the second part of your question you can use the dlr hosting apis to run ironpython code from within application the dlr hosting spec is here this blog also contains some sample hosting applications
QA
iron python beautiful soup win app does beautiful soup work with iron python if so with which version of iron python how easy is it to distribute windows desktop app on net using iron python mostly calling some python code for parsing html
also regarding one of the previous comments about compiling with saveassemblies that is wrong saveassemblies is meant as debugging feature there is api meant for compiling python code into binaries this post explains the api and the difference between the two modes
QA
python regular expression to split paragraphs how would one write regular expression to use in python to split paragraphs paragraph is defined by linebreaks but one can have any ammount of spaces tabs together with the line breaks and it still should be considered as paragraph am using python so the solution can use python regular expression syntax which is extended can make use of stuff examples the str paragraph nparagraph splitting should yield paragraph paragraph the str np tstill tp should yield tstill the str tp should yield tp the best could come with is but that is ugly anything better edit suggestions rejected that would make example and fail since includes so it would allow paragraph breaks with more than ns
not regexp but really elegant from itertools import groupby def paragraph lines for group separator line iteration in groupby lines splitlines true key str isspace if not group separator yield join line iteration for in paragraph np tstill tp print repr tstill tp it is up to you to strip the output as you need it of course inspired from the famous python cookbook
QA
how to get set logical directory path in python in python is it possible to get or set logical directory as opposed to an absolute one for example if have real path to dir and have linked path to dir linked to the same directory using os getcwd and os chdir will always use the absolute path import os os chdir linked path to dir print os getcwd real path to dir the only way have found to get around this at all is to launch pwd in another process and read the output however this only works until you call os chdir for the first time
the underlying operational system she will reports real paths to python so there really is no way around it since os getcwd is wrapped call to library getcwd function there are some workarounds in the spirit of the one that you already know which is launching pwd another one would involve using os environ pwd if that environmnent variable is set you can make some getcwd function that respects it the solution below combines both import os from subprocess import popen pipe class cwdkeeper object def init self self cwd os environ get pwd if self cwd is none no environment fall back to calling pwd on she will self cwd popen pwd stdout pipe communicate strip self os getcwd os getcwd self os chdir os chdir def chdir self path if not self cwd return self os chdir path os path normpath os path join self cwd path result self os chdir self cwd os environ pwd return result def getcwd self if not self cwd return self os getcwd return self cwd cwd cwdkeeper print cwd getcwd use only cwd chdir and cwd getcwd from now on monkeypatch os if you want os chdir cwd chdir os getcwd cwd getcwd now you can use os chdir and os getcwd as normal
QA
is there an eclipse add on to build python executable for distribution want to build an executable to distribute to people without python installed on their machines is there an add on to eclipse that allows this could not find one if not do you have builder that you recommend that would make it easy to go to my python project directory created in eclipse and bundle it all up thanks mark
see these questions
QA
how do you translate this regular expression idiom from perl into python switched from perl to python about year ago and have not looked back there is only one idiom that have ever found can do more easily in perl than in python if var foo do something with elsif var bar do something with elsif var baz do something with the corresponding python code is not so elegant since the if statements keep getting nested re search foo var if do something with group else re search bar var if do something with group else re search baz var if do something with group does anyone have an elegant way to reproduce this pattern in python have seen anonymous function dispatch tables used but those seem kind of unwieldy to me for small number of regular expressions
would suggest this as it uses the least regex to accomplish your goal it is still functional code but no worse then your old perl import re var barbazfoo re search foo bar baz var if group foo print group do something with group elif group bar print group do something with group elif group baz print group do something with group
QA
passing around urls between applications in the same project am trying to mock up an api and am using separate apps within django to represent different web services would like app to take in link that corresponds to app and parse the json response is there way to dynamically construct the url to app so that can test the code in development and not change to much before going into production the problem is that cannot use localhost as part of link am currently using urllib but eventually would like to do something less hacky and better fitting with the web services rest paradigm
you could do something like if settings debug other localhost else other somehost and use other to build the external url generally you code in debug mode and deploy in non debug mode settings debug is standard django thing