content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Client machine not able to connect with xmlrpc server, hosted on EC2 cloud Server I have ubuntu instance on Ec2 cloud server and on same instance I have created xmlrpc server using simpleXMLRP. I'd like to access server methods from my local ubuntu machine.but when I tried to do so, it raised "Protocol Error" as b...
Client machine not able to connect with xmlrpc server, hosted on EC2 cloud Server
I have ubuntu instance on Ec2 cloud server and on same instance I have created xmlrpc server using simpleXMLRP. I'd like to access server methods from my local ubuntu machine.but when I tried to do so, it raised "Protocol Error" as below, "XMLRPC Error : xmlrpclib.ProtocolError: ProtocolError for ec2-70-41-59-2.amazo...
[ "This answer may help someone to solve the same problem,\n1) Select your (or default) Security Group in Ec2 Section of cloud Server.\n2) Select \"Inbound\" Tab and create new Rule for \"All TCP\" and give access to your required port.\nas per my knowledge, second step will inform cloud server to open selected port ...
[ 0 ]
[]
[]
[ "amazon_ec2", "cloud", "python", "simplexmlrpcserver" ]
stackoverflow_0006274661_amazon_ec2_cloud_python_simplexmlrpcserver.txt
Q: Efficient Datatype Python (list or numpy array?) I'm still confused whether to use list or numpy array. I started with the latter, but since I have to do a lot of append I ended up with many vstacks slowing my code down. Using list would solve this problem, but I also need to delete elements which again works wel...
Efficient Datatype Python (list or numpy array?)
I'm still confused whether to use list or numpy array. I started with the latter, but since I have to do a lot of append I ended up with many vstacks slowing my code down. Using list would solve this problem, but I also need to delete elements which again works well with delete on numpy array. As it looks now I'll hav...
[ "As I see it, if you were doing this in C or Fortran, you'd have to have an idea of the size of the array so that you can allocate the correct amount of memory (ignoring realloc!). So assuming you do know this, why do you need to append to the array?\nIn any case, numpy arrays have the resize method, which you can ...
[ 1 ]
[]
[]
[ "arrays", "numpy", "performance", "python" ]
stackoverflow_0006577657_arrays_numpy_performance_python.txt
Q: How do I specify the constructor docstring for a Django model? Then I run pdoc Mymodel in the python shell, I want the docstring for the constructor of my django model. Where can I specify this ? A: In the __init__ method. class MyModel(models.Model) def __init__(self, *args, **kwargs) """My docstri...
How do I specify the constructor docstring for a Django model?
Then I run pdoc Mymodel in the python shell, I want the docstring for the constructor of my django model. Where can I specify this ?
[ "In the __init__ method.\nclass MyModel(models.Model)\n\n def __init__(self, *args, **kwargs)\n \"\"\"My docstring\n \"\"\"\n super(MyModel, self).__init__(*args, **kwargs)\n\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006581109_django_python.txt
Q: Binding checkbox to string in IronPython How can I bind a checkbox to a string such that when the checkbox is checked/unchecked, the value of the string changes? I have this (with CheckAll as my checkbox): class MyWindow(Window): def __init__(self): wpf.LoadComponent(self, 'BioApp1.xaml') openD...
Binding checkbox to string in IronPython
How can I bind a checkbox to a string such that when the checkbox is checked/unchecked, the value of the string changes? I have this (with CheckAll as my checkbox): class MyWindow(Window): def __init__(self): wpf.LoadComponent(self, 'BioApp1.xaml') openDialog = SequenceFileOperations() self....
[ "I would use Converter.\nEdit:\nYou can implement converter in Python: \nclass BoolToVisibilityConverter(IValueConverter):\n\n def Convert(self, value, targetType, parameter, culture):\n return Visibility.Visible if value != val else Visibility.Collapsed\n\nLast time I worked with WPF in IronPython, you c...
[ 1 ]
[]
[]
[ "data_binding", "ironpython", "python", "visual_studio_2010" ]
stackoverflow_0006575599_data_binding_ironpython_python_visual_studio_2010.txt
Q: Can any one explain how can i pass arg or kwargs from redirect to another view? I am trying to let the manager of a site I'm developing send mail to the members and send get a confirmation page. The send mail is working and sending the mail OK, but in the confirmation i want him to get the the list of people he se...
Can any one explain how can i pass arg or kwargs from redirect to another view?
I am trying to let the manager of a site I'm developing send mail to the members and send get a confirmation page. The send mail is working and sending the mail OK, but in the confirmation i want him to get the the list of people he sent the mail to. So, i need to send the users_list from one function (view) to the oth...
[ "Rather then trying to pass it in the reverse/redirect you could set users_list as a session variable. e.g.\n# before redirect\nrequest.session['users_list'] = users_list\n\n# in sent view\nusers_list = request.session.get('users_list', None)\n\n" ]
[ 2 ]
[]
[]
[ "django", "django_urls", "django_views", "python" ]
stackoverflow_0006581351_django_django_urls_django_views_python.txt
Q: how to do a join in sqlalchemy session query? I need to find the equivalent of this query in sqlalchemy. SELECT u.user_id, u.user_name, c.country FROM table_user u , table_country c WHERE u.user_email = 'abc@def.com' i tried this below code: session.query(User).join(Country.country).filter(User.user_email == 'abc...
how to do a join in sqlalchemy session query?
I need to find the equivalent of this query in sqlalchemy. SELECT u.user_id, u.user_name, c.country FROM table_user u , table_country c WHERE u.user_email = 'abc@def.com' i tried this below code: session.query(User).join(Country.country).filter(User.user_email == 'abc@def.com').first() and this gave me below error : ...
[ "Try this, assuming your User mapper has a relationship to Country configured.\nuser, country = session.query(User, Country.country).join(Country).filter(User.user_email == 'abc@def.com').first()\n\n" ]
[ 20 ]
[]
[]
[ "orm", "python", "sqlalchemy" ]
stackoverflow_0006580835_orm_python_sqlalchemy.txt
Q: Is there any API for Oneworld Alliance? Does anyone know if there is an API for Oneworld Alliance ? The idea is to program in Python a Traveling Salesman, who visits all airports in the system based on actual available flight connections. A: I don't think Oneworld Alliance themselves, or other airlines or allian...
Is there any API for Oneworld Alliance?
Does anyone know if there is an API for Oneworld Alliance ? The idea is to program in Python a Traveling Salesman, who visits all airports in the system based on actual available flight connections.
[ "I don't think Oneworld Alliance themselves, or other airlines or alliances, have their own APIs. Not sure whether asking this is ontopic to SO.\nTry the search engines and booking sites: Travelocity, Expedia, Hotwire, cheaptickets...\nFor example by Google here's Expedia Affiliate Network.\nKayak apparently used t...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0006383376_python.txt
Q: Where do I put methods that perform create_if_missing or update_if_exists function in django? In what location should I place methods that perform: Create this row if it is missing Update the row if it exists for a django model ? Additionally since I am using the default transaction scheme of django, this might ...
Where do I put methods that perform create_if_missing or update_if_exists function in django?
In what location should I place methods that perform: Create this row if it is missing Update the row if it exists for a django model ? Additionally since I am using the default transaction scheme of django, this might introduce race conditions. How do I prevent that ?
[ "Django has this built-in: get_or_create.\n", "The answer is get_or_create.\nI suppose it is obligatory to link to their docs as well.\n" ]
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006581518_django_python.txt
Q: How do I use mocking to test a next_day_of_week function I'm tracking events that recur on a particular day of the week (e.g., first Sunday of the month, third Friday of the month). I have a DayOfWeek model that stores the event's day of the week. It contains a method next_day_of_week to return a date object set t...
How do I use mocking to test a next_day_of_week function
I'm tracking events that recur on a particular day of the week (e.g., first Sunday of the month, third Friday of the month). I have a DayOfWeek model that stores the event's day of the week. It contains a method next_day_of_week to return a date object set to the next occurrence of whatever weekday a given event instan...
[ "Figured it out.\nThe question was really Where to patch and the answer came from studying the Mock documentation I linked to above (this page).\nThe solution was to mock the date class in the namespace of the module that contains the models for this app, like so:\nclass TestDayOfWeek(TestCase):\n #Test the day ...
[ 10, 0 ]
[]
[]
[ "django", "python", "unit_testing" ]
stackoverflow_0006575687_django_python_unit_testing.txt
Q: How to replace Unicode values using re in Python? How to replace unicode values using re in Python ? I'm looking for something like this: line.replace('Ã','') line.replace('¢','') line.replace('â','') Or is there any way which will replace all the non-ASCII characters from a file. Actually I converted PDF file ...
How to replace Unicode values using re in Python?
How to replace unicode values using re in Python ? I'm looking for something like this: line.replace('Ã','') line.replace('¢','') line.replace('â','') Or is there any way which will replace all the non-ASCII characters from a file. Actually I converted PDF file to ASCII, where I'm getting some non-ASCII characters [...
[ "Why you want to replace if you have\ntitle.decode('latin-1').encode('utf-8')\n\nor if you want to ignore\nunicode(title, errors='replace')\n\n", "Edit after feedback in comments.\nAnother solution would be to check the numeric value of each character and see if they are under 128, since ascii goes from 0 - 127. ...
[ 1, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006581701_python_regex.txt
Q: How to get the user email from auth.User when filterring a field in UserProfile? I have a situation where i need to query the UserProfile model but need to get for every user record a field from the auth.User model: groups_list = User.objects.filter(status__in=group_list).values_list('email', flat=True) Where "st...
How to get the user email from auth.User when filterring a field in UserProfile?
I have a situation where i need to query the UserProfile model but need to get for every user record a field from the auth.User model: groups_list = User.objects.filter(status__in=group_list).values_list('email', flat=True) Where "status" in the filter is from the UserProfile model. Can any one help me with this? Than...
[ "I think this is what you need.\nThus it'll be something like:\ngroups_list = User.objects.filter(userprofile__status__in=group_list).values_list('email', flat=True)\n\n", "In your UserProfile model make sure that the foreign key to User has related_name='profile' set. You can then do the following:\ngroups_li...
[ 1, 1 ]
[]
[]
[ "django", "django_models", "django_queryset", "django_views", "python" ]
stackoverflow_0006582183_django_django_models_django_queryset_django_views_python.txt
Q: Is it possible to measure packet rate with libpcap? I have a python script, that uses libpcap (pcapy) to capture some specific packets, for example, packets from 10.1.1.1 to 10.2.2.2. Is it possible to measure that data transfer rate? I mean, we can get a size of packet, but as I understand, we can't find out how ...
Is it possible to measure packet rate with libpcap?
I have a python script, that uses libpcap (pcapy) to capture some specific packets, for example, packets from 10.1.1.1 to 10.2.2.2. Is it possible to measure that data transfer rate? I mean, we can get a size of packet, but as I understand, we can't find out how long did it take to transfer that packet. Is there some a...
[ "You could use time to time how long it takes to get the packet:\nimport time\nstart = time.time()\n# do something you want to time\nelapsed = time.time() - start\n\n" ]
[ 0 ]
[]
[]
[ "libpcap", "pcap", "python" ]
stackoverflow_0006581676_libpcap_pcap_python.txt
Q: How to avoid copy of a non-global numpy array between process? I've read " Is shared readonly data copied to different processes for Python multiprocessing? " but the array described there is global. Is it possible to do the same with local arrays ?
How to avoid copy of a non-global numpy array between process?
I've read " Is shared readonly data copied to different processes for Python multiprocessing? " but the array described there is global. Is it possible to do the same with local arrays ?
[]
[]
[ "I don't think so - but you can save stuff to a module variable. If you do this before the fork (and you are not on windows) it should work fine.\nEg\nimport mymodule\n\ndef somefunc(parameter):\n # do something with mymodule.var\n\n# load/process local data\n# save to module variable\nmymodule.var = var\n# now ...
[ -1 ]
[ "arrays", "copy", "multiprocessing", "numpy", "python" ]
stackoverflow_0006579829_arrays_copy_multiprocessing_numpy_python.txt
Q: Multiple 'endings' to a function - return an object, return a string, raise an exception? This one's a structure design problem, I guess. Back for some advice. To start: I'm writing a module. Hence the effort of making it as usable to potential developers as possible. Inside an object (let's call it Swoosh) I have...
Multiple 'endings' to a function - return an object, return a string, raise an exception?
This one's a structure design problem, I guess. Back for some advice. To start: I'm writing a module. Hence the effort of making it as usable to potential developers as possible. Inside an object (let's call it Swoosh) I have a method which, when called, may result in either success (a new object is returned -- for ins...
[ "As much as I like the approach of handling both cases with specifically-typed exceptions, I'm going to offer a different approach in case it helps: callbacks.\nCallbacks tend to work better if you're already using an asynchronous framework like Twisted, but that's not their only place. So you might have a method t...
[ 6, 5, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006582741_python.txt
Q: python import the same file name programatically from different folders I have the following structure sites - SiteA - Settings.py - SiteA - Settings.py - SiteA - Settings.py all the settings.py file has a variable DOMAIN_KEY = '' Is there a way to programmically import this structure and loo...
python import the same file name programatically from different folders
I have the following structure sites - SiteA - Settings.py - SiteA - Settings.py - SiteA - Settings.py all the settings.py file has a variable DOMAIN_KEY = '' Is there a way to programmically import this structure and look through this variable in all the setting files and print it? EDIT (Updated ...
[ "Supposing you do not have duplicate file names you can access these modules and its variables like this:\nimport SiteA.Settings as A, SiteB.Settings as B, SiteC.Settings as C\nprint(A.DOMAIN_KEY, B.DOMAIN_KEY, C.DOMAIN_KEY)\n\nEDIT: Another option would be the __import__() statement, that lets you load a module wi...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0006583058_python.txt
Q: Download file with low priority using Python and urllib2 I'm writing simple tool to keep every image that I've copied (URL of image) I'm using pythoncom and pyhook to catch keyboard "Copy" combination. The problem here is that when Image starts downloading it causes major slowdown, so I have to wait for 0.5-2 seco...
Download file with low priority using Python and urllib2
I'm writing simple tool to keep every image that I've copied (URL of image) I'm using pythoncom and pyhook to catch keyboard "Copy" combination. The problem here is that when Image starts downloading it causes major slowdown, so I have to wait for 0.5-2 seconds for script to finish. Here's the code: response = urllib2....
[ "The question in its current state (unedited) is not really that clear. But I am under the impression your problem is the fact you have to download the image from somewhere before processing it. To get around that, I would use either of the two:\n\nPre-emptive downloading. You start download the image(s) that is mo...
[ 2 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0006583164_python_urllib2.txt
Q: Is there a way to send a user email when user object is created? In the system I am building user CAN NOT register them selves. The users are added by one of the system admins. So there is no user registration form or view. The registration is only being done in the admin so I guess that the send_mail has to be ov...
Is there a way to send a user email when user object is created?
In the system I am building user CAN NOT register them selves. The users are added by one of the system admins. So there is no user registration form or view. The registration is only being done in the admin so I guess that the send_mail has to be over there also (or am I wrong)? I need to send an automatic email to th...
[ "You can register a callback on the post_save signal for the User model. Somewhere along the lines of:\n# note: untested code\n\nfrom django.db.models.signals import post_save\nfrom django.contrib.auth.models import User\n\ndef email_new_user(sender, **kwargs):\n if kwargs[\"created\"]: # only for new users\n ...
[ 6, 2, 1 ]
[]
[]
[ "django", "django_admin", "django_authentication", "python" ]
stackoverflow_0006583212_django_django_admin_django_authentication_python.txt
Q: Django/httplib : transmitting request.raw_post_data with httplib "AAaarg" ! Please HeLp !!! Here is what I am trying to do ... I have a Django site site1, which needs to access the API of another service site2. However, in order to do that, site1 needs to use its own login credentials and stuff ... Therefore I ha...
Django/httplib : transmitting request.raw_post_data with httplib
"AAaarg" ! Please HeLp !!! Here is what I am trying to do ... I have a Django site site1, which needs to access the API of another service site2. However, in order to do that, site1 needs to use its own login credentials and stuff ... Therefore I have written a small Django app, which duplicates urls of site2, but und...
[ "From this: http://bugs.python.org/issue11898#msg138059 it looks like you might be okay if you ensure that the url argument is coerced into a str.\n" ]
[ 1 ]
[]
[]
[ "django", "encoding", "httplib", "python", "unicode" ]
stackoverflow_0006582955_django_encoding_httplib_python_unicode.txt
Q: Create event for another owner using Facebook Graph API I'm at the moment working on a web page where the users who visit it should have the possibility to create an event in my web page's name. There is a Page on Facebook for the web page which should be the owner of the user created event. Is this possible? All ...
Create event for another owner using Facebook Graph API
I'm at the moment working on a web page where the users who visit it should have the possibility to create an event in my web page's name. There is a Page on Facebook for the web page which should be the owner of the user created event. Is this possible? All users are authenticated using Facebook Connect, but since the...
[ "This is possible, using the access token provided for your page you can publish to this as you would with a user. If you want to post FROM the USER than you need to use the current user's access token, if you want to post FROM the PAGE then using the access token from the page you can publish to that\n" ]
[ 0 ]
[]
[]
[ "django", "facebook", "python" ]
stackoverflow_0003005640_django_facebook_python.txt
Q: how can i optimize a django oracle connection? I work with Oracle Database and lastest Django but when i use the default user model is the query very slow what can i do? A: The solution was to add an index.
how can i optimize a django oracle connection?
I work with Oracle Database and lastest Django but when i use the default user model is the query very slow what can i do?
[ "The solution was to add an index.\n" ]
[ 2 ]
[]
[]
[ "django", "django_models", "model", "oracle", "python" ]
stackoverflow_0004625835_django_django_models_model_oracle_python.txt
Q: GC Doesn't Delete Circular References in WeakKeyDictionaries? I have a situation in which I'd like to maintain a mapping from one object to another for as long as the first object exists. My first thought was to use a WeakKeyDictionary. import weakref import gc class M: pass w = weakref.WeakKeyDictionary() m...
GC Doesn't Delete Circular References in WeakKeyDictionaries?
I have a situation in which I'd like to maintain a mapping from one object to another for as long as the first object exists. My first thought was to use a WeakKeyDictionary. import weakref import gc class M: pass w = weakref.WeakKeyDictionary() m = M() w[m] = some_other_object del m gc.collect() print w.keys() ...
[ "You don't really have circular references in these examples. Your circle goes like:\nWeakKeyDict -> value -> key -> ...\nSo the dict keeps the value alive, which in turn keeps the key alive, and through a separate mechanism that does not involve a strong reference, the key instructs the dict to keep the value aliv...
[ 2, 1 ]
[]
[]
[ "garbage_collection", "python", "weak_references" ]
stackoverflow_0006210024_garbage_collection_python_weak_references.txt
Q: how to update a wxlistbox from a different class? i have a wxlistbox in a class and i want to update the data inside the listbox from a different class.Is i possible to reload the class while leave the control from another class?if yes ,how? eg: i have two classes,Class A and Class B.In class A there is a wxlistbo...
how to update a wxlistbox from a different class?
i have a wxlistbox in a class and i want to update the data inside the listbox from a different class.Is i possible to reload the class while leave the control from another class?if yes ,how? eg: i have two classes,Class A and Class B.In class A there is a wxlistbox.while starting the program class A initilise the wxli...
[ "I would use the SetItems() method, which according to the docs does the following: \"Clear and set the strings in the control from a list\".\nEdit: myListCtrl.SetItems(ListOfStrings)\nThat will replace all the items in the control with whatever is in the list.\n" ]
[ 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0006581744_python_wxpython.txt
Q: Optparse callback not consuming argument I'm trying to get to know optparse a bit better, but I'm struggling to understand why the following code behaves the way it does. Am I doing something stupid? import optparse def store_test(option, opt_str, value, parser, args=None, kwargs=None): print 'opt_str:', opt_...
Optparse callback not consuming argument
I'm trying to get to know optparse a bit better, but I'm struggling to understand why the following code behaves the way it does. Am I doing something stupid? import optparse def store_test(option, opt_str, value, parser, args=None, kwargs=None): print 'opt_str:', opt_str print 'value:', value op = optparse.O...
[ "You're missing a \"type\" or \"nargs\" option attribute:\nop.add_option('-t', '--test', action='callback', callback=store_test, default='test',\n dest='test', help='test!', type='str')\n\nThis option will cause it to consume the next argument.\nReference:\nhttp://docs.python.org/library/optparse.html#optparse-o...
[ 6 ]
[]
[]
[ "optparse", "python" ]
stackoverflow_0006583963_optparse_python.txt
Q: Django installing packages via symlinking Is it possible to "install" third party django packages by sym linking them into your site directory? For example, I'd like to use the django-registration package. However, I don't want to install django-registration into my site-packages directory. I'd rather just link d...
Django installing packages via symlinking
Is it possible to "install" third party django packages by sym linking them into your site directory? For example, I'd like to use the django-registration package. However, I don't want to install django-registration into my site-packages directory. I'd rather just link django-registration/registration into my project...
[ "If you can, it's better to include the packages as an svn external / git module / etc. That way they're always available, even to others that checkout your project.\nShort of that, virtualenv is the better solution. You still \"install\" the packages, but they are added to the virtual environment (hence the name)....
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006583593_django_python.txt
Q: Paramiko and "remote python" I would like to be able to control a remote Python interpreter over an SSH connection, and drive it from Python itself. I've got a basic template: ssh.connect(servername, serverport, username, key_filename=key_filename) transport = ssh.get_transport() channel = transport.open_session...
Paramiko and "remote python"
I would like to be able to control a remote Python interpreter over an SSH connection, and drive it from Python itself. I've got a basic template: ssh.connect(servername, serverport, username, key_filename=key_filename) transport = ssh.get_transport() channel = transport.open_session() channel.exec_command(PATH_TO_E...
[ "Depending from what your goal is, you could follow one of these two ways (I'm sure there are several other alternatives, though!).\nIf you want to control execution of scripts on remote machines via python you could try Fabric. From their website:\n\nFabric is a Python (2.5 or higher) library and command-line tool...
[ 2, 2 ]
[]
[]
[ "paramiko", "python" ]
stackoverflow_0006584288_paramiko_python.txt
Q: What is the precedence of python compiled files in imports? Python files are compiled to bytecode (*.pyc). Using Cython you can compile them to machine code (*.so in Linux). If you use have both files in the same folder, under the same name what is the precedence between them? Is there an automatic way to ensure ...
What is the precedence of python compiled files in imports?
Python files are compiled to bytecode (*.pyc). Using Cython you can compile them to machine code (*.so in Linux). If you use have both files in the same folder, under the same name what is the precedence between them? Is there an automatic way to ensure that the *.so file is used instead of the *.pyc one? Or you have ...
[ "Python will load the .so file first. See this question for an ordered list of the suffixes that python searches for. \nWell, I'll just tell you: \nfoo (a directory)\nfoo.so\nfoomodule.so\nfoo.py\nfoo.pyc\n\n" ]
[ 11 ]
[]
[]
[ "bytecode", "compilation", "cython", "python" ]
stackoverflow_0006584457_bytecode_compilation_cython_python.txt
Q: Regex for file encoded with CP1252 I have a CP1252 encoded text file, where I match patterns using python regex. For example, the following text can be matched by regex string '1\s*(\w*)\s*(<.*$)' 1 kAMpleksa <fs af='kAMpleksa,unk,,,,,,'> But when the text contains special characters like the accented 'U'...
Regex for file encoded with CP1252
I have a CP1252 encoded text file, where I match patterns using python regex. For example, the following text can be matched by regex string '1\s*(\w*)\s*(<.*$)' 1 kAMpleksa <fs af='kAMpleksa,unk,,,,,,'> But when the text contains special characters like the accented 'U' in the following text, the regex fails ...
[ "This works on both my machines, but I'm copying and pasting the text in, so there might be some invisible translation happening. Have you tried setting the unicode flag? As in \n'(?u)1\\s*(\\w*)\\s*(<.*$)'\n\nor\nre.match(r, t, flags=re.U).group()\n\n", "You forgot to specify re.U in the flags.\n" ]
[ 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006584767_python_regex.txt
Q: How do I track 400 keywords with Twitter using the Streaming API? I have 400 urls that I want to track in the Streaming API, and I'm allowed to have 400 keywords (the urls) to track as per the streaming api. However, the url I end up querying with is too large for a standared post request and doesn't work. In the...
How do I track 400 keywords with Twitter using the Streaming API?
I have 400 urls that I want to track in the Streaming API, and I'm allowed to have 400 keywords (the urls) to track as per the streaming api. However, the url I end up querying with is too large for a standared post request and doesn't work. In the Twitter Docs, it says increaded access levels allow up to 10000 keywor...
[ "Your question seems a little confusing -- I assume you must be doing GET rather than POST, as there's no real limit on POSTs. From the API docs:\n\nPlacing long parameters in the URL may\n cause the request to be rejected for\n excessive URL length. Use a POST\n request header parameter to avoid long\n URLs.\...
[ 1 ]
[]
[]
[ "python", "streaming", "twitter" ]
stackoverflow_0006571639_python_streaming_twitter.txt
Q: Python: Multi-Dimensional Array Using ctypes? How do I define a multi-dimensional float array using ctypes in python? Is there a limitation to the number of dimensions that can be defines? A: Here's one quick-and-dirty method: >>> A = ((ctypes.c_float * 10) * 10) >>> a = A() >>> a[5][5] 0.0
Python: Multi-Dimensional Array Using ctypes?
How do I define a multi-dimensional float array using ctypes in python? Is there a limitation to the number of dimensions that can be defines?
[ "Here's one quick-and-dirty method:\n>>> A = ((ctypes.c_float * 10) * 10)\n>>> a = A()\n>>> a[5][5]\n0.0\n\n" ]
[ 9 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0006585031_ctypes_python.txt
Q: scapy independent layers, no encapsulation I try to create a protocol, and I have some understanding problems. I created a class for every layer. Then I created some methods that build the packets for me, by stacking the layers one above the other. When I create a packet: a=Foo()/Bar() (or a=test()) I get somethi...
scapy independent layers, no encapsulation
I try to create a protocol, and I have some understanding problems. I created a class for every layer. Then I created some methods that build the packets for me, by stacking the layers one above the other. When I create a packet: a=Foo()/Bar() (or a=test()) I get something like: <Foo | <Bar |>>, this means, to my un...
[ "If you don't want Bar inside Foo, I don't understand why you aren't using a list... for instance this is a list of two pings to 10.2.2.2... [IP(dst=\"10.2.2.2\") / ICMP(), IP(dst=\"10.2.2.2\") / ICMP()]\nsr([IP(dst=\"10.2.2.2\") / ICMP(), IP(dst=\"10.2.2.2\") / ICMP()])\nBegin emission:\n........................*F...
[ 2 ]
[]
[]
[ "python", "scapy" ]
stackoverflow_0006572253_python_scapy.txt
Q: Updating Dictionaries in Python I'm reading per line a file and creating new entries for my dictionary: Suppose that the first line after parsing and splitting will have an entry like this: dict = {"A":{"B":1}, "G":{"P":2}}.... then I continue to line 2 and say there is an arbitrary lines to read: And both keys "...
Updating Dictionaries in Python
I'm reading per line a file and creating new entries for my dictionary: Suppose that the first line after parsing and splitting will have an entry like this: dict = {"A":{"B":1}, "G":{"P":2}}.... then I continue to line 2 and say there is an arbitrary lines to read: And both keys "A", and "G" appeared again along with...
[ "This would be easier to show with an example of the file. But it's easy enough:\nfrom collections import defaultdict\nmydict = defaultdict(dict)\nfor line in file:\n for outerkey, innerkey, value in parseline(line):\n mydict[outerkey][innerkey] = value\n\nThis would still overwrite the \"H\" value in {\"...
[ 2, 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006585152_python.txt
Q: Python: 64bit Numpy? I am currently working with numpy on a 32bit system (Ubuntu 10.04 LTS). Can I expect my code to work fluently, in the same manner, on a 64bit (Ubuntu) system? Does numpy have an compatibility issues with 64bit python? A: NumPy has been used on 64-bit systems of all types for years now. I dou...
Python: 64bit Numpy?
I am currently working with numpy on a 32bit system (Ubuntu 10.04 LTS). Can I expect my code to work fluently, in the same manner, on a 64bit (Ubuntu) system? Does numpy have an compatibility issues with 64bit python?
[ "NumPy has been used on 64-bit systems of all types for years now. I doubt you will find anything new that doesn't show up elsewhere as well.\n", "There are official Ubuntu packages and the installation instructions explicitly mention AMD64 as a target plattform: Installing SciPy/Linux. \nThe code uses type ident...
[ 4, 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0006585176_numpy_python.txt
Q: Python Imaging Library (PIL) in virtualenv on windows I've got a python program that is using a ridiculous amount of extensions, so I'm trying to set up a virtualenv for it. However, one of the libraries it uses is PIL. After installing it, I get an import error on PIL. This problem has been identified at the link...
Python Imaging Library (PIL) in virtualenv on windows
I've got a python program that is using a ridiculous amount of extensions, so I'm trying to set up a virtualenv for it. However, one of the libraries it uses is PIL. After installing it, I get an import error on PIL. This problem has been identified at the link below, but the solution there does not work for me (possib...
[ "The issue was whether I was importing PIL.Image or simply Image. The virtualenv used Image, whereas my Python installation used PIL.image.\n" ]
[ 0 ]
[]
[]
[ "distutils", "python", "python_imaging_library", "virtualenv", "windows" ]
stackoverflow_0006540752_distutils_python_python_imaging_library_virtualenv_windows.txt
Q: How to convert varying formats of a string into a list of int? (python) m = re.match(r'(\d+)(?:-(\d+))?$', string) start = m.group(1) end = m.group(2) or start return list(range(int(start, 10), int(end, 10) + 1)) Right now this is able to handle strings in the following format and convert them into a list... '0-6...
How to convert varying formats of a string into a list of int? (python)
m = re.match(r'(\d+)(?:-(\d+))?$', string) start = m.group(1) end = m.group(2) or start return list(range(int(start, 10), int(end, 10) + 1)) Right now this is able to handle strings in the following format and convert them into a list... '0-6' results in [0,1,2,3,4,5,6] '7' results in [7] Is there anyway I can change ...
[ "Regular expressions are not all there is to life. In this case, there's really no reason to use regular expressions. Try this, it's over twice as fast as, for example, Shawn Chin's to_num_list on the sample data '0-6 2 3-6' (for all data I tried on it it was between about 1.9 and 4.5 times as fast):\ndef included_...
[ 6, 3, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006585266_python_regex.txt
Q: Problem setting up MySQL with python on OSX 10.6 I'm trying to install MySQL on OSX 10.6 to work with Django. MySQL seems to have installed correctly. I'm attempting to install MySQLdb for Python I've tried using easy_install $ python setup.py install Which completes But I'm getting the follow error: Python 2.7....
Problem setting up MySQL with python on OSX 10.6
I'm trying to install MySQL on OSX 10.6 to work with Django. MySQL seems to have installed correctly. I'm attempting to install MySQLdb for Python I've tried using easy_install $ python setup.py install Which completes But I'm getting the follow error: Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) [GCC 4...
[ "Check to make sure the mysql client library (the C client library) is properly installed. Look in /usr/include or /usr/local/include for for a folder called \"mysql\". Do the same for /usr/lib or /usr/local/lib. \n" ]
[ 0 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0006585951_django_mysql_python.txt
Q: Python web frameworks vs Java web frameworks (how is web development in Python done?) I am thinking in starting a personal pet web project to experiment with different things and extend my knowledge. I use Java a lot at work (for web applications :D) and was thinking in making my own in Python since I kinda like t...
Python web frameworks vs Java web frameworks (how is web development in Python done?)
I am thinking in starting a personal pet web project to experiment with different things and extend my knowledge. I use Java a lot at work (for web applications :D) and was thinking in making my own in Python since I kinda like this language but never passed the simple scripts stages. I want to step up a gear regardi...
[ "hi try bottle python framework (bottle.paws.de / bottlepy.org) its really nice to use blistering fast and gets out of your way + the best thing about it is that its one single file to import, i recently migrated from PHP and i have to tell you am so ... loving it!\n", "It may sound strange, but there's no need t...
[ 3, 2, 2, 2 ]
[]
[]
[ "java", "python", "templates", "web_frameworks" ]
stackoverflow_0004909306_java_python_templates_web_frameworks.txt
Q: Why WSGIDaemonProcess isn't available on Windows? Why isn't WSGIDaemonProcess available on Windows? A: http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode On the Windows platform there is no daemon mode only embedded mode. The MPM used on Apache is the 'winnt' MPM. This MPM is like the worker MPM on...
Why WSGIDaemonProcess isn't available on Windows?
Why isn't WSGIDaemonProcess available on Windows?
[ "http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode\n\nOn the Windows platform there is no\n daemon mode only embedded mode. The\n MPM used on Apache is the 'winnt' MPM.\n This MPM is like the worker MPM on\n UNIX systems except that there is only\n one process.\n\nSeems pretty clear. Need more informa...
[ 6 ]
[]
[]
[ "apache", "mod_wsgi", "python" ]
stackoverflow_0006586412_apache_mod_wsgi_python.txt
Q: How to communicate ONLY IN UNICODE with MySQL Database using OurSQL in python? I was reading the documentation of oursql and encountered this description for establishing a connection: By default, oursql will try to use unicode wherever possible, and set the connection charset to utf8. My tables and all the colu...
How to communicate ONLY IN UNICODE with MySQL Database using OurSQL in python?
I was reading the documentation of oursql and encountered this description for establishing a connection: By default, oursql will try to use unicode wherever possible, and set the connection charset to utf8. My tables and all the columns store every string in utf8. Does this mean, when I connect to my database like t...
[ "You should be able to, yes. My guess is you just need to set the MySQL character set connection variables. SET NAMES is usually sufficient.\n" ]
[ 0 ]
[]
[]
[ "mysql", "python", "unicode", "utf_8" ]
stackoverflow_0006445508_mysql_python_unicode_utf_8.txt
Q: Using openssl with IronPython on a hosted website I have a python script which calls the following: signature = Popen(["openssl", "sha1", "-sign", key, input], stdout=PIPE).stdout.read(); I need to run this script through IronPython on a hosted website. Is it possible to use openssl and somehow reference it? I lo...
Using openssl with IronPython on a hosted website
I have a python script which calls the following: signature = Popen(["openssl", "sha1", "-sign", key, input], stdout=PIPE).stdout.read(); I need to run this script through IronPython on a hosted website. Is it possible to use openssl and somehow reference it? I looked into an alternative using M2Crypto but unfortunate...
[ "I don't know if .NET's crypto libraries can do what you need, but that's always an option with IronPython.\nOtherwise, you should be able to install OpenSSL on Windows and use the code you gave as-is.\n" ]
[ 1 ]
[]
[]
[ "asp.net", "ironpython", "m2crypto", "openssl", "python" ]
stackoverflow_0006563090_asp.net_ironpython_m2crypto_openssl_python.txt
Q: Data Manipulation: Stemming from a inability to select lists I am very new to python with no real prior programing knowledge. At my current job I am being asked to take data in the form of text from about 500+ files and plot them out. I understand the plotting to a degree, but I cannot seem to figure out how to ma...
Data Manipulation: Stemming from a inability to select lists
I am very new to python with no real prior programing knowledge. At my current job I am being asked to take data in the form of text from about 500+ files and plot them out. I understand the plotting to a degree, but I cannot seem to figure out how to manipulate the data in a way that it is easy to select specific sect...
[ "The easiest way to get a list of lines from a file is as follows:\nwith open('file', 'r') as f:\n lines = f.readlines()\n\nNow you can split those lines or do whatever you want with them:\nlines = [line.split() for line in lines]\n\nI'm not certain that answers your question -- let me know if you have something...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0006586651_python.txt
Q: django - How can I render a template I use everywhere in my webpage? I'm using django 1.2.4. I have a template for login in registration/login.html (wich action is django.contrib.auth.views.login) and I want to include it on everypage. I created a block on my base.html as I do for every template. The thing is the...
django - How can I render a template I use everywhere in my webpage?
I'm using django 1.2.4. I have a template for login in registration/login.html (wich action is django.contrib.auth.views.login) and I want to include it on everypage. I created a block on my base.html as I do for every template. The thing is the browser doesn't recognize this login block and I think it is because I on...
[ "I think you are looking for the include tag. This way you can include your login html snippet in your base.html :\n{% include \"/registration/login.html\" %}\n\n", "What I really need was to create a templatetag in templatetags/mytags.py, where I define a function called get_login wich looks like this:\n@registe...
[ 3, 0 ]
[]
[]
[ "django", "python", "render", "templates", "view" ]
stackoverflow_0006479477_django_python_render_templates_view.txt
Q: parse comma separated csv file with quotes in python Below i have a string which represents a single row pulled from a csv file. Each column is separated by a comma and the value is wrapped in "". What is the simplest way to parse out the value from each column in python? "Mr","Bob","","Boberton","","President",""...
parse comma separated csv file with quotes in python
Below i have a string which represents a single row pulled from a csv file. Each column is separated by a comma and the value is wrapped in "". What is the simplest way to parse out the value from each column in python? "Mr","Bob","","Boberton","","President","","","","Blah, Inc. of Iowa","blah blah blah","","Grand Isl...
[ "Python has a module for that:\nhttp://docs.python.org/library/csv.html\nimport csv, sys\nfilename = 'some.csv'\nwith open(filename, 'rb') as f:\n reader = csv.reader(f)\n try:\n for row in reader:\n print row\n except csv.Error, e:\n sys.exit('file %s, line %d: %s' % (filename, re...
[ 16 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0006586748_csv_python.txt
Q: Organizing an array of points in python I need to input 3, 3D points as a matrix into this function; so I made a tuple like this one: initPoints = ([10,20,30],[5,15,25],[100,150,200]) but I got the following error: AttributeError: 'tuple' object has no attribute 'shape' The same thing happened when i used a list...
Organizing an array of points in python
I need to input 3, 3D points as a matrix into this function; so I made a tuple like this one: initPoints = ([10,20,30],[5,15,25],[100,150,200]) but I got the following error: AttributeError: 'tuple' object has no attribute 'shape' The same thing happened when i used a list. any ideas? what is 'shape'? do i need some ...
[ "Perhaps the function is expecting a numpy array or matrix instead of a tuple of lists?\nhttp://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html\nhttp://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.html\n>>> import numpy\n>>> a = numpy.array(((1,2,3),(4,5,6)))\n>>> a.shape\n(2, 3)\n\nWe'd ...
[ 4, 3 ]
[]
[]
[ "arrays", "python", "scipy" ]
stackoverflow_0006586712_arrays_python_scipy.txt
Q: no cpickle module When I tried import cpikcle as pickle I got an error message saying no module named cpickle. Does anybody know how to get cpickle module? Because I heard that cpickle is faster than pickle. Thanks A: Try import cPickle as pickle instead. Note the upper-case 'P'. Also, you misspelled cPickle ...
no cpickle module
When I tried import cpikcle as pickle I got an error message saying no module named cpickle. Does anybody know how to get cpickle module? Because I heard that cpickle is faster than pickle. Thanks
[ "Try import cPickle as pickle instead. Note the upper-case 'P'. Also, you misspelled cPickle as cpikcle in your question.\n" ]
[ 10 ]
[]
[]
[ "python" ]
stackoverflow_0006586888_python.txt
Q: How to build and run emesene on OS X using Git Anyone knows how to build and run emesene - the chat client in Python - on OS X once you get the code from GitHub? I have searched online and I cannot find a source that is working. I did find some documents on sidhosting website. But that did not work for me complete...
How to build and run emesene on OS X using Git
Anyone knows how to build and run emesene - the chat client in Python - on OS X once you get the code from GitHub? I have searched online and I cannot find a source that is working. I did find some documents on sidhosting website. But that did not work for me completely. Hence I need help here. Thanks Sumod
[ "Have you tried running python setup.py install in the emesene directory?\n" ]
[ 2 ]
[]
[]
[ "git", "python" ]
stackoverflow_0006586793_git_python.txt
Q: Haskell vs. Python threading model Maybe there's someone out there with the right interests that will know how to answer this. Basically the question is: What are the differences between the multiprocessing module in Python, and the parallelism in Haskell. For instance: are threads created in Python mapped to OS t...
Haskell vs. Python threading model
Maybe there's someone out there with the right interests that will know how to answer this. Basically the question is: What are the differences between the multiprocessing module in Python, and the parallelism in Haskell. For instance: are threads created in Python mapped to OS threads? If so, what if there are more th...
[ "As opposed to Python (See Eli's answer), the threading model of Haskell is quite different. You have a difference between concurrency (multiple threads handling different aspects of the program) and parallelism (multiple threads just to speed up computation). Both are handled by lightweight threads managed by the ...
[ 7, 6 ]
[]
[]
[ "haskell", "multicore", "python" ]
stackoverflow_0006587095_haskell_multicore_python.txt
Q: Python module not found How do I import pyBarcode from the Python interpreter? According to the pyBarcode documentation the first step is to import barcode. When I try that it says there is no such module. ~# python Python 2.6.6 (r266:84292, Dec 26 2010, 22:31:48) [GCC 4.4.5] on linux2 >>> import barcode Tracebac...
Python module not found
How do I import pyBarcode from the Python interpreter? According to the pyBarcode documentation the first step is to import barcode. When I try that it says there is no such module. ~# python Python 2.6.6 (r266:84292, Dec 26 2010, 22:31:48) [GCC 4.4.5] on linux2 >>> import barcode Traceback (most recent call last): Fi...
[ "Before using (importing) pyBarcode, you must install it, for instance with\npip install pyBarcode\n\n", "Make sure that the directory that contains the module is in your PYTHONPATH environment variable.\nAlternatively, you can use\nimport sys\nsys.path.append(r\"C:\\path to pyBarcode\")\nimport barcode\n\n" ]
[ 5, 5 ]
[]
[]
[ "python" ]
stackoverflow_0006587382_python.txt
Q: How does pyodbc determine the encoding? I'm fighting Sybase SQL Anywhere 12 together with Python (and Twisted) for several weeks by now and I even got my stuff working. There's only one annoyance left: If I run my script on CentOS 5 with a custom Python 2.7.1, which is the deployment platform, I get my results as ...
How does pyodbc determine the encoding?
I'm fighting Sybase SQL Anywhere 12 together with Python (and Twisted) for several weeks by now and I even got my stuff working. There's only one annoyance left: If I run my script on CentOS 5 with a custom Python 2.7.1, which is the deployment platform, I get my results as UTF-8. If I run it on my Ubuntu box (Natty Na...
[ "I can't tell you why it's different, but if you add \"Charset=utf-8\" to your DSN, you should get the results you want on both machines.\nDisclaimer: I work for Sybase in SQL Anywhere engineering.\n", "pyodbc uses the ODBC specification, which only supports 2 encodings. All ODBC functions that end with 'W' are ...
[ 4, 4 ]
[]
[]
[ "pyodbc", "python", "sqlanywhere", "unixodbc" ]
stackoverflow_0005884504_pyodbc_python_sqlanywhere_unixodbc.txt
Q: Python API - pattern for creating optional parenthesis? I am designing the API for a Python library, and have run into a situation where I think my imagination might have overtaken Python's considerable abilities. (I want to apologize to any Pythonistas who may get offended by the Ruby-ness of my design) Basically...
Python API - pattern for creating optional parenthesis?
I am designing the API for a Python library, and have run into a situation where I think my imagination might have overtaken Python's considerable abilities. (I want to apologize to any Pythonistas who may get offended by the Ruby-ness of my design) Basically, there is a class with a few methods on it, each of which re...
[ "I think you're nuts for wanting to do this. What reason do you have? What about methods that take arguments? (See example below.)\nIt seems to work for methods without arguments if you use __getattribute__ instead of __getattr__.\nWorking example:\nclass Test(object):\n def __getattribute__(self, name):\n ...
[ 3, 3 ]
[]
[]
[ "function", "python" ]
stackoverflow_0006587858_function_python.txt
Q: How do you display greek characters on a PyQt4 GUI? I am a bit of a noob, so forgive me if this is a simple question. I am writing a program to perform scientific simulations, some of the parameters for which are measured in micrometres. The suffix for such parameters is µm where the greek symbol mu preceeds the m...
How do you display greek characters on a PyQt4 GUI?
I am a bit of a noob, so forgive me if this is a simple question. I am writing a program to perform scientific simulations, some of the parameters for which are measured in micrometres. The suffix for such parameters is µm where the greek symbol mu preceeds the m for metre. Ideally i would like to set the suffix for my...
[ "Using unicode object instead of simple string:\n# -*- coding: utf8 -*-\n\n# Your code ...\n\nspin1 = QtGui.QDoubleSpinBox()\nspin1.setSuffix(u\"µm\")\n\n" ]
[ 4 ]
[]
[]
[ "pyqt4", "python", "python_2.6", "qspinbox" ]
stackoverflow_0006587857_pyqt4_python_python_2.6_qspinbox.txt
Q: PyQt: Access objects while using threading I’m currently working on a small markdown-editor, but I have a problem: While being very fast, the markdown module can’t do magic, and because it processes the whole text every time something is changed, the program will become unresponsive when e.g. holding down backspac...
PyQt: Access objects while using threading
I’m currently working on a small markdown-editor, but I have a problem: While being very fast, the markdown module can’t do magic, and because it processes the whole text every time something is changed, the program will become unresponsive when e.g. holding down backspace. How can I use threading (subprocess, QThread)...
[ "To me this looks like a job for QThreadPool and QRunnable:\n\nCreate a class deriving from QRunnable, describing a \"render job\"\nCreate a QThreadPool with maxThreadCount set to 1 (very important, because there shall only be a single rendering thread at a time).\nEach time the text changes, create an instance of ...
[ 2, 0 ]
[]
[]
[ "multithreading", "pyqt", "python", "queue" ]
stackoverflow_0006576831_multithreading_pyqt_python_queue.txt
Q: Dynamic user based authorization in Pyramid I'm following security guidelines found on Pyramid docs along with wiki tutorial Adding Authorization Now I need to add restrictions based un single user rather than groups. Let's say for example that, if any blog editor can have permission to review all comments, only ...
Dynamic user based authorization in Pyramid
I'm following security guidelines found on Pyramid docs along with wiki tutorial Adding Authorization Now I need to add restrictions based un single user rather than groups. Let's say for example that, if any blog editor can have permission to review all comments, only post author can edit the post itself. For the fir...
[ "You already have a \"Resource Tree\" by creating the Root resource in your project. You just need to add a node on it for posts that will return a Post object with a particular __acl__ that contains only the authorized user id. You can then have your edit_posts route use traverse='/posts/{post_id}' to traverse you...
[ 8, 4 ]
[]
[]
[ "authorization", "pyramid", "python" ]
stackoverflow_0006585370_authorization_pyramid_python.txt
Q: Writing UTF-8 friendly parsers in python I wrote a simple file parser and writer, but then I came across an article talking about the importance of unicode and then it occurred to me that I'm assuming the input file is ascii encoded, which may not be the case all the time, though it would be rare in my situation. ...
Writing UTF-8 friendly parsers in python
I wrote a simple file parser and writer, but then I came across an article talking about the importance of unicode and then it occurred to me that I'm assuming the input file is ascii encoded, which may not be the case all the time, though it would be rare in my situation. In those rare cases, I would expect UTF-8 enco...
[ "Python natively supports Unicode. If you directly read and write from the first file to the second, then no data is lost as it copies the bytes verbatim. However, if you decode the string and then re-encode it, you'll need to make sure you use the right encoding.\n", "If you are using Python 2, you can simply ch...
[ 3, 3, 2, 0 ]
[]
[]
[ "python", "python_2.7", "unicode_string" ]
stackoverflow_0006588041_python_python_2.7_unicode_string.txt
Q: How to create namespace packages in Python? I have a Python 3 project with the following structure: project/ | +--root/ | +--__init__.py | +--sub/ | +--__init__.py | +--actualcode.py I want to use "namespace packages" so that my lib shares a common namespace with other related ...
How to create namespace packages in Python?
I have a Python 3 project with the following structure: project/ | +--root/ | +--__init__.py | +--sub/ | +--__init__.py | +--actualcode.py I want to use "namespace packages" so that my lib shares a common namespace with other related libs in separate projects. The import statement s...
[ "Namespace packages can be built with distribute. The trick is then to add the following line to the parameter of setup:\nsetup(\n # ...\n namespace_packages = [\"root\"]\n)\n\nThe rest of the example in the question is correct.\n" ]
[ 0 ]
[ "I just tried your example, but it seems to work like you want it to:\n >>> from root.sub.actualcode import foo\n >>> foo()\n Bar!\n\nI ran the Python interpreter from the directory containing the root folder. I created the empty __init__.py files and my actualcode.py looks like this:\n #!/bin/python3\n...
[ -2 ]
[ "distutils", "namespaces", "package", "python" ]
stackoverflow_0006568223_distutils_namespaces_package_python.txt
Q: Getting the event name rather than integer ID in wxPython I have the following code: self.sliderR.Bind(wx.EVT_SCROLL,self.OnSlide) In the function OnSlide I have the inserted the code pdb.set_trace() to help me debug. In the pdb prompt if I type event.GetEventType() it returns a number (10136) but I have no idea w...
Getting the event name rather than integer ID in wxPython
I have the following code: self.sliderR.Bind(wx.EVT_SCROLL,self.OnSlide) In the function OnSlide I have the inserted the code pdb.set_trace() to help me debug. In the pdb prompt if I type event.GetEventType() it returns a number (10136) but I have no idea which event that corresponds to. Does the 10136 refer to the wx....
[ "There isn't a built-in way. You will need to build an event dictionary. Robin Dunn has some code here that will help: http://osdir.com/ml/wxpython-users/2009-11/msg00138.html\nOr you can check out my simple example:\nimport wx\n\nclass MyForm(wx.Frame):\n\n def __init__(self):\n wx.Frame.__init__(self, N...
[ 4 ]
[]
[]
[ "event_handling", "python", "wxpython" ]
stackoverflow_0006553570_event_handling_python_wxpython.txt
Q: Search for a specific value in a specific column with Python I've got a text file that is tab delimited and I'm trying to figure out how to search for a value in a specific column in this file. I think i need to use the csv import but have been unsuccessful so far. Can someone point me in the right direction? Than...
Search for a specific value in a specific column with Python
I've got a text file that is tab delimited and I'm trying to figure out how to search for a value in a specific column in this file. I think i need to use the csv import but have been unsuccessful so far. Can someone point me in the right direction? Thanks! **Update** Thanks for everyone's updates. I know I could proba...
[ "You can also use the sniffer (example taken from http://docs.python.org/library/csv.html)\ncsvfile = open(\"example.csv\", \"rb\")\ndialect = csv.Sniffer().sniff(csvfile.read(1024))\ncsvfile.seek(0)\nreader = csv.reader(csvfile, dialect)\n\n", "Yes, you'll want to use the csv module, and you'll want to set delim...
[ 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006588144_python.txt
Q: What are the different options for interfacing C (or C++) with Python? I know there are many ways to interface C function into Python: the Python C API, scipy.weave, ctypes, pyrex/cython, SWIG, Boost.Python, Psyco... What are each of them best for? Why should I use a given method instead of others? What should be ...
What are the different options for interfacing C (or C++) with Python?
I know there are many ways to interface C function into Python: the Python C API, scipy.weave, ctypes, pyrex/cython, SWIG, Boost.Python, Psyco... What are each of them best for? Why should I use a given method instead of others? What should be considered when I need to choose a binding between Python and C? I know some...
[ "I haven't used all these methods although I have investigated them all at one point or another...\nThe Python C API: For writing C code that compiles to a python module that can be imported in Python. Or for writing a Python module that acts as \"glue\" code to interface with some C library.\nscipy.weave: Allows y...
[ 9, 4 ]
[]
[]
[ "c", "interfacing", "python" ]
stackoverflow_0006587407_c_interfacing_python.txt
Q: asynchronous downloads with wxpython ok so one of my functions is to open a url and read its contents and then write it in a file the problem is when i do that my UI freezes i know that i need to use asynchronous downloads but i dont seem to understand exatcly how to ! the url im openining is about 10-20 mg also ...
asynchronous downloads with wxpython
ok so one of my functions is to open a url and read its contents and then write it in a file the problem is when i do that my UI freezes i know that i need to use asynchronous downloads but i dont seem to understand exatcly how to ! the url im openining is about 10-20 mg also would http://docs.python.org/library/threa...
[ "You can use the asynhttp client to do this, since you can't be bothered to read the docs on threading.\nhttp://code.google.com/p/asynhttp/\n", "Here's an example. The 10 in the call to asyncDownload is the timeout period in seconds. You'll want to increase that, or possibly get rid of it altogether. The downl...
[ 0, 0, 0, 0 ]
[]
[]
[ "python", "urllib", "wxpython" ]
stackoverflow_0006566164_python_urllib_wxpython.txt
Q: XMPP based live-chat system in Django I need to implement an XMPP based live-chat system in Django. After a lot of scourging and ideas from a colleague, we came up with this. Method using a bot: When a visitor visits the site. The visitor's XMPP client which in this case is Strophe.JS begins an XMPP-over-BOSH co...
XMPP based live-chat system in Django
I need to implement an XMPP based live-chat system in Django. After a lot of scourging and ideas from a colleague, we came up with this. Method using a bot: When a visitor visits the site. The visitor's XMPP client which in this case is Strophe.JS begins an XMPP-over-BOSH connection to the XMPP server and connects to...
[ "I wrote exactly this. It's called Seshat and uses a \"broker\" bot between the website and a Jabber server (I use ejabberd). It's in beta right now mainly because it hasn't been extensively tested outside my company.\nNote: while the README specifically mentions the Pyramid web framework, the core system would wor...
[ 2, 1, 1 ]
[]
[]
[ "django", "python", "xmpp" ]
stackoverflow_0006584015_django_python_xmpp.txt
Q: Python cProfile: Is it possible for pyo file I am beginner to Python and trying to invoke the cProfile through command line i.e. python -m cProfile -o ./temp/PROFILE.log myScript.pyo But it throws an error message stating that SyntaxError: Non-ASCII character '\xb3' in file myScript.pyo on line 1, but no encodin...
Python cProfile: Is it possible for pyo file
I am beginner to Python and trying to invoke the cProfile through command line i.e. python -m cProfile -o ./temp/PROFILE.log myScript.pyo But it throws an error message stating that SyntaxError: Non-ASCII character '\xb3' in file myScript.pyo on line 1, but no encoding declared; see http://www.python.org/peps/pep-026...
[ "I'm pretty sure that cProfile makes use of execfile(). The hint comes from the docs ( http://docs.python.org/library/profile.html ):\n\nThis function takes a single argument\n that can be passed to the exec\n statement\n\nexecfile() is unable to execute *.pyc and *.pyo files - it fails with the same exception.\...
[ 1 ]
[]
[]
[ "cprofile", "python" ]
stackoverflow_0006585358_cprofile_python.txt
Q: Machine learning for weighting adjustment I'm trying to work out how to implement some machine learning library to help me find out what the correct weighting for each parameter is in order to make a good decision. In more detail: Context: trying to implement a date of publication extractor for html files. This is...
Machine learning for weighting adjustment
I'm trying to work out how to implement some machine learning library to help me find out what the correct weighting for each parameter is in order to make a good decision. In more detail: Context: trying to implement a date of publication extractor for html files. This is for news sites, so I don't have a generic date...
[ "Given your problem description, the characteristics of yoru data, and your ML background and personal preferences, i would recommend Orange.\nOrange is a mature, free and open source project with a large selection of ML algorithms and excellent documentation and training materials. Most users probably use the GUI ...
[ 11, 2 ]
[]
[]
[ "machine_learning", "python", "weighting" ]
stackoverflow_0006585734_machine_learning_python_weighting.txt
Q: With Jug, how to run nested loops in multiprocessing mode? for example, the following code only run the task in 1 process: from jug import TaskGenerator evaluate = TaskGenerator(evaluate) for p0 in [1,2,3]: for p1 in xrange(10): for p2 in xrange(10,20): for p3 in [True, False]: for p4 in...
With Jug, how to run nested loops in multiprocessing mode?
for example, the following code only run the task in 1 process: from jug import TaskGenerator evaluate = TaskGenerator(evaluate) for p0 in [1,2,3]: for p1 in xrange(10): for p2 in xrange(10,20): for p3 in [True, False]: for p4 in xrange(100): results.append(evaluate(p0,p1,p2,p...
[ "Author of jug here.\nTo run this script, assuming it is a file called script.py, you will run the jug execute script.py command (and not python script.py).\nYou can simply run multiple of these in parallel. If you are using a Unix-like shell, the following should work just fine in order to use two processors:\nju...
[ 4 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0006589030_multiprocessing_python.txt
Q: Regular expression matches more than expected Given is the following python script: text = '<?xml version="1.24" encoding="utf-8">' mu = (".??[?]?[?]", "....") for item in mu: print item,":",re.search(item, text).group() Can someone please explain why the first hit with the regex .??[?]?[?] returns <? instead...
Regular expression matches more than expected
Given is the following python script: text = '<?xml version="1.24" encoding="utf-8">' mu = (".??[?]?[?]", "....") for item in mu: print item,":",re.search(item, text).group() Can someone please explain why the first hit with the regex .??[?]?[?] returns <? instead of just ?. My explaination: .?? should match noth...
[ "For the same reason o*?bar matches oobar in foobar. Even if the quantifier is non-greedy the regex will try to match from the first char in all possible ways, before moving on to the next.\nFirst the .?? matches an empty string, but when the regex engine backtracks to it, it matches <, thus making the rest of the ...
[ 3, 2 ]
[]
[]
[ "pattern_matching", "python", "regex" ]
stackoverflow_0006589226_pattern_matching_python_regex.txt
Q: Setting the 'reply to' address using python and google app engine I have an email web service based on GAE mail API . How can I set a "reply to" address ? from future import with_statement # read data from request mail_to = str(self.request.POST.get('to')) mail_from = str(self.request.POST...
Setting the 'reply to' address using python and google app engine
I have an email web service based on GAE mail API . How can I set a "reply to" address ? from future import with_statement # read data from request mail_to = str(self.request.POST.get('to')) mail_from = str(self.request.POST.get('from')) mail_subject = str(self.request.POST.get('subject...
[ "message.reply_to ='example@googlemail.com' \n", "Here is an example:\n mail.send_mail(sender = email0,\n reply_to = email1,\n to = email2,\n subject = subject,\n body = body)\n\n" ]
[ 4, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006587886_google_app_engine_python.txt
Q: How can I append additional dictionary to my model_list? I get 'Pixel' object does not support item assignment How can I append additional dictionary to my pixel_list objects? def pixel_main(request, page): y = int(page) * 10 x = y - 10 pixel_list = Pixel.objects.all()[x:y] for i in pixel_list: ...
How can I append additional dictionary to my model_list?
I get 'Pixel' object does not support item assignment How can I append additional dictionary to my pixel_list objects? def pixel_main(request, page): y = int(page) * 10 x = y - 10 pixel_list = Pixel.objects.all()[x:y] for i in pixel_list: if Handler.objects.filter(pixel=i.id).filter(user=request...
[ "Python lets you add attributes to object instances using dot notation:\nfor i in pixel_list:\n if Handler.objects.filter(pixel=i.id).filter(user=request.user):\n i.vote = True\n else:\n i.vote = False\n\n", "You could add a BooleanField to the pixel class in your models.py, if the vote should...
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006588353_django_python.txt
Q: Properly encoding text in the bulk uploader What is the proper way to encode strings for the bulk uploader. It is currently bailing out when it runs into an apostrophe inside my text fields. Here's a sample CSV file: demo,name,message FALSE,one,"Welcome message" FALSE,two,"If you’re having a medical emergency" H...
Properly encoding text in the bulk uploader
What is the proper way to encode strings for the bulk uploader. It is currently bailing out when it runs into an apostrophe inside my text fields. Here's a sample CSV file: demo,name,message FALSE,one,"Welcome message" FALSE,two,"If you’re having a medical emergency" Here's my bulkloader.yaml: transformers: - kind: M...
[ "’ isn't an ASCII character. You should try changing the property transform to be import_transform: unicode\n" ]
[ 2 ]
[]
[]
[ "bulkloader", "character_encoding", "google_app_engine", "python" ]
stackoverflow_0006589285_bulkloader_character_encoding_google_app_engine_python.txt
Q: How do twisted and multiprocessing.Process create zombies? In python, using twisted loopingcall, multiprocessing.Process, and multiprocessing.Queue; is it possible to create a zombie process. And, if so, then how? A: A zombie is a process which has completed but whose completion has not yet been noticed by the ...
How do twisted and multiprocessing.Process create zombies?
In python, using twisted loopingcall, multiprocessing.Process, and multiprocessing.Queue; is it possible to create a zombie process. And, if so, then how?
[ "A zombie is a process which has completed but whose completion has not yet been noticed by the process which started it. It's the Twisted process's responsibility to reap its children.\nIf you start the process with spawnProcess, everything should always work as expected. However, as described in bug #733 in Twi...
[ 6 ]
[]
[]
[ "multiprocessing", "process", "python", "twisted", "zombie_process" ]
stackoverflow_0006589225_multiprocessing_process_python_twisted_zombie_process.txt
Q: In Python, removing thousands comma from numbers in a list where the numbers are separated by commas I have a list of data similar to that below: a = ['"105', '424"', '"102', '629"', '"104', '307"'] I want this data to be in a form similar to that of below: a = ['105424', '102629', '104307'] I am unsure of how t...
In Python, removing thousands comma from numbers in a list where the numbers are separated by commas
I have a list of data similar to that below: a = ['"105', '424"', '"102', '629"', '"104', '307"'] I want this data to be in a form similar to that of below: a = ['105424', '102629', '104307'] I am unsure of how to proceed. I thought perhaps removing all the commas then inserting commas only where they should be and ...
[ "I'm assuming this data was originally in a csv file where data that contains commas is quoted (\"105,424\",\"102,629\",\"104,307\") and then you are splitting on comma:\n>>> '\"105,424\",\"102,629\",\"104,307\"'.split(',')\n['\"105', '424\"', '\"102', '629\"', '\"104', '307\"']\n\nRather you should let the csv mod...
[ 4, 1, 1, 0, 0 ]
[]
[]
[ "python", "quotes" ]
stackoverflow_0006589260_python_quotes.txt
Q: How does Worldviz Vizard compares to Panda3D and Pygame? Is anybody familiar with Worldviz-Vizard's 3D engine for python? How does it compare to Panda3D? I have a feeling that it might be easier to learn but far more limited. They only support python 2.4 which also makes me not want to try it. A: Been using Viza...
How does Worldviz Vizard compares to Panda3D and Pygame?
Is anybody familiar with Worldviz-Vizard's 3D engine for python? How does it compare to Panda3D? I have a feeling that it might be easier to learn but far more limited. They only support python 2.4 which also makes me not want to try it.
[ "Been using Vizard for various VR and AR development for about 3 yrs now - it's NOT unity - i.e. a web enabled game engine (excellent though it is) - what Vizard provides is a highly optimized OpenGL engine, wrapped in user friendly python scripting environment BUT on top of this you get the ability to seamlessly d...
[ 2, 1, 0 ]
[]
[]
[ "3d_engine", "panda3d", "pygame", "python" ]
stackoverflow_0003877971_3d_engine_panda3d_pygame_python.txt
Q: Get the directory of a Shortcut calling a Python Script How does one acquire the directory of the Windows Shortcut calling a python script. I'd like to have multiple shortcuts in various places pointing to one script that I could edit if I wanted, but where the directory from which the script is called is accessib...
Get the directory of a Shortcut calling a Python Script
How does one acquire the directory of the Windows Shortcut calling a python script. I'd like to have multiple shortcuts in various places pointing to one script that I could edit if I wanted, but where the directory from which the script is called is accessible. Is this possible? This script would likely then be compi...
[ "The easiest solution is to just use a batch script instead of a shortcut.\nAll it needs is python C:\\path\\to\\script\\script.py, and the script will have the correct CWD.\nThe default when creating a shortcut on windows is for the Start in: property to be set to the folder the linked file resides in.\nThe script...
[ 5, 1 ]
[ "you can do so with\nimport os\nprint os.getcwd()\n\n\nos.getcwd()\nReturn a string representing the current working directory.\n Availability: Unix, Windows.\n\n" ]
[ -1 ]
[ "directory", "python" ]
stackoverflow_0006589499_directory_python.txt
Q: MySQL Dynamic Query Statement in Python I am trying to accomplish something like the following: cursor = db.cursor() cursor.execute('INSERT INTO media_files (%s, %s, %s, %s ... ) VALUES (%s, %s, %s, %s, ...)', (fieldlist, valuelist)) cursor.commit() I have 2 lists, fieldlist and valuelist which each contain th...
MySQL Dynamic Query Statement in Python
I am trying to accomplish something like the following: cursor = db.cursor() cursor.execute('INSERT INTO media_files (%s, %s, %s, %s ... ) VALUES (%s, %s, %s, %s, ...)', (fieldlist, valuelist)) cursor.commit() I have 2 lists, fieldlist and valuelist which each contain the same number of items. What is the best way ...
[ "cursor.execute('INSERT INTO media_files (%s) VALUES (%%s, %%s, %%s, %%s, ...)' % ','.join(fieldlist), valuelist)\n\nTo make it clearer:\nsql = 'INSERT INTO media_files (%s) VALUES (%%s, %%s, %%s, %%s, ...)' % ','.join(fieldlist)\ncursor.execute(sql, valuelist)\n\n", "The cursor expects parameters to be passe...
[ 3, 2 ]
[]
[]
[ "mysql", "python", "sql" ]
stackoverflow_0006589414_mysql_python_sql.txt
Q: appengine channel no messages arrive I am trying to get the channel api working. This is what I have so far: in the view: def channel_test(channel_token): tries = 1 logging.info('starting channel_test') for attempt in range(tries): message = 'this is message number: ' + str(attempt) cha...
appengine channel no messages arrive
I am trying to get the channel api working. This is what I have so far: in the view: def channel_test(channel_token): tries = 1 logging.info('starting channel_test') for attempt in range(tries): message = 'this is message number: ' + str(attempt) channel.send_message(channel_token, message) ...
[ "You pass the client_id to send_message not the channel_token. So your code should be:\nchannel.send_message('aosasdf123', message)\n\nYou place the channel_token client-side for opening the channel, and keep the client_id secret on the server-side for transmitting messages to that client via the channel.\n" ]
[ 4 ]
[]
[]
[ "channel", "flask", "google_app_engine", "javascript", "python" ]
stackoverflow_0006589559_channel_flask_google_app_engine_javascript_python.txt
Q: Where do I store data which is loaded on each request, in a Bottle-powered app? I have a simple Bottle app which stores its configuration in a text file. Naturally, I need the config to be available in almost every handler of the app, and I want it to be reloaded on every request. In Flask I could load the config ...
Where do I store data which is loaded on each request, in a Bottle-powered app?
I have a simple Bottle app which stores its configuration in a text file. Naturally, I need the config to be available in almost every handler of the app, and I want it to be reloaded on every request. In Flask I could load the config file into a ConfigParser instance in before_request and put a reference to it into an...
[ "Since you want it reloaded every single request, why not just use a function?\ndef get_config():\n with open('config.json') as f:\n return json.load(f)\n\n@route('/')\ndef index():\n config = get_config()\n return 'Welcome to %s' % config['site_name']\n\nIf you wanted to wrap that into a plugin it'...
[ 1 ]
[]
[]
[ "bottle", "flask", "python" ]
stackoverflow_0006589493_bottle_flask_python.txt
Q: How to close urllib2 connection? I have made a program using urllib2 that makes a lot of connections across the web. I noticed that eventually that this can be DDoS worthy; I would like to know how to close down each connection after I have done my business to prevent such an attack. The code I am using to open a ...
How to close urllib2 connection?
I have made a program using urllib2 that makes a lot of connections across the web. I noticed that eventually that this can be DDoS worthy; I would like to know how to close down each connection after I have done my business to prevent such an attack. The code I am using to open a connection is: cj = cookielib.CookieJa...
[ "I assume you are opening them with the urlopen() function. Its documentation states:\n\nThis function returns a file-like object with two additional methods:\n\nAs a file-like object, it will have a close method which you can call:\nconnection = urllib2.urlopen(url)\n# Do cool stuff in here.\nconnection.close()\n\...
[ 8, 2, 0 ]
[]
[]
[ "connection", "ddos", "python", "urllib" ]
stackoverflow_0006589960_connection_ddos_python_urllib.txt
Q: python multiline group regex I'm trying to extract the mpath name "DS4800_VG_STAGE*" and the number of online paths from the output of multipath -ll. DS4800_VG_STAGE_2 (3600a0b80004710ce00001ce24e08ce1c) dm-6 IBM,1815 FAStT [size=241G][features=1 queue_if_no_path][hwhandler=1 rdac][rw] \_ round-robin 0 ...
python multiline group regex
I'm trying to extract the mpath name "DS4800_VG_STAGE*" and the number of online paths from the output of multipath -ll. DS4800_VG_STAGE_2 (3600a0b80004710ce00001ce24e08ce1c) dm-6 IBM,1815 FAStT [size=241G][features=1 queue_if_no_path][hwhandler=1 rdac][rw] \_ round-robin 0 [prio=100][active] \_ 1:0:1:5 s...
[ "Try using this instead:\n^(\\w+\\s+).+?$$\\n((?:.+?\\n+)+)\n\nI think in your expression you are using [^\\\\] which is preventing any line with backslash from being caught in the expression. But every line (following the first two \"header lines\") starts with a backslash.\n" ]
[ 0 ]
[]
[]
[ "multiline", "python", "regex" ]
stackoverflow_0006589761_multiline_python_regex.txt
Q: Python's fromtimestamp returns inconsistent results on different machines I have two computers, for the first one: >>> datetime.datetime.fromtimestamp(0) datetime.datetime(1970, 1, 1, 7, 30) >>> datetime.datetime.fromtimestamp(1309846824) datetime.datetime(2011, 7, 5, 14, 20, 24) for the second one: >>> datetime....
Python's fromtimestamp returns inconsistent results on different machines
I have two computers, for the first one: >>> datetime.datetime.fromtimestamp(0) datetime.datetime(1970, 1, 1, 7, 30) >>> datetime.datetime.fromtimestamp(1309846824) datetime.datetime(2011, 7, 5, 14, 20, 24) for the second one: >>> datetime.datetime.fromtimestamp(0) datetime.datetime(1970, 1, 1, 8, 0) >>> datetime.date...
[ "Here is an excerpt from the \"asia\" file that tzdata uses. On debian/ubuntu you can get this file by running the command apt-get source tzdata\n\n...\n# Zone NAME GMTOFF RULES FORMAT [UNTIL]\nZone Asia/Kuala_Lumpur 6:46:46 - LMT 1901 Jan 1\n 6:55:25 - SMT ...
[ 2 ]
[]
[]
[ "datetime", "python", "timestamp" ]
stackoverflow_0006578701_datetime_python_timestamp.txt
Q: Closing a file in python opened with a shortcut I am just beginning with python with lpthw and had a specific question for closing a file. I can open a file with: input = open(from_file) indata = input.read() #Do something indata.close() However, if I try to simplify the code into a single line: indata = open(f...
Closing a file in python opened with a shortcut
I am just beginning with python with lpthw and had a specific question for closing a file. I can open a file with: input = open(from_file) indata = input.read() #Do something indata.close() However, if I try to simplify the code into a single line: indata = open(from_file).read() How do I close the file I opened, o...
[ "You simply have to use more than one line; however, a more pythonic way to do it would be:\nwith open(path_to_file, 'r') as f:\n contents = f.read()\n\nNote that with what you are doing before, you could miss closing the file if an exception was thrown. The 'with' statement here will cause it be closed even if ...
[ 6, 1 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0006590225_file_io_python.txt
Q: Problem Using Variable in Sqlite3 Statement I have a problem with a Python 2.7 project. I'm trying to set a variable to a value retrieved from an sqlite3 database, but I'm having trouble. Here is my code thus far, and the error I'm receiving. Yes, the connection opens just fine, and the table, columns, and indicat...
Problem Using Variable in Sqlite3 Statement
I have a problem with a Python 2.7 project. I'm trying to set a variable to a value retrieved from an sqlite3 database, but I'm having trouble. Here is my code thus far, and the error I'm receiving. Yes, the connection opens just fine, and the table, columns, and indicated row are there as they should be. import sqlite...
[ "As Thomas K mentions in a comment, index is a SQL keyword.\nYou can either rename that column, or enclose in backticks:\nTrailcrest.FireAutoHelp = c.execute(\"\"\"select fireautohelp \n from roster \n where `index` = ?;\"\"\", (AI,) ).f...
[ 6 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0006590146_python_sqlite.txt
Q: Why is this code giving me an "IndentationError: unexpected unindent" The code below is really annoying me I have looked on stackoverflow and google yet have not found anything and I am a pretty good pyton programmer and have not as of yet, well untill now, found an error that I could not deal with. I have tried e...
Why is this code giving me an "IndentationError: unexpected unindent"
The code below is really annoying me I have looked on stackoverflow and google yet have not found anything and I am a pretty good pyton programmer and have not as of yet, well untill now, found an error that I could not deal with. I have tried everything but this peace of code is giving me the IndentationError: unexpec...
[ "I think your idea is to have a different decorator apply to a function depending on whether the module is being run directly, or imported. Unfortunately this won't work the way you have it, because the decorator call needs the function to follow immediately after it. However, you could do it like this:\nif __name_...
[ 9, 3, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006590285_python.txt
Q: PYTHON programming: Search and Replace text in a file I am new to PYTHON and trying to write script which replaces text in a text file. This is what I have come up with using Python 3.1. But I am having some errors. Would somebody help me, please? #**************************************************************** #...
PYTHON programming: Search and Replace text in a file
I am new to PYTHON and trying to write script which replaces text in a text file. This is what I have come up with using Python 3.1. But I am having some errors. Would somebody help me, please? #**************************************************************** # a Python code to find and replace text in a file. # search...
[ "First off, I am not sure if this is an error in your putting your code online, but the body of your for loop is not indented.\nfor line in fileinput.input( fileToSearch ):\ntempFile.write( line.replace( textToSearch, textToReplace ) )\ntempFile.close()\n\nShould be\nfor line in fileinput.input( fileToSearch ):\n ...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006590083_python.txt
Q: Is it possible to fetch a google profile nickname and use in app engine apps? Currently the method nickname() in the Users class seem to return either the initial way you entered your username when you signed up for gmail (IE. "UseRnAme" if thats how you chose to type it, rather then "username" as it would show up...
Is it possible to fetch a google profile nickname and use in app engine apps?
Currently the method nickname() in the Users class seem to return either the initial way you entered your username when you signed up for gmail (IE. "UseRnAme" if thats how you chose to type it, rather then "username" as it would show up when you log in on a google service) or the entire email if you signed up for a go...
[ "From the javadocs for User and UserService, it doesn't appear that there is a way to get anything but the nickname.\nSpecifically, the only methods defined by User are:\nint compareTo(User user);\nboolean equals(java.lang.Object object);\njava.lang.String getAuthDomain();\njava.lang.String ge...
[ 0, 0 ]
[]
[]
[ "authentication", "google_app_engine", "python" ]
stackoverflow_0006586106_authentication_google_app_engine_python.txt
Q: Avoid related processes in process listing How can I generate a process listing, that does not include the current process, its shell and any related processes in the process group, and the SSHD process generated to handle the session? Does ps(1) actually have an option that does this? Is there some predicate I ca...
Avoid related processes in process listing
How can I generate a process listing, that does not include the current process, its shell and any related processes in the process group, and the SSHD process generated to handle the session? Does ps(1) actually have an option that does this? Is there some predicate I can apply to each process to filter it out of any ...
[ "Combining the answer referenced below with the -N (--deselect) option for ps might get you there:\n\nHow do I find the top-level parent PID of a given process using bash?\n\n" ]
[ 1 ]
[]
[]
[ "linux", "procfs", "ps", "python", "ssh" ]
stackoverflow_0006590320_linux_procfs_ps_python_ssh.txt
Q: Why won't you switch to Python 3.x? I ask this for deployable reasons. As in, if I write a solution in python, I feel bound to write to 2.x due to the lack of adoption of python 3. This is a major daily concern of mine, and I want to figure out what's going on. For many of the python-based questions here, people a...
Why won't you switch to Python 3.x?
I ask this for deployable reasons. As in, if I write a solution in python, I feel bound to write to 2.x due to the lack of adoption of python 3. This is a major daily concern of mine, and I want to figure out what's going on. For many of the python-based questions here, people are giving solutions that simply do not wo...
[ "[Edit 03/10/2014: This answer is now out-of-date. Django has supported Python 3 for some time.]\n[However, it must also be noted that the django third-party packages and extensions used in many Django projects are in various stages of Python 3 compatibility implementation. More details can be found in Django packa...
[ 33, 18, 4, 4, 3, 1, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "deployment", "python", "python_3.x" ]
stackoverflow_0000766636_deployment_python_python_3.x.txt
Q: Command-line interface design with base options and subcommands I'm trying to develop a command line interface for a tool I'm writing. I'm tossing up between an interface similar to Fabric's fab tool and one like svn's command line tool. fab's usage message: Usage: fab [options] <command>[:arg1,arg2=val2,host=foo,...
Command-line interface design with base options and subcommands
I'm trying to develop a command line interface for a tool I'm writing. I'm tossing up between an interface similar to Fabric's fab tool and one like svn's command line tool. fab's usage message: Usage: fab [options] <command>[:arg1,arg2=val2,host=foo,hosts='h1;h2',...] ... svn's usage message: usage: svn <subcommand> ...
[ "\nsubversion's way is more standard.\nProbably not.\nYou can cut butter with a hand axe.\n\nIf you want to simplify documentation and usage, go with SVN's way. I can see why fab's way seems appealing, it's logical for a programmer. But it's actually complicated and messed up for users.\nPlac looks cool, but you ne...
[ 4 ]
[]
[]
[ "argparse", "command_line", "python" ]
stackoverflow_0006590757_argparse_command_line_python.txt
Q: allocating more size in sizer to wx.CollapsiblePane when expanded I have several CollapsiblePanes in a vertical BoxSizer. I would like to be able to expand and collapse them without having them run into each other. I am running wxPython 2.8.10.1 on Windows 7. Runnable sample application demonstrating the problem i...
allocating more size in sizer to wx.CollapsiblePane when expanded
I have several CollapsiblePanes in a vertical BoxSizer. I would like to be able to expand and collapse them without having them run into each other. I am running wxPython 2.8.10.1 on Windows 7. Runnable sample application demonstrating the problem is below. import wx class SampleCollapsiblePane(wx.CollapsiblePane): ...
[ "The documentation explicitly states that you should use proportion=0 when adding collapsible panes to a sizer.\nhttp://docs.wxwidgets.org/stable/wx_wxcollapsiblepane.html\nSo, first, change the 1 at the end of this line to a 0:\nsizer.Add(SampleCollapsiblePane(self.main_panel, label = str(x)), 1)\n\nNext, add this...
[ 4 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0006589509_python_wxpython.txt
Q: Pygame; making C extensions I'm relatively new to python and have made some useful tools and some small games w/ 10 sprites in python; based on performance I think my next logical step is making C extensions to improve performance in pygame. My first initial question is in pygame, can I make a main loop in C (or w...
Pygame; making C extensions
I'm relatively new to python and have made some useful tools and some small games w/ 10 sprites in python; based on performance I think my next logical step is making C extensions to improve performance in pygame. My first initial question is in pygame, can I make a main loop in C (or would I have to interface with SDL...
[ "Without any insight to your code, I can make these suggestions. Since you are rightly concerned about performance, instead of trying to improve performance by writing C modules, try optimising the python code you have written. A good article on how to do this can be found in this article about patterns at Python...
[ 3 ]
[]
[]
[ "c", "optimization", "pygame", "python" ]
stackoverflow_0006586335_c_optimization_pygame_python.txt
Q: Where is the NumPy version string documented? What are the possible NumPy version strings? What is the standard? Where is this documented? 1.4.0dev7059 1.4.0b1 1.4.0rc2 I've seen dev, b, rc. A: b, dev, rc signify beta, development release and release candidate, respectively. Some of this is documented in the R...
Where is the NumPy version string documented?
What are the possible NumPy version strings? What is the standard? Where is this documented? 1.4.0dev7059 1.4.0b1 1.4.0rc2 I've seen dev, b, rc.
[ "b, dev, rc signify beta, development release and release candidate, respectively. Some of this is documented in the Release Notes:\n\nVersion Number explanation: \n1.0.X will be maintainence releases (modules will not need recompilation)\n1.X will be major stable releases which might contain changes to the\n C-...
[ 2 ]
[]
[]
[ "numpy", "python", "version" ]
stackoverflow_0006589985_numpy_python_version.txt
Q: Is there a python module, which can turn geocoordinates into the name of the corresponding city? I have a bunch of coordinates and I want to transform them to human readable addresses. Is there a way to achieve this? It would be great if i can get the name of the city where the coordinates are located in. A: Use...
Is there a python module, which can turn geocoordinates into the name of the corresponding city?
I have a bunch of coordinates and I want to transform them to human readable addresses. Is there a way to achieve this? It would be great if i can get the name of the city where the coordinates are located in.
[ "Use the Google Maps Reverse Geocoding API. \n", "If you can do with political units instead of street addresses I would suggest Pete Warden's Data Science Toolkit: http://www.datasciencetoolkit.org/developerdocs#coordinates2politics\nWith Google Maps API, you are limited to 2500 requests per day. Warden's toolki...
[ 5, 1 ]
[]
[]
[ "city", "geolocation", "python", "reverse_geocoding", "street_address" ]
stackoverflow_0006590689_city_geolocation_python_reverse_geocoding_street_address.txt
Q: Cython: Dynamically linking with a dll/so I'm working with an API which is distributed as a dll/so file that I need to dynamically link with my python program. To accomplish this, I want to use Cython. I have been able to, in the past, link with the dll statically. This works well, except that the API comes in fo...
Cython: Dynamically linking with a dll/so
I'm working with an API which is distributed as a dll/so file that I need to dynamically link with my python program. To accomplish this, I want to use Cython. I have been able to, in the past, link with the dll statically. This works well, except that the API comes in four different flavors, with theoretically infini...
[ "I assume you are talking about writing C modules here. If so yes you can. I don't know what the equivalent on Windows is, but in Linux you can use dlopen and friends. There is a man page for it, and several web sites documenting it. Try this link \"http://linux.die.net/man/3/dlopen\" it provides you with a nic...
[ 2 ]
[]
[]
[ "cython", "python" ]
stackoverflow_0006546310_cython_python.txt
Q: How to average column data for multiple columns in text files? I have a tab delimited data text file in the following format: Depth Temp Salinity 0.30 28.30 31.90 0.30 28.30 31.90 0.30 28.20 31.90 0.30 28.20 31.90 0.40 28.20 32.00 0.40 28.00 32.00 0.50 28.00 31.90 0....
How to average column data for multiple columns in text files?
I have a tab delimited data text file in the following format: Depth Temp Salinity 0.30 28.30 31.90 0.30 28.30 31.90 0.30 28.20 31.90 0.30 28.20 31.90 0.40 28.20 32.00 0.40 28.00 32.00 0.50 28.00 31.90 0.60 28.00 32.00 0.70 27.90 32.00 0.60 27.90 32.10 ...
[ "You should use a dictionary where the key is the depth.\nlines = [\n\"0.30 28.30 31.90\",\n\"0.30 28.30 31.90\",\n\"0.30 28.20 31.90\",\n\"0.30 28.20 31.90\",\n\"0.40 28.20 32.00\",\n\"0.40 28.00 32.00\",\n\"0.50 28.00 31.90\",\n\"0.60 28.00 32.00\",\n\"0.70 27.90...
[ 1, 1, 0 ]
[]
[]
[ "duplicates", "list", "python" ]
stackoverflow_0006591166_duplicates_list_python.txt
Q: Python: Unbound method When I try to bind a method, I get an error: Traceback (most recent call last): File "pygametest3.py", line 12, in <module> render = winback.rend() TypeError: unbound method rend() must be called with winback instance as first argument (got nothing instead) This is the code, up to the...
Python: Unbound method
When I try to bind a method, I get an error: Traceback (most recent call last): File "pygametest3.py", line 12, in <module> render = winback.rend() TypeError: unbound method rend() must be called with winback instance as first argument (got nothing instead) This is the code, up to the offending point: import sys...
[ "Classes must be instantiated before a normal method on them can be called.\nclass Winback(object):\n def rend(self):\n ...\n\nwinback = Winback()\nrender = winback.rend()\n\nOr you could use @staticmethod. But make it a module-level function instead.\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0006591610_python.txt
Q: optimize this query that selects rows before and after a pk I'm trying to select 2 rows before and after a given primary key. This is my solution so far, but seems inefficient. Is there a way to optimize this? images = Media.objects.filter(owner=user_object) #select objects by a user id_list = list(images.values_l...
optimize this query that selects rows before and after a pk
I'm trying to select 2 rows before and after a given primary key. This is my solution so far, but seems inefficient. Is there a way to optimize this? images = Media.objects.filter(owner=user_object) #select objects by a user id_list = list(images.values_list('id', flat=True)) #get the primary keys for the objects idx =...
[ "Get the rows with an ID less/greater than yours, and limit it to 2 rows.\nnext_objs = Media.objects.filter(id__gt=image.id).order_by('id')[:2]\nprev_objs = Media.objects.filter(id__lt=image.id).order_by('-id')[:2]\n\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006591599_django_python.txt
Q: Python exec command with pipe control I have a python script which is called by network. This script gets some data as input stream and sends some data as output one - stdin and stdout. Now I want this script to call other one. And redirects his stdin to child process and child's stdout back. Basically this will b...
Python exec command with pipe control
I have a python script which is called by network. This script gets some data as input stream and sends some data as output one - stdin and stdout. Now I want this script to call other one. And redirects his stdin to child process and child's stdout back. Basically this will be proxy like script. The most important mom...
[ "If data needs to be fully read before sending it back then you could implement a proxy using :\nimport sys\nfrom subprocess import *\nif __name__ == \"__main__\":\n\n network_content = sys.stdin.read()\n p = Popen(\"python other_script.py\",stdin=PIPE, stdout=PIPE, stderr=PIPE, \n close_fds=True)\n ...
[ 0 ]
[]
[]
[ "exec", "python" ]
stackoverflow_0006591401_exec_python.txt
Q: how to get the dictionary with a given value in a list of dictionary in python? I have a list of dictionary, for example my given key value is 'jerry'. Is there a way to loop to the list and return only dictionary with the key value name of 'jerry'? lst= [{'name':'tom','score':5},{'name':'jerry','score':10},{'nam...
how to get the dictionary with a given value in a list of dictionary in python?
I have a list of dictionary, for example my given key value is 'jerry'. Is there a way to loop to the list and return only dictionary with the key value name of 'jerry'? lst= [{'name':'tom','score':5},{'name':'jerry','score':10},{'name':'jason','score':8}] It should return {'name':'jerry','score':10}
[ "You can get all suitable elements with a generator expression and pick the first with next:\nnext(d for d in lst if d['name'] == 'jerry')\n\n", "Use a list comprehension:\nresult = [x for x in lst if x['name'] == 'jerry'][0]\n\nAs a side note, you may want to use a namedtuple for your data if you're going to hav...
[ 5, 3, 1, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0006590834_dictionary_list_python.txt
Q: locked SQLite database errors with WSGI python app I'm having issues making multiple ajax POST calls to functions that access a database in my web app using sqlite and mod-wsgi. I have no issues making requests to one function, but as soon as I call a different function, I started getting "database is locked" err...
locked SQLite database errors with WSGI python app
I'm having issues making multiple ajax POST calls to functions that access a database in my web app using sqlite and mod-wsgi. I have no issues making requests to one function, but as soon as I call a different function, I started getting "database is locked" errors. I've tried setting the variables as global and jus...
[ "See warnings about concurrent access from multiple processes in SQLite documentation.\nhttp://www.sqlite.org/faq.html#q5\nThis information was provided on mod_wsgi list where question was also asked, but following up here.\nThis can be an issue because Apache/mod_wsgi supports both single and multi process configu...
[ 0 ]
[]
[]
[ "python", "wsgi" ]
stackoverflow_0006567299_python_wsgi.txt
Q: Python what is the pythonic way of comparing 2 increasing in size lists? I have one list (list a) that increases based on size and has items removed from this list and put into another list (list b) that maintains what has already been checked. The list that is maintaining (list b) what has been done needs to be c...
Python what is the pythonic way of comparing 2 increasing in size lists?
I have one list (list a) that increases based on size and has items removed from this list and put into another list (list b) that maintains what has already been checked. The list that is maintaining (list b) what has been done needs to be compared with the list that has content (list a) that hasn't been checked alrea...
[ "Your code will produce inconsistent output. You shouldn't iterate and modify a list in the same loop context.\nYou could use listA as a Queue:\n while len(listA):\n element = listA.pop()\n #do something with element\n listB.add(element)\n\nthis code is consistent because even tough the list is being mo...
[ 5, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0006591792_list_python.txt
Q: Issue with python httplib2 on linux I'm using the following snippet of code to call a web service, that requires basic auth: import urllib import httplib2 url='http://heywatch.com/download.json' body={'username':'my_username','password':'my_password'} header_data={'Accept': 'application/json'} http=httplib2.Http(...
Issue with python httplib2 on linux
I'm using the following snippet of code to call a web service, that requires basic auth: import urllib import httplib2 url='http://heywatch.com/download.json' body={'username':'my_username','password':'my_password'} header_data={'Accept': 'application/json'} http=httplib2.Http() response, content = http.request(url, '...
[ "This has to do with how the linux box is resolving heywatch.com. CAn you do a ping to see if heywatch.com is reachable (probably not). You might want to look at /etc/resolv.conf on your linux box to see what nameservers are configured and ask amazon if you are using any of theirs.\nFWIW, I just tried to resolve he...
[ 0 ]
[]
[]
[ "httplib2", "linux", "python" ]
stackoverflow_0006591892_httplib2_linux_python.txt
Q: python: APNs SSLError I am trying to send push notifications to iPhone via python as described here but I am getting the following error: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/omat/CA/server/ca/models.py", line 193, in push c.connect((host_name, 2195)) File ...
python: APNs SSLError
I am trying to send push notifications to iPhone via python as described here but I am getting the following error: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/omat/CA/server/ca/models.py", line 193, in push c.connect((host_name, 2195)) File "/usr/lib/python2.6/ssl.py"...
[ "Here is how I get it working:\nFrom within KeyChain export the following both in p12 format, without giving password:\n\nApple Development Push Services certificate as cert.p12\nprimary key under Apple Development Push Services as pkey.p12\n\nIn terminal go to the directory where you have exported the certificates...
[ 39, 13 ]
[]
[]
[ "apple_push_notifications", "python", "ssl" ]
stackoverflow_0005833642_apple_push_notifications_python_ssl.txt
Q: Getting file size in Python? Is there a built-in function for getting the size of a file object in bytes? I see some people do something like this: def getSize(fileobject): fileobject.seek(0,2) # move the cursor to the end of the file size = fileobject.tell() return size file = open('myfile.bin', 'rb'...
Getting file size in Python?
Is there a built-in function for getting the size of a file object in bytes? I see some people do something like this: def getSize(fileobject): fileobject.seek(0,2) # move the cursor to the end of the file size = fileobject.tell() return size file = open('myfile.bin', 'rb') print getSize(file) But from my...
[ "Use os.path.getsize(path) which will\n\nReturn the size, in bytes, of path. Raise OSError if the file does not exist or is inaccessible.\n\nimport os\nos.path.getsize('C:\\\\Python27\\\\Lib\\\\genericpath.py')\n\nOr use os.stat(path).st_size\nimport os\nos.stat('C:\\\\Python27\\\\Lib\\\\genericpath.py').st_size \n...
[ 948, 251, 97, 28, 16 ]
[]
[]
[ "file", "python", "size" ]
stackoverflow_0006591931_file_python_size.txt
Q: If I use urlretrive and urlopen to access the same url, I end up with different files. Why? I'm fairly new to python, (and programming in general), and I've ran into some trouble while writing a program to fetch midi files from the internet. Below is some code that I expected to write two identical files: #method...
If I use urlretrive and urlopen to access the same url, I end up with different files. Why?
I'm fairly new to python, (and programming in general), and I've ran into some trouble while writing a program to fetch midi files from the internet. Below is some code that I expected to write two identical files: #method one url = "http://.../asfd.mid" urllib.urlretrieve(url, "C:\...\this_is_file_one.mid") #method ...
[ "urllib.urlretrieve() opens the file to save in binary mode.\nopen(\"this_is_file_two.mid\", \"wb\").write(g)\n\n" ]
[ 4 ]
[]
[]
[ "python", "urllib", "urlopen" ]
stackoverflow_0006592054_python_urllib_urlopen.txt