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: Inconsistent page has expired message in internet explorer I have an application developed in Python-Zope where only on some of the pages, I am getting "page has expired issue" and this does not come every time. This issue comes when I click on "Back" or "Cancel" buttons which use browser history to redirect to th...
Inconsistent page has expired message in internet explorer
I have an application developed in Python-Zope where only on some of the pages, I am getting "page has expired issue" and this does not come every time. This issue comes when I click on "Back" or "Cancel" buttons which use browser history to redirect to the earlier pages. I have reviewed my code and there is not code s...
[ "Is your page served on HTTPS?\nIf so this is the expected behavior. By default IE will not cache a secured page on disk, nor will it automatically resubmit pages with POST data.\nThis is security feature (prevent cache sniffing, etc) and is about the only thing IE does correctly.\n" ]
[ 1 ]
[]
[]
[ "internet_explorer", "python", "zope" ]
stackoverflow_0005653478_internet_explorer_python_zope.txt
Q: Reading binary data with PySerial from serial port PyQT 4.7 does not have inherited class from QIODevice that allows to talk with serial port directly (e.g. QSerialDevice). So I thought that it would be easier for me to use QProcess class and implement the actual reading/writing to serial port from a different pro...
Reading binary data with PySerial from serial port
PyQT 4.7 does not have inherited class from QIODevice that allows to talk with serial port directly (e.g. QSerialDevice). So I thought that it would be easier for me to use QProcess class and implement the actual reading/writing to serial port from a different process that will interface with my main QT application usi...
[ "It seems that PySerial (or a library that Pyserial depends on) is translating a single \"0x0a\" (\\n) character into two characters \"0x0d 0x0a\"(\\r\\n). Both communication end-points are running on Linux, so I am not sure why someone would like to even translate those line endings at all...\nHere strace indicate...
[ 2, 1 ]
[]
[]
[ "pyqt", "python", "qprocess", "qt", "serial_port" ]
stackoverflow_0005643925_pyqt_python_qprocess_qt_serial_port.txt
Q: django reverse query Am trying to query from parent to child and with a single query being able to have the child results in parent. In my example, am trying to do a relation between i18n tables in which I want to include the row from the child table in a single hit. models.py class main(models.Model): slug ...
django reverse query
Am trying to query from parent to child and with a single query being able to have the child results in parent. In my example, am trying to do a relation between i18n tables in which I want to include the row from the child table in a single hit. models.py class main(models.Model): slug = models.SlugField() ...
[ "When you use a foreign key you need to access that data through the RelatedManager. In your case you would access data in the main_i18n from the main like:\n>>> a=main.objects.get(id=1)\n>>> i18n = a.main_i18n_set.get()\n>>> i18n.language\nu'en'\n\nor if you need to operate on multiple objects:\na = main.objects.f...
[ 2, 1 ]
[]
[]
[ "django", "orm", "python" ]
stackoverflow_0005653172_django_orm_python.txt
Q: How to accurately obtain page hits on a django page when using memcached I've developed a web application in django, and I'm interested in accurately knowing how many people visited certain pages and keeping that info in my database. As I was already running some code whenever a page was loaded, I had a small bit ...
How to accurately obtain page hits on a django page when using memcached
I've developed a web application in django, and I'm interested in accurately knowing how many people visited certain pages and keeping that info in my database. As I was already running some code whenever a page was loaded, I had a small bit of code that increased the counter in 1. However, when implementing memcached...
[ "A) Use Google Analytics to determine within 2% your page views\nB) Build an app to hold request data (time, browser, IP, etc) and create middleware that stores info about each request in that app. Place this middleware above your cache middleware.\n" ]
[ 3 ]
[]
[]
[ "django", "memcached", "python" ]
stackoverflow_0005654001_django_memcached_python.txt
Q: Using celery as a fault tolerant scheduler I would like to use celery w/ rabbitmq as a fault tolerant scheduler in a distributed environment. By fault tolerant, i mean that if a task is given to a worker and that worker goes down for whatever reason, celery should be able to reschedule it to another server. How is...
Using celery as a fault tolerant scheduler
I would like to use celery w/ rabbitmq as a fault tolerant scheduler in a distributed environment. By fault tolerant, i mean that if a task is given to a worker and that worker goes down for whatever reason, celery should be able to reschedule it to another server. How is it possible to achieve this in an environment w...
[ "Probably all you need is just to set CELERY_ACKS_LATE\nLate ack means the task messages will be acknowledged after the task has been executed, not just before, which is the default behaviour. In this way if the worker crash rabbit MQ still have the message.\nHere more info\nRetry Lost or Failed Tasks (Celery, Djan...
[ 5, 2 ]
[]
[]
[ "celery", "python", "rabbitmq" ]
stackoverflow_0005563827_celery_python_rabbitmq.txt
Q: Script downloading file from filesonic Could somebody please advise me on how I could write a Python script to do these things? Change my IP address to some random proxy address. Download and display the captcha image and show me the prompt where I can write captcha characters. Download the main file. The script...
Script downloading file from filesonic
Could somebody please advise me on how I could write a Python script to do these things? Change my IP address to some random proxy address. Download and display the captcha image and show me the prompt where I can write captcha characters. Download the main file. The script should have one input parameter (the addres...
[ "Here's some basic Python to get you started:\nimport urllib2\nresponse = urllib2.urlopen('http://www.example.com/')\nhtml = response.read() # This is what is read from the file. In your case,\n # it'll only read the contents of the webpage.\n\nTo change your IP address, you can use some Linux...
[ 2 ]
[]
[]
[ "python", "scripting" ]
stackoverflow_0005654367_python_scripting.txt
Q: Read in a file and skip the header portion of a text file in Python I've taken a book in text format from gutenberg.org and I'm trying to read in the text, but skip the beginning portion of the file, and then use a process function I've written to parse the rest. How can I do this? Here is the start of the text...
Read in a file and skip the header portion of a text file in Python
I've taken a book in text format from gutenberg.org and I'm trying to read in the text, but skip the beginning portion of the file, and then use a process function I've written to parse the rest. How can I do this? Here is the start of the text file. > The Project Gutenberg EBook of The Kama Sutra of Vatsyayana, by ...
[ "Add this:\nfor line in fin:\n if \"START OF THIS PROJECT GUTENBERG BOOK\" in line:\n break\n\njust before your own \"for line in fin:\" loop.\n", "Well, you can just read input until you match your criteria to skip the beginning:\ndef process_file(filename):\n \"\"\" opens a file and passes back a lis...
[ 3, 3 ]
[]
[]
[ "file", "python", "text", "text_files" ]
stackoverflow_0005654714_file_python_text_text_files.txt
Q: how can i send file data from android to python? I want to send file of data from my android In other word { i want to Enter some data like name gender location age ....etc and this in android then take this data and send it to python } can this be file sending ?? or it must be data ?!! A: Try Android Scriptin...
how can i send file data from android to python?
I want to send file of data from my android In other word { i want to Enter some data like name gender location age ....etc and this in android then take this data and send it to python } can this be file sending ?? or it must be data ?!!
[ "Try Android Scripting by using this you can create layer of scripting over Android.\n", "if it is an open sever socket then on the Android just use a client socket and send your data through. You'll have to decide what the format of the data is and how you will parse it but the commutation part is strait forward...
[ 0, 0 ]
[]
[]
[ "android", "python" ]
stackoverflow_0005652794_android_python.txt
Q: Python SSL with PKCS#12 certificates Is there some way to wrap a socket connection with SSL using python's ssl module in python 2.6 using a pkcs#12 file? The file contains a private key and certificate. I want to use them for the client side of the connection. This post seems to hint that it may be possible but ...
Python SSL with PKCS#12 certificates
Is there some way to wrap a socket connection with SSL using python's ssl module in python 2.6 using a pkcs#12 file? The file contains a private key and certificate. I want to use them for the client side of the connection. This post seems to hint that it may be possible but doesn't give a real definitive answer.
[ "Not with python's ssl module. M2Crypto can't do this also at the moment, nor does python-gnutls. If you've got openssl command available on your client machine, you can re-export that pkcs12 to pem format running the openssl command, and use the results, something like:\nopenssl pkcs12 -in your_pkcs.p12 -out clien...
[ 2 ]
[]
[]
[ "openssl", "pkcs#12", "python", "ssl" ]
stackoverflow_0004372291_openssl_pkcs#12_python_ssl.txt
Q: Django URL syntax error I am creating a wiki app. And when I create url for my app in urls.py I get syntax error message. I am not good at regular expressions. Here is my code, (r'wikicamp/(?<page_name>[^/]+)/edit/$', 'wikicamp.wiki.views.edit_page'), (r'wikicamp/(?<page_name>[^/]+)/save/$', 'wikicamp.wiki.views.s...
Django URL syntax error
I am creating a wiki app. And when I create url for my app in urls.py I get syntax error message. I am not good at regular expressions. Here is my code, (r'wikicamp/(?<page_name>[^/]+)/edit/$', 'wikicamp.wiki.views.edit_page'), (r'wikicamp/(?<page_name>[^/]+)/save/$', 'wikicamp.wiki.views.save_page'), (r'wikicamp/(?<pa...
[ "Your named capture groups are missing the 'P'. Do it like so:\n(r'wikicamp/(?P<page_name>[^/]+)/edit/$', 'wikicamp.wiki.views.edit_page'),\n(r'wikicamp/(?P<page_name>[^/]+)/save/$', 'wikicamp.wiki.views.save_page'),\n(r'wikicamp/(?P<page_name>[^/]+)/$', 'wikicamp.wiki.views.view_page'),\n\n", "According to http:...
[ 4, 0 ]
[]
[]
[ "django", "django_urls", "python", "regex" ]
stackoverflow_0005655152_django_django_urls_python_regex.txt
Q: Python get instance from list based on instance variable Given a list of instances, say clients I'm trying to pluck an item from the list based on the value of a single instance variable screenName. I know I can do this: for client in clients: if client.screenName = search: return client But is there a nice...
Python get instance from list based on instance variable
Given a list of instances, say clients I'm trying to pluck an item from the list based on the value of a single instance variable screenName. I know I can do this: for client in clients: if client.screenName = search: return client But is there a nicer way of doing this without the loop? Thanks for your help :)
[ "You can use filter \ntry:\n filter(lambda client: client.screenName == search, clients)[0]\nexcept IndexError:\n # handle error. May be use a default value\n\n", "I would use list comprehensions. Suppose this is your Client class:\n>>> class Client:\n... def __init__(self, screenName):\n... self....
[ 5, 1, 1, 0, 0, 0 ]
[]
[]
[ "instances", "list", "python" ]
stackoverflow_0005655198_instances_list_python.txt
Q: Free RDMBS With Python Client & Gui Tools For Ubuntu Can any of you recommend a free database engine with a Python client & gui tools (to run queries etc) that is working well with Ubuntu? I would simply go to MySQL, but from what I know, it's Python client is not being maintained (I am searching for a database en...
Free RDMBS With Python Client & Gui Tools For Ubuntu
Can any of you recommend a free database engine with a Python client & gui tools (to run queries etc) that is working well with Ubuntu? I would simply go to MySQL, but from what I know, it's Python client is not being maintained (I am searching for a database engine that has a good, working Python client)
[ "Personally I'd go with PostgreSQL, but oursql.\n" ]
[ 1 ]
[]
[]
[ "database", "linux", "python" ]
stackoverflow_0005655350_database_linux_python.txt
Q: Problem in insertion from python script in mysql database with innondb engine I am facing a problem where I am trying to add data from a python script to mysql database with InnonDB engine, it works fine with myisam engine of the mysql database. But the problem with the myisam engine is that it doesn't support for...
Problem in insertion from python script in mysql database with innondb engine
I am facing a problem where I am trying to add data from a python script to mysql database with InnonDB engine, it works fine with myisam engine of the mysql database. But the problem with the myisam engine is that it doesn't support foreign keys so I'll have to add extra code each place where I want to insert/delete r...
[ "InnoDB is transactional. You need to call connection.commit() after inserts/deletes/updates.\nEdit: you can call connection.autocommit(True) to turn on autocommit.\n", "Python DB API disables autocommit by default\nPasted from google (first page, 2nd result)\n\nMySQL :: MySQL 5.0 Reference Manual :: 13.2.8 The...
[ 6, 4 ]
[]
[]
[ "innodb", "myisam", "mysql", "python" ]
stackoverflow_0005654107_innodb_myisam_mysql_python.txt
Q: Django Boto S3 Access I can't figure this out. Here's what I want to happen ... I have an applications that users upload files to S3 using boto and django. I want those files to be private and only accessible through my app using my api credentials. So if a user uploads a photo via my app, the only way he or an...
Django Boto S3 Access
I can't figure this out. Here's what I want to happen ... I have an applications that users upload files to S3 using boto and django. I want those files to be private and only accessible through my app using my api credentials. So if a user uploads a photo via my app, the only way he or anyone else can download it i...
[ "The docs for boto's ACLs are here. I suggest just using the private \"canned policy\" -- since your users don't have S3 accounts anyway, it's by far the simplest idea. Your app will of course have to keep track of which user \"owns\" which files (which should be a very, very simple Django model!).\n", "I think...
[ 7, 5, 2 ]
[]
[]
[ "amazon_s3", "boto", "django", "python" ]
stackoverflow_0003498464_amazon_s3_boto_django_python.txt
Q: Converting string to ascii using ord() I must preface this by saying that I am a neophyte (learning), so please waive the omission of the obvious in deference to a man who has had limited exposure to your world (Python). My objective is to get string from a user and convert it to Hex and Ascii string. I was able t...
Converting string to ascii using ord()
I must preface this by saying that I am a neophyte (learning), so please waive the omission of the obvious in deference to a man who has had limited exposure to your world (Python). My objective is to get string from a user and convert it to Hex and Ascii string. I was able to accomplish this successfully with hex (enc...
[ "Is this what you're looking for?\nwhile True:\n stringName = raw_input(\"Convert string to hex & ascii(type stop to quit): \").strip()\n if stringName == 'stop':\n break\n\n print \"Hex value: \", stringName.encode('hex')\n print \"ASCII value: \", ', '.join(str(ord(c)) for c in stringName)\n\n", "S...
[ 7, 6, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005655574_python.txt
Q: reduce time for a long for-loop in python a other stupid question from my side ;) I have some issues with the following snippet with len(x)=len(y)=7'700'000: from numpy import * for k in range(len(x)): if x[k] == xmax: xind = -1 else: xind = int(floor((x[k]-xmin)/xdelta)) if y[k] == ym...
reduce time for a long for-loop in python
a other stupid question from my side ;) I have some issues with the following snippet with len(x)=len(y)=7'700'000: from numpy import * for k in range(len(x)): if x[k] == xmax: xind = -1 else: xind = int(floor((x[k]-xmin)/xdelta)) if y[k] == ymax: yind = -1 else: yind = ...
[ "How about something like:\nimport numpy as np\nxind = np.floor((x-xmin)/xdelta).astype(int)\nyind = np.floor((y-ymin)/ydelta).astype(int)\n\nxind[np.argmax(x)] = -1\nyind[np.argmax(y)] = -1\n\narr = grid[xind,yind]\n\nNote: if you're using numpy don't treat the arrays like python lists if you want to do things eff...
[ 4, 1, 0, 0 ]
[ "x's lenght is 7 millions? I think that's why!\nTHe iterations ocurrs 7 millions times, \nprobably you shoud make another kind of loop.\nIt's really necesary looping over 7 m times?\n" ]
[ -1 ]
[ "for_loop", "numpy", "python" ]
stackoverflow_0005655052_for_loop_numpy_python.txt
Q: Refer to same input multiple times in string replacement? I need to print something like this "a=name1,b=name2,c=name1,d=name2" While I have name1 and name2 in variable n1 n2 n1="name1" n2="name2" what I am trying to do "a=%s,b=%s,c=%s,d=%s" % (n1,n2,n1,n2) Is there a better way than this? way to avoid n1,n2,n...
Refer to same input multiple times in string replacement?
I need to print something like this "a=name1,b=name2,c=name1,d=name2" While I have name1 and name2 in variable n1 n2 n1="name1" n2="name2" what I am trying to do "a=%s,b=%s,c=%s,d=%s" % (n1,n2,n1,n2) Is there a better way than this? way to avoid n1,n2,n1,n2 ? with python 3 ? and what if print sys.version_info (2, 1...
[ "\"a=%(name1)s,b=%(name2)s,c=%(name1)s,d=%(name2)s\" % {'name1': n1, 'name2': n2}\n\n", "As long as the tuple is simply duplicated you can simplify by using tuple multiplication, otherwise use the dictionary interpolation shown in the other answer or use string.format.\n(n1, n2, n1, n2) == (n1, n2) * 2\n\nExample...
[ 7, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0005655805_python_string.txt
Q: How to gather data from multiple threads in python? I'm wanting to use multiple threads in Python to calculate pixel values for an image, to be constructed at the end, though I'm having trouble figuring out how to get the result of the thread back and collected. Here's the setup: A Queue.Queue() object is created,...
How to gather data from multiple threads in python?
I'm wanting to use multiple threads in Python to calculate pixel values for an image, to be constructed at the end, though I'm having trouble figuring out how to get the result of the thread back and collected. Here's the setup: A Queue.Queue() object is created, as well as a threading.Thread() class child: q = Queue.Q...
[ "Python has a global lock for modifying python-level datastructures, called the GIL. This makes it difficult to efficiently do the sort of things you want to do with threads.\nBut, despair not! The kind developers have given us the multiprocessing module. Replace threading with multiprocessing (to use multiprocessi...
[ 2, 1, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0005654541_multithreading_python.txt
Q: Practical Django Projects - Pages 71 and 80 I am reading the book "Practical Django Projects". It is a nice book. I have a few questions though : On page 71, there is the following code : from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() from coltrane.models import ...
Practical Django Projects - Pages 71 and 80
I am reading the book "Practical Django Projects". It is a nice book. I have a few questions though : On page 71, there is the following code : from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() from coltrane.models import Entry entry_info_dict = { 'queryset': Entry....
[ "\npub_date refers to coltrane.models.Entry attribute pub_date see the source\nfrom django.conf import settings imports your project settings.py so you have to define your settings inside your project/settings.py file. Here are some docs on the official docs about using settings in python code\n\n", "pub_date is ...
[ 2, 0 ]
[]
[]
[ "django", "project", "python", "python_2.7" ]
stackoverflow_0005655918_django_project_python_python_2.7.txt
Q: How do I make a Python Flickr GUI? We’ll be using Web 2.0 APIs for this project. Write a program that displays a wallpaper picture made of Flickr photos about a given topic. That is, the program should: • Have a GUI that enables the user to enter a topic. • Query Flickr to gather relevant photos. • Display a wallp...
How do I make a Python Flickr GUI?
We’ll be using Web 2.0 APIs for this project. Write a program that displays a wallpaper picture made of Flickr photos about a given topic. That is, the program should: • Have a GUI that enables the user to enter a topic. • Query Flickr to gather relevant photos. • Display a wallpaper picture made of at least 16 differe...
[ "What you would need is. \n1. Ability to fetch all photos about a given topic from flickr, I think the flickr API gives you that option. This should be a good starting point\n\nStitch at least 16 photos together to form a wall paper using Python Imaging library.\nDisplay these photos together. \n\n" ]
[ 1 ]
[]
[]
[ "api", "python", "python_imaging_library", "user_interface" ]
stackoverflow_0005655849_api_python_python_imaging_library_user_interface.txt
Q: Python: get all values associated with key in a dictionary, where the values may be a list or a single item I'm looking to get all values associated with a key in a dictionary. Sometimes the key holds a single dictionary, sometimes a list of dictionaries. a = { 'shelf':{ 'book':{'title':'the catcher in the r...
Python: get all values associated with key in a dictionary, where the values may be a list or a single item
I'm looking to get all values associated with a key in a dictionary. Sometimes the key holds a single dictionary, sometimes a list of dictionaries. a = { 'shelf':{ 'book':{'title':'the catcher in the rye', 'author':'j d salinger'} } } b = { 'shelf':[ {'book':{'title':'kafka on the shore', 'author':'har...
[ "Given your code will break if you have a list with a single item (and this is how I think it should be), if you really can't change your data structure this is a bit more robust and logic:\ndef print_books(d):\n if isinstance(d['shelf'], dict):\n print d['shelf']['book']['title']\n else:\n for ...
[ 5, 3, 1, 0 ]
[]
[]
[ "dictionary", "key", "python" ]
stackoverflow_0005655420_dictionary_key_python.txt
Q: MIRC Port Scanner if data.find('!scan') != -1: nick = data.split('!')[ 0 ].replace(':','') targetip = str(socket.gethostbyname(args)) sck.send('PRIVMSG ' + chan + " :" ' scanning host' + " " + targetip + '\r\n') for i in range(20, 1025): s = socket.socket(socket.AF_INET, socket.SOCK_...
MIRC Port Scanner
if data.find('!scan') != -1: nick = data.split('!')[ 0 ].replace(':','') targetip = str(socket.gethostbyname(args)) sck.send('PRIVMSG ' + chan + " :" ' scanning host' + " " + targetip + '\r\n') for i in range(20, 1025): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result...
[ "The best solution is to use multiple threads, with the main thread parsing input from IRC and responding to PINGs, while other threads do actual command processing and anything that could take a long time. \nskybot, my IRC bot, spawns a new thread whenever a command is issued, and uses thread-safe queues to pass m...
[ 1 ]
[]
[]
[ "irc", "python", "sockets" ]
stackoverflow_0005655968_irc_python_sockets.txt
Q: allocating memory for list - Python I have a small problem. How do I allocate some memory for a list. Let's say it'll have 4 elements, but this code gives error that it can't assign to operator. char *buf1 = int* PyMem_New(int, 4) Maybe it's late, but I need it for my college assignment. THANK YOU very much! A: ...
allocating memory for list - Python
I have a small problem. How do I allocate some memory for a list. Let's say it'll have 4 elements, but this code gives error that it can't assign to operator. char *buf1 = int* PyMem_New(int, 4) Maybe it's late, but I need it for my college assignment. THANK YOU very much!
[ "PyList_New() allows you to specify an initial size in the single mandatory argument. Don't forget to actually set the items with PyList_SetItem() before using the list in Python code though.\n", "I believe buf1 needs to be a pointer.\nchar *buf1 = PyMem_New(int, 4);\n\n" ]
[ 1, 0 ]
[]
[]
[ "allocation", "list", "malloc", "memory", "python" ]
stackoverflow_0005656378_allocation_list_malloc_memory_python.txt
Q: Reverse lookup on Django m2m field? I have a Django object called "Family". "Family" has the variable "children", which is a many to many field of a class called "Child". If I have a "Child" object, is there a way I get the family object to which the child belongs? Child some more fields... Family chi...
Reverse lookup on Django m2m field?
I have a Django object called "Family". "Family" has the variable "children", which is a many to many field of a class called "Child". If I have a "Child" object, is there a way I get the family object to which the child belongs? Child some more fields... Family children = models.ManyToManyField(Child) ...
[ "Django automatically creates a reverse relationship for you in this case, so with an instance of the Child model, you can find all Family instances to which the child belongs:\nc = Child.objects.get(id=1)\nc.family_set.all() # gives you a list of Families\n\nSince it's unlikely a child will belong to multiple fam...
[ 5, 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005656564_django_python.txt
Q: How to model lending items between a group of companies I have a group of related companies that share items they own with one-another. Each item has a company that owns it and a company that has possession of it. Obviously, the company that owns the item can also have possession of it. Also, companies sometimes p...
How to model lending items between a group of companies
I have a group of related companies that share items they own with one-another. Each item has a company that owns it and a company that has possession of it. Obviously, the company that owns the item can also have possession of it. Also, companies sometimes permanently transfer ownership of items instead of just lendin...
[ "Is there a reason why you don't want your item to contain the relationship information? It feels like the owner and possessor are attributes of the item.\nclass Company(models.Model):\n pass\n\nclass Item(models.Model):\n ...\n owner = models.ForeignKey(Company, related_name='owned_items')\n holder = m...
[ 2, 0, 0 ]
[]
[]
[ "database_design", "design_patterns", "django", "django_models", "python" ]
stackoverflow_0005656345_database_design_design_patterns_django_django_models_python.txt
Q: Shorthand for defining Python functions that are the same? If I have many variables I want to initialize with the same value, I use: a = b = c = "" Is there a similar shorthand for defining many functions that do the same thing? That is, neither of the following works: def x() = y() = z(): def x() = def y() = def...
Shorthand for defining Python functions that are the same?
If I have many variables I want to initialize with the same value, I use: a = b = c = "" Is there a similar shorthand for defining many functions that do the same thing? That is, neither of the following works: def x() = y() = z(): def x() = def y() = def z():
[ "You can simply assign functions like you would assign variables.\ndef z():\n whatever\n\nx = y = z\n\nYou can't do it in one line if you want to use def, but if you can make it into a lambda you can make a one-liner:\nx = y = z = lambda foo: bar()\n\n", "How about:\ndef z():\n pass\n\nx = y = z\n\n", "Uhm....
[ 6, 1, 0, 0 ]
[]
[]
[ "function", "python" ]
stackoverflow_0005656840_function_python.txt
Q: How do I make a python script like answer = raw_input() if answer: BLAH import script How do I make a python script as: answer = raw_input() if answer: "BLAH" then import script Well I'm new to python and really programming altogether. I got this book on python called learning python by: Mark Lutz. no where in th...
How do I make a python script like answer = raw_input() if answer: BLAH import script
How do I make a python script as: answer = raw_input() if answer: "BLAH" then import script Well I'm new to python and really programming altogether. I got this book on python called learning python by: Mark Lutz. no where in the book have i found out how to do this but I haven't read threw the book fully I have looke...
[ ">>> if raw_input(\"input something!:\") == 'BLAH':\n... import some_module.py\n... \ninput something!:BLAH\nTraceback (most recent call last):\n File \"<stdin>\", line 2, in <module>\nImportError: No module named some_module.py\n>>> \n\n", "You mean something like this?\ntext = raw_input(\"import y/n: \")\n...
[ 2, 1, 1 ]
[]
[]
[ "python", "variables" ]
stackoverflow_0005656775_python_variables.txt
Q: Read file error in Python, even though print function is printing the list I have been trying different ways of writing this code but cannot get past this. Currently the program will run all the way to the write_names(list) function and create the file, and the print function will print the sorted list. The prog...
Read file error in Python, even though print function is printing the list
I have been trying different ways of writing this code but cannot get past this. Currently the program will run all the way to the write_names(list) function and create the file, and the print function will print the sorted list. The program refuses to get the user input for the search_names() function but it will pr...
[ "Your issue is that upper is a function, and you are not calling it. Your while in search_names() should read: \nwhile again.upper() == 'Y':\n\n", "instead of:\n#strip \\n from each element\nindex = 0\nwhile index < len(list):\n list[index] = list[index].rstrip('\\n')\n index += 1\nreturn list\n\njust use ...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005656922_python.txt
Q: How do I speed up iteration of large datasets in Django I have a query set of approximately 1500 records from a Django ORM query. I have used the select_related() and only() methods to make sure the query is tight. I have also used connection.queries to make sure there is only this one query. That is, I have ma...
How do I speed up iteration of large datasets in Django
I have a query set of approximately 1500 records from a Django ORM query. I have used the select_related() and only() methods to make sure the query is tight. I have also used connection.queries to make sure there is only this one query. That is, I have made sure no extra queries are getting called on each iteration...
[ "A QuerySet can get pretty heavy when it's full of model objects. In similar situations, I've used the .values method on the queryset to specify the properties I need as a list of dictionaries, which can be much faster to iterate over.\nDjango documentation: values_list\n", "1500 records is far from being a large...
[ 16, 3, 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005656238_django_python.txt
Q: recfromcsv, genfromtxt, recfromtxt mysteriously missing from numpy I am used to using numpy.recfromcsv to load csv files as record arrays in python. However on my new laptop (MB pro running OS 10.6.6), numpy doesn't seem to recognize recfromcsv as a function (same with genfromtxt or recfromtxt). >>> import numpy a...
recfromcsv, genfromtxt, recfromtxt mysteriously missing from numpy
I am used to using numpy.recfromcsv to load csv files as record arrays in python. However on my new laptop (MB pro running OS 10.6.6), numpy doesn't seem to recognize recfromcsv as a function (same with genfromtxt or recfromtxt). >>> import numpy as np >>> np.recfromcsv Traceback (most recent call last): File "<stdin>"...
[ "If you look at:\nnp.version.version\n\nyou'll see that on mac it's version 1.2.1 (at least on my machine). np.recfromcsv was likely added in a newer release of numpy so that's why you're missing it along with the other methods.\nThis is a fairly old version of numpy, so you should think about upgrading. And I reco...
[ 3 ]
[]
[]
[ "genfromtxt", "macos", "numpy", "python" ]
stackoverflow_0005656821_genfromtxt_macos_numpy_python.txt
Q: Python immutable object from within function I asked a previous question on stackoverflow here: Python immutable types in function calls which made it clear that only references to immutable objects are passed to functions, and so passing a tuple to a function does not result in a full memory copy of that object....
Python immutable object from within function
I asked a previous question on stackoverflow here: Python immutable types in function calls which made it clear that only references to immutable objects are passed to functions, and so passing a tuple to a function does not result in a full memory copy of that object. However, according to: http://www.testingreflecti...
[ "You will think a lot more clearly about variables in Python if you think of them not as boxes that contain values, but names that are attached to objects. Any object can have any number of names attached to it; some of the names are local to functions and will be taken off the object automatically when the functio...
[ 6, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005657054_python.txt
Q: Property lat must be a float displaying in my dashboard I have created a Google AppEngine Project which takes in a .txt file, finds locations within the file and uses Yahoo Placemaker to plot a maker on the map to represent the .txt file. The project works fine when I run in on my localhost but when I try and uplo...
Property lat must be a float displaying in my dashboard
I have created a Google AppEngine Project which takes in a .txt file, finds locations within the file and uses Yahoo Placemaker to plot a maker on the map to represent the .txt file. The project works fine when I run in on my localhost but when I try and upload it to appspot I get an error: BadValueError: Property lat...
[ "\nThe really obvious: path = '/Users/kimmasterson/storing/txtFiles' - I hope you're not uploading exactly that to Appengine, because obviously that's not going to work on a remote server.\nIf you print out some details about place, what do you get just before the error?\n\nEDIT:\nLooking at what you're trying to d...
[ 2, 0 ]
[]
[]
[ "cron", "floating_point", "google_app_engine", "python" ]
stackoverflow_0005647706_cron_floating_point_google_app_engine_python.txt
Q: Pass variables to a "success" page after processing a form in Django Is there anyway to pass context variables to a redirect response? I want to redirect a user to a success page after they submit a form, but I don't want the success page to be just a static html file. I need to display extra information based on ...
Pass variables to a "success" page after processing a form in Django
Is there anyway to pass context variables to a redirect response? I want to redirect a user to a success page after they submit a form, but I don't want the success page to be just a static html file. I need to display extra information based on the form data. I have looked at this question, but the solution presented ...
[ "The way I see it you have three options:\n\nUse GET variables in the redirect.\nStore something in the session.\nIf you are creating an object using the form that was submitted, put the id of that object in the redirect url and use it in the new view.\n\nThe limitation you are running up against is that http is st...
[ 5, 4 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0005657235_django_django_forms_python.txt
Q: In python how can I match two lists of tuples by a tuple element? Let's say I have names as a list of tuples that contain name tuples in arbitrary order: names = [(1,"Alice"), (2,"Bob")] and genders as another list of tuples that contain gender tuples in arbitrary order: genders = [(2,"male"), (1,"female")] How ...
In python how can I match two lists of tuples by a tuple element?
Let's say I have names as a list of tuples that contain name tuples in arbitrary order: names = [(1,"Alice"), (2,"Bob")] and genders as another list of tuples that contain gender tuples in arbitrary order: genders = [(2,"male"), (1,"female")] How can I effectively match the two lists by using the first elements of th...
[ "Convert to dictionaries, gather the keys, and iterate.\n", "Easy one-liner answer, runs slowly:\n[(name, gender) for (id0, gender) in genders for (id1, name) in names if id0==id1]\n\nBetter answer (see Ignazio's response):\nnamedict = dict(names)\ngenderdict = dict(genders)\n[(namedict[id], genderdict[id]) for i...
[ 7, 7 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0005657297_list_python_tuples.txt
Q: How to remove non-ascii infected rows in my csv I have a very large csv file that looks like this: keywords,impressions descargar juegos gratis,951 パソコン kakaku com,451 corporate meeting,155 rental cars,356 smart,1224 guitar tab,064 英语翻译,160 I have read the file into a dict like so: # Read the CSV f...
How to remove non-ascii infected rows in my csv
I have a very large csv file that looks like this: keywords,impressions descargar juegos gratis,951 パソコン kakaku com,451 corporate meeting,155 rental cars,356 smart,1224 guitar tab,064 英语翻译,160 I have read the file into a dict like so: # Read the CSV filename = argv[1] csvfile = open(filename, 'r') csvre...
[ "Easy way: you can try to decode it, and catch the exception.\ntry:\n string.decode('ascii')\nexcept UnicodeDecodeError:\n print \"Not ascii\"\n\n", "import csv, sys\n\nfilename = sys.argv[1]\ncsvfile = open(filename, 'r')\ncsvreader = csv.DictReader(csvfile)\nrows = []\nfor row in csvreader:\n try:\n ...
[ 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005656528_python.txt
Q: Emulating a HTTP Post Request in Python I am trying to send a HTTP post request in a PHP page. I gave a try on both Java and Python (this was the first time I used Python) and I can say that both of them worked almost fine for me. Actually, they worked fine only for my test PHP page. For some reason, neither of th...
Emulating a HTTP Post Request in Python
I am trying to send a HTTP post request in a PHP page. I gave a try on both Java and Python (this was the first time I used Python) and I can say that both of them worked almost fine for me. Actually, they worked fine only for my test PHP page. For some reason, neither of them worked for my target PHP page. In my opini...
[ "I use paste.proxy.TransparentProxy and webob.Request ...\nYou need to install the libraries \neasy_install webob webtest paste\n\nor \npip install webob webtest paste\n\nthen in a script...\nfrom paste.proxy import TransparentProxy\nfrom webob import Request\nproxy_app = TransparentProxy() \nrequest = Request.b...
[ 1 ]
[]
[]
[ "http", "php", "post", "python", "request" ]
stackoverflow_0005656801_http_php_post_python_request.txt
Q: NumPy: load heterogenous columns of data from list of strings I'm working with array data stored in an ASCII file (similar to this thread). My file is at least 2M lines (158 MB), and is divided into multiple sections with different schemas. In my module to read the format, I want to read the whole file via lines =...
NumPy: load heterogenous columns of data from list of strings
I'm working with array data stored in an ASCII file (similar to this thread). My file is at least 2M lines (158 MB), and is divided into multiple sections with different schemas. In my module to read the format, I want to read the whole file via lines = open('myfile.txt', 'r').readlines(), so I can index the positions ...
[ "StringIO can make file-type objects from strings. So you could do\nfrom StringIO import StringIO\nm = np.loadtxt(StringIO('\\n'.join(lines[5:10])))\n\nOr even easier, just do\nm = np.fromiter(lines[5:10],np.dtype([('col1', '<i2'), ('col2', 'f4'), ('col3', 'f4')]))\n\n" ]
[ 3 ]
[]
[]
[ "load", "numpy", "python" ]
stackoverflow_0005657444_load_numpy_python.txt
Q: My python script dosen't open the browser and auto log in I have written a python script to auto login into a website every time I click on it. The script runs fine on the command prompt but does not open the browser. I can see the html source code run in the command prompt but it doesn't open the browser. I have ...
My python script dosen't open the browser and auto log in
I have written a python script to auto login into a website every time I click on it. The script runs fine on the command prompt but does not open the browser. I can see the html source code run in the command prompt but it doesn't open the browser. I have not included any browser based command also, may be thats one r...
[ "AFAIK, urllib has no relationship with your browser. Instead, Python is successfully connecting itself to the remote system, logging in, and retrieving the resulting page. \nYou probably want webbrowser, not urllib. The documentation for that module is here: http://docs.python.org/library/webbrowser.html\n" ]
[ 1 ]
[]
[]
[ "autologin", "browser", "python" ]
stackoverflow_0005656896_autologin_browser_python.txt
Q: In python, how do I copy files into a directory and stop once that directory reaches a certain size I am still very new to Python, but I am trying to create a program which will, among other things, copy the contents of a directory into a set of directories that will fit onto a disc (I have it set up the following...
In python, how do I copy files into a directory and stop once that directory reaches a certain size
I am still very new to Python, but I am trying to create a program which will, among other things, copy the contents of a directory into a set of directories that will fit onto a disc (I have it set up the following variables to be the size capacities I want, and set up an input statement to say which one applies): Blu...
[ "You can use os.path.getsize to get the size of a file, and you can use os.walk to walk a directory tree, so something like the following (I'll let you implement CreateOutputDirectory and CopyFileToDirectory):\ncurrent_destination = CreateOutputDirectory()\nfor root, folders, files in os.walk(input_directory):\n ...
[ 3, 0 ]
[]
[]
[ "copy", "directory", "python" ]
stackoverflow_0005657216_copy_directory_python.txt
Q: how to reorder columns in a google spreadsheet I would like to programmatically reorder the columns in a Google spreadsheet, preferably with the python client library. Any ideas on how to do this using the API itself? A: download it as a xls file. use xlrd to read the content and xlwt to write back. See python-e...
how to reorder columns in a google spreadsheet
I would like to programmatically reorder the columns in a Google spreadsheet, preferably with the python client library. Any ideas on how to do this using the API itself?
[ "download it as a xls file. use xlrd to read the content and xlwt to write back. See python-excel\nfor example:\nimport xlrd\nwb = xlrd.open_workbook('myworkbook.xls')\nb.sheet_names()\nsh = wb.sheet_by_index(0)\ncol = sh.col_values(0)\n.....\n\njust refer to the documents of the package\n==========================...
[ 2 ]
[]
[]
[ "google_sheets", "google_spreadsheet_api", "python" ]
stackoverflow_0005657129_google_sheets_google_spreadsheet_api_python.txt
Q: Python Desktop Program Using Web APIs I have a very random request from a client wanting a desktop based program that can retrieve information from web based APIs such as Google Analytics, SEOMoz and other similar services. They then want parts or all of these results stored in a central location. They have said t...
Python Desktop Program Using Web APIs
I have a very random request from a client wanting a desktop based program that can retrieve information from web based APIs such as Google Analytics, SEOMoz and other similar services. They then want parts or all of these results stored in a central location. They have said they DO NOT want a web application at all, b...
[ "\nyes, urllib, urllib2 and urlparse are the core python libs for reading to/from urls. I would suggest PyQt for the gui framework (pyGTK, wxWidgets and tkinter would be fine also, they all run fine on the three os's you've mentioned). PyQt includes everything you would need, without reaching into any other libra...
[ 2 ]
[]
[]
[ "api", "desktop_application", "python" ]
stackoverflow_0005657800_api_desktop_application_python.txt
Q: Python Extensionless URLs with out mod_rewrite I am currently porting over a website from php to python. The php web app is using extenionless urls by using DefaultType application/x-httpd-php Is there something like this that I can do for python? I have searched around through Google and tried adding mime types ...
Python Extensionless URLs with out mod_rewrite
I am currently porting over a website from php to python. The php web app is using extenionless urls by using DefaultType application/x-httpd-php Is there something like this that I can do for python? I have searched around through Google and tried adding mime types that would make sense for python but so far have not...
[ "WSGI doesn't use/need extensions at all; your routing framework handles the URL appropriately. And if you aren't using WSGI... why not?\n", "I guess a full answer would take forever, but the best way to run python on apache is through WSGI, so I suggest your start looking here: http://code.google.com/p/modwsgi/\...
[ 1, 0 ]
[]
[]
[ "canonicalization", "python" ]
stackoverflow_0005657843_canonicalization_python.txt
Q: Basic question on Object Oriented programming in Python I'm having a hard time grasping the variables inside a method of a Class, and am seeking an explanation of how these work, to help me better understand it. For example: inside Time class def __init__(self, hour,minute, second) self.hour = hour self.mi...
Basic question on Object Oriented programming in Python
I'm having a hard time grasping the variables inside a method of a Class, and am seeking an explanation of how these work, to help me better understand it. For example: inside Time class def __init__(self, hour,minute, second) self.hour = hour self.minute = minute self.second = second def print_time(self):...
[ "\nMagic. Python-specific magic, to be exact; other languages may (and frequently do) choose to do it differently.\nIt can be. In Python, Class.method(obj) is the same as obj.method() when obj is an instance of Class. __init__() is a special case though.\n\n", "Where did you get this wierd code? It does not make ...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005657712_python.txt
Q: sum over bin range in python I have a numpy array with shape: In: imar.shape Out: (21, 77, 10000) I want a binned sum on the last axis, with every bin containing 20 items. The way I'm doing this now is: np.sum( imar.reshape([-1,500,20]), axis=2 ).reshape(imar.shape[:2]) It's fast, but seems error-prone if I ge...
sum over bin range in python
I have a numpy array with shape: In: imar.shape Out: (21, 77, 10000) I want a binned sum on the last axis, with every bin containing 20 items. The way I'm doing this now is: np.sum( imar.reshape([-1,500,20]), axis=2 ).reshape(imar.shape[:2]) It's fast, but seems error-prone if I get the arguments to reshape wrong. ...
[ "You have the right approach. I asked a similar question a while back:\nHow can I efficiently process a numpy array in blocks similar to Matlab's blkproc (blockproc) function \nThere are several approaches to handling the reshape. If you are careful and write a function to do it, you'll be alright. Of course, yo...
[ 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0005656427_numpy_python.txt
Q: How to parse a specific wiki page & automate that? I am try to make a web application that needs to parse one specific wikipedia page & extract some information which is stored in a table format on the page. The extracted data would then need to be stored onto a database. I haven't really done anything like this ...
How to parse a specific wiki page & automate that?
I am try to make a web application that needs to parse one specific wikipedia page & extract some information which is stored in a table format on the page. The extracted data would then need to be stored onto a database. I haven't really done anything like this before. What scripting language should I use to do this?...
[ "\nWhat scripting language should I use to do this? \n\nPython will do, as you've tagged your question.\n\nlooks like Python (using urllib2 & BeautifulSoup) should do the job, but is it the best way of approaching the problem.\n\nIt's workable. I'd use lxml.etree personally. An alternative is fetching the page in t...
[ 1, 0 ]
[]
[]
[ "parsing", "python", "screen_scraping" ]
stackoverflow_0005647413_parsing_python_screen_scraping.txt
Q: Unicode strings in tornado web app How can I use unicode strings in tornado views or templates? I insert in template <meta http-equiv="content-type" content="text/html;charset=utf-8" /> And in view# -- coding: utf-8 -- Output is ???? A: Once you have your unicode string ready, the request should end self.render(...
Unicode strings in tornado web app
How can I use unicode strings in tornado views or templates? I insert in template <meta http-equiv="content-type" content="text/html;charset=utf-8" /> And in view# -- coding: utf-8 -- Output is ????
[ "Once you have your unicode string ready, the request should end\nself.render(\"template.html\", aString=aUnicodeString)\n\nThis renders the file \"template.html\" setting the aString variable to aUnicodeString.\ntemplate.html would look something like this:\n<html>\n <head>\n <meta http-equiv=\"Content-T...
[ 1 ]
[]
[]
[ "python", "tornado" ]
stackoverflow_0005647648_python_tornado.txt
Q: Python Timed-Script How do I have a python script run everyday at a set-time. Say exactly at 2:00 P.M. every day. Is there a way to have it run exactly twice a day? Not really sure where to start with this. Thanks for the help. A: Don't reinvent and use functionality existing for decades on any system: cron Apar...
Python Timed-Script
How do I have a python script run everyday at a set-time. Say exactly at 2:00 P.M. every day. Is there a way to have it run exactly twice a day? Not really sure where to start with this. Thanks for the help.
[ "Don't reinvent and use functionality existing for decades on any system: cron\nApart from that: PyPI lists a bunch of cron-related or cron-similar packages:\nhttp://pypi.python.org/pypi?%3Aaction=search&term=cron&submit=search\nIn addition: Python provides a dedicated 'sched' module:\nhttp://docs.python.org/librar...
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0005657429_python.txt
Q: virtualenv pip mysqldb mac os X python I tried this http://jazstudios.blogspot.com/2010/07/installing-mysql-python-mysqldb-in.html tip to install mysql-python (mysqldb) inside a virtualenv (named dogme). (this post point out 2 important things : export ARCHFLAGS="-arch x86_64" echo "mysql_config = /opt/local/bin/...
virtualenv pip mysqldb mac os X python
I tried this http://jazstudios.blogspot.com/2010/07/installing-mysql-python-mysqldb-in.html tip to install mysql-python (mysqldb) inside a virtualenv (named dogme). (this post point out 2 important things : export ARCHFLAGS="-arch x86_64" echo "mysql_config = /opt/local/bin/mysql_config5" >> ./dogme/build/MySQL-python...
[ "I had a similar problem, look my traceback:\n>>> import MySQLdb\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"/Library/Python/2.6/site-packages/MySQLdb/__init__.py\", line 19, in <module>\n import _mysql\nImportError: dlopen(/Library/Python/2.6/site-packages/_mysql.so, 2...
[ 2 ]
[]
[]
[ "macos", "mysql", "pip", "python", "virtualenv" ]
stackoverflow_0004954884_macos_mysql_pip_python_virtualenv.txt
Q: Why does this code have this error: "Expected:)"? I am getting an error from Aptana "Expected:)" on this code at the return render_to_response line after the final else:. I can't for the life of me figure out why that is, because as far as I can tell I have closed all of my parentheses. I'm guessing that it is a...
Why does this code have this error: "Expected:)"?
I am getting an error from Aptana "Expected:)" on this code at the return render_to_response line after the final else:. I can't for the life of me figure out why that is, because as far as I can tell I have closed all of my parentheses. I'm guessing that it is actually some other error and Aptana (Eclipse branch) is...
[ "There's a comma missing after 'login.html' in the else: section\n", "You're missing a comma after the template name in the final return line.\nYou have:\nreturn render_to_response('login.html' {\n 'failed_login' : False,\n 'form' : Authenticat...
[ 4, 2 ]
[]
[]
[ "aptana", "django", "python" ]
stackoverflow_0005658265_aptana_django_python.txt
Q: What's the fastest way to convert an interleaved NumPy integer array to complex64? I have a stream of incoming data that has interleaved real and imaginary integers. Converting these to complex64 values is the slowest operation in my program. This is my current approach: import numpy as np a = np.zeros(1000000, d...
What's the fastest way to convert an interleaved NumPy integer array to complex64?
I have a stream of incoming data that has interleaved real and imaginary integers. Converting these to complex64 values is the slowest operation in my program. This is my current approach: import numpy as np a = np.zeros(1000000, dtype=np.int16) b = np.complex64(a[::2]) + np.complex64(1j) * np.complex64(a[1::2]) Can ...
[ "[~]\n|1> import numpy as np\n\n[~]\n|2> a = np.zeros(1000000, dtype=np.int16)\n\n[~]\n|3> b = a.astype(np.float32).view(np.complex64)\n\n[~]\n|4> b.shape\n(500000,)\n\n[~]\n|5> b.dtype\ndtype('complex64')\n\n" ]
[ 21 ]
[]
[]
[ "complex_numbers", "numpy", "python" ]
stackoverflow_0005658047_complex_numbers_numpy_python.txt
Q: Best method for appending new column in tab delimited csv file How can I read and write at the same time in csv file. def read_txt_file(txt_filename): def get_all_sheet_values(filename): lines = [] myFile= open( filename, "rU" ) for aRow in myFile: val = aRow.split('\t') val = map(lam...
Best method for appending new column in tab delimited csv file
How can I read and write at the same time in csv file. def read_txt_file(txt_filename): def get_all_sheet_values(filename): lines = [] myFile= open( filename, "rU" ) for aRow in myFile: val = aRow.split('\t') val = map(lambda s: s.strip(), val) if len(val) > 1 : print v...
[ "Files don't work that way. Write to a new file, and rename it after.\n", "You can't. When you add the column you are making each line longer. If you were to write it out before going to the next line you would overwrite a portion of it.\n" ]
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005658452_python.txt
Q: Which of these are immutable in Python? I am trying to figure out whether the following are immutable in Sage (which is built on Python so I believe if it is immutable in python, I believe in most cases it will be immutable in Sage) Below are objects e, f, g, i class e: pass f = e() g = pi # (g's "type" in Sage is...
Which of these are immutable in Python?
I am trying to figure out whether the following are immutable in Sage (which is built on Python so I believe if it is immutable in python, I believe in most cases it will be immutable in Sage) Below are objects e, f, g, i class e: pass f = e() g = pi # (g's "type" in Sage is symbolic expression. It's supposed to be 3.1...
[ "e is mutable. You can, for instance, add a new method on the class: e.foo = lambda self,x: x.\nf is mutable. You can, for instance, add a new field to this class instance: f.x = 99.\ng is immutable. You can't change anything about it.\ni is not immutable. You can do all sorts of evil things to it: i.func_code = (l...
[ 7, 3 ]
[]
[]
[ "immutability", "python" ]
stackoverflow_0005656998_immutability_python.txt
Q: Designing a Website Backend - Python or C++/C#? I am working on a realtime data website that has a data-mining backend side to it. I am highly experienced in both Python and C++/C#, and wondering which one would be preferable for the backend development. I am strongly leaning towards Python for its available libra...
Designing a Website Backend - Python or C++/C#?
I am working on a realtime data website that has a data-mining backend side to it. I am highly experienced in both Python and C++/C#, and wondering which one would be preferable for the backend development. I am strongly leaning towards Python for its available libraries and ease of use. But am I wrong? If so, why? As ...
[ "We do backend development based on Zope, Python and other Python-related stuff since almost 15 years. Python gives you great flexibility and all-batteries included (likely true for C#, not sure about C++).\nIf you do RDBMS development with Python: SQLAlchemy is the way to go. It provides a huge functionality and s...
[ 1 ]
[]
[]
[ "backend", "c#", "c++", "python" ]
stackoverflow_0005658529_backend_c#_c++_python.txt
Q: Python MySQL Unicode Error I am trying to insert a query that contains é - or \xe9 (INSERT INTO tbl1 (text) VALUES ("fiancé")) into a MySQL table in Python using the _mysql module. My query is in unicode, and when I call _mysql.connect(...).query(query) I get a UnicodeEncodeError: 'ascii' codec can't encode charac...
Python MySQL Unicode Error
I am trying to insert a query that contains é - or \xe9 (INSERT INTO tbl1 (text) VALUES ("fiancé")) into a MySQL table in Python using the _mysql module. My query is in unicode, and when I call _mysql.connect(...).query(query) I get a UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position X : ordi...
[ "I know this doesn't directly answer your question, but why aren't you using prepared statements? That will do two things: probably fix your problem, and almost certainly fix the SQLi bug you've almost certainly got.\nIf you won't do that, are you absolutely certain your string itself is unicode? If you're just nai...
[ 0 ]
[]
[]
[ "mysql", "python", "unicode" ]
stackoverflow_0005658737_mysql_python_unicode.txt
Q: How do you construct a GUID with a set prefix and zero-padded suffix? Freebase's Python API uses GUIDs that have a set prefix and a zero-padded suffix: "guid":"#9202a8c04000641f8000000000211f52" (http://wiki.freebase.com/wiki/Guid) "Freebase guids are represented with 32 hexidecimal characters, the first 17 are th...
How do you construct a GUID with a set prefix and zero-padded suffix?
Freebase's Python API uses GUIDs that have a set prefix and a zero-padded suffix: "guid":"#9202a8c04000641f8000000000211f52" (http://wiki.freebase.com/wiki/Guid) "Freebase guids are represented with 32 hexidecimal characters, the first 17 are the graph prefix and the remaining 15 are the item suffix" (http://tinyify.fr...
[ "You'd need to look at the source for Freebase where it generates that GUID. It's definitely not a standard RFC GUID of any sort.\n" ]
[ 0 ]
[]
[]
[ "guid", "python", "tinyurl", "uuid" ]
stackoverflow_0005652093_guid_python_tinyurl_uuid.txt
Q: PyCUDA: Pow within device code tries to use std::pow, fails Question more or less says it all. calling a host function("std::pow<int, int> ") from a __device__/__global__ function("_calc_psd") is not allowed from my understanding, this should be using the cuda pow function instead, but it isn't. A: The error i...
PyCUDA: Pow within device code tries to use std::pow, fails
Question more or less says it all. calling a host function("std::pow<int, int> ") from a __device__/__global__ function("_calc_psd") is not allowed from my understanding, this should be using the cuda pow function instead, but it isn't.
[ "The error is exactly as the compiler is reported. You can't used host functions in device code, and that include the whole host C++ std library. CUDA includes its own standard library, described in the programming guide, but you should use either pow or fpow (taken from the C standard library, no C++ or namespaces...
[ 7 ]
[]
[]
[ "cuda", "pow", "pycuda", "python" ]
stackoverflow_0005656605_cuda_pow_pycuda_python.txt
Q: Limit the size of wxListCtrl in wxpython I want to limit the size of a list control box. Let us take the following code: import wx class Students(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(380, 230)) hbox = wx.BoxSizer(wx.HORIZONTAL) ...
Limit the size of wxListCtrl in wxpython
I want to limit the size of a list control box. Let us take the following code: import wx class Students(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(380, 230)) hbox = wx.BoxSizer(wx.HORIZONTAL) panel = wx.Panel(self, -1) self....
[ "You can set the width of your list control manually and then set the proportion to 0. \nThe width of columns can be set manually:\nimport wx\n\nclass MainWindow(wx.Frame):\n def __init__(self, *args, **kwargs):\n wx.Frame.__init__(self, *args, **kwargs)\n self.panel = wx.Panel(self)\n self....
[ 5, 0 ]
[]
[]
[ "python", "user_interface", "wxpython" ]
stackoverflow_0005648816_python_user_interface_wxpython.txt
Q: python subprocess Popen environment PATH? Suppose there's an executable and a Python script to launch it, and they're located in 'sibling' subdirectories, e.g. /tmp/subdir1/myexecutable /tmp/subdir2/myscript.py If in /tmp and running python subdir2/myscript.py with a relative path to executable # myscript.py from...
python subprocess Popen environment PATH?
Suppose there's an executable and a Python script to launch it, and they're located in 'sibling' subdirectories, e.g. /tmp/subdir1/myexecutable /tmp/subdir2/myscript.py If in /tmp and running python subdir2/myscript.py with a relative path to executable # myscript.py from subprocess import Popen proc = Popen(["../subd...
[ "Relative paths (paths containing slashes) never get checked in any PATH, no matter what you do. They are relative to the current working directory only. If you need to resolve relative paths, you will have to search through the PATH manually.\nIf you want to run a program relative to the location of the Python sc...
[ 83, 15, 2, 0 ]
[]
[]
[ "environment", "path", "popen", "python", "subprocess" ]
stackoverflow_0005658622_environment_path_popen_python_subprocess.txt
Q: Easy secure JSON-RPC in python What's the simplest way to set up a JSON-RPC server in python and make it secure? I'm very interested Pyjamas for python/javascript - but the documentation doesn't explain how to implement security with the JSON-RPC. A: I've played with pyjamas a little and am currently implementi...
Easy secure JSON-RPC in python
What's the simplest way to set up a JSON-RPC server in python and make it secure? I'm very interested Pyjamas for python/javascript - but the documentation doesn't explain how to implement security with the JSON-RPC.
[ "I've played with pyjamas a little and am currently implementing json-rpc with django.\nHave you considered using ssl to secure the site. Short of implementing your own (basic) encryption routine, its probably the best way forward.\n" ]
[ 2 ]
[]
[]
[ "json", "pyjamas", "python" ]
stackoverflow_0004999078_json_pyjamas_python.txt
Q: python: change printing of class Is it possible in python to change what is printed for classes. I know that if we provide __str__ __unicode__ methods, we can change the way instances of a class are printed. But i want to do this for a class Eg: class A(object): def __str__(self): return 'hello' a = A...
python: change printing of class
Is it possible in python to change what is printed for classes. I know that if we provide __str__ __unicode__ methods, we can change the way instances of a class are printed. But i want to do this for a class Eg: class A(object): def __str__(self): return 'hello' a = A() print a will print hello. Is it po...
[ "Yes, by providing a metaclass. This is a bad idea because metaclasses don't compose very well, and it's magical and confusing.\n>>> class A(type):\n... def __repr__(self):\n... return '<this is not a class!>'\n...\n>>> class B(object):\n... __metaclass__ = A\n...\n>>> print B\n<this is not a cl...
[ 7, 4 ]
[]
[]
[ "class", "mysql", "object", "printing", "python" ]
stackoverflow_0005659683_class_mysql_object_printing_python.txt
Q: Python JSON Google Translator parsing with Simplejson problem I am trying to parse the Google Translation result using simplejson in Python. But I am getting the following Exception. Traceback (most recent call last): File "Translator.py", line 45, in <module> main() File "Translator.py", line 41, in main ...
Python JSON Google Translator parsing with Simplejson problem
I am trying to parse the Google Translation result using simplejson in Python. But I am getting the following Exception. Traceback (most recent call last): File "Translator.py", line 45, in <module> main() File "Translator.py", line 41, in main parse_json(trans_text) File "Translator.py", line 29, in pars...
[ "The issue is that simplejson supports json with double quote encoded strings and not single quote encoded strings, so a naive solution might be\njson.loads(jsonstring.replace(\"'\", '\"'))\n\n", "You are doing simplejson.loads(str(trans_text))\ntrans_text is NOT a string (str or unicode) or buffer object. This i...
[ 4, 4, 2 ]
[]
[]
[ "python", "simplejson" ]
stackoverflow_0005631288_python_simplejson.txt
Q: Python Threading Hey all, I'm unable to understand some part of the following code (from Programming Python by Mark Lutz): import _thread as thread stdoutmutex = thread.allocate_lock() exitmutexes = [thread.allocate_lock() for i in range(10)] def counter(myId, count): for i in range(count): stdoutmut...
Python Threading
Hey all, I'm unable to understand some part of the following code (from Programming Python by Mark Lutz): import _thread as thread stdoutmutex = thread.allocate_lock() exitmutexes = [thread.allocate_lock() for i in range(10)] def counter(myId, count): for i in range(count): stdoutmutex.acquire() p...
[ "It basically waits until all exit mutexes have been locked and then exits.\nfor mutex in exitmutexes:\n while not mutex.locked(): pass\n\nThis code iterates over the exit mutexes and for each mutex it enters a loop waiting for the mutex to be locked.\nHowever, it uses \"active waiting\" resulting in very high C...
[ 0 ]
[]
[]
[ "multithreading", "python", "python_3.x" ]
stackoverflow_0005659923_multithreading_python_python_3.x.txt
Q: Twisted XML-RPC error I get an exception on both client and server side when I run the first example at http://buildbot.twistedmatrix.com/builds/sphinx-html/291-15849/projects/web/howto/xmlrpc.html. The server code I used is below: from twisted.web import xmlrpc, server class Example(xmlrpc.XMLRPC): """An exa...
Twisted XML-RPC error
I get an exception on both client and server side when I run the first example at http://buildbot.twistedmatrix.com/builds/sphinx-html/291-15849/projects/web/howto/xmlrpc.html. The server code I used is below: from twisted.web import xmlrpc, server class Example(xmlrpc.XMLRPC): """An example object to be published...
[ "Looks like you have an old version of xmlrpclib?\nWhat version of python are you using?\nWhere is the xmlrpclib coming from that your xmlrpc server is using, and what version is it?\n$ python -v\n>>> import xmlrpclib\n# /usr/lib/python2.6/xmlrpclib.pyc matches /usr/lib/python2.6/xmlrpclib.py\n>>> xmlrpclib.__versi...
[ 2 ]
[]
[]
[ "python", "twisted", "xml_rpc" ]
stackoverflow_0005659680_python_twisted_xml_rpc.txt
Q: run "altinstall"ed python2.4 for nodejs install i'm new to linux, please bear with me. i'm trying to get nodejs running on my server, but because the default python version is 2.3, and nodejs requires at least 2.4 to install, i have done a "altinstall" of python2.4. the python should be installed correctly, i can ...
run "altinstall"ed python2.4 for nodejs install
i'm new to linux, please bear with me. i'm trying to get nodejs running on my server, but because the default python version is 2.3, and nodejs requires at least 2.4 to install, i have done a "altinstall" of python2.4. the python should be installed correctly, i can run it like this /usr/local/bin/python2.4, and when i...
[ "I had a look at the sources, and a ./configure --help in the node sources said nothing about specifying your python, so you could try these slightly hackier tricks:\nAn alias python=/usr/local/bin/python2.4 before you execute configure could work.\nIt that doesn't work, a symlink in a custom ~/bin directory (or si...
[ 1 ]
[]
[]
[ "centos", "linux", "node.js", "python" ]
stackoverflow_0005660034_centos_linux_node.js_python.txt
Q: Beginning MySQL/Python I have just begun learning Python. Eventually I will learn Django, as my goal is to able to do web development (video sharing/social networking). At which point should I begin learning MySQL? Do I need to know it before I even begin Django? If so, how much should I look to know before diving...
Beginning MySQL/Python
I have just begun learning Python. Eventually I will learn Django, as my goal is to able to do web development (video sharing/social networking). At which point should I begin learning MySQL? Do I need to know it before I even begin Django? If so, how much should I look to know before diving into Django? Thank you.
[ "Having some ideas of what's going on in ANY database will help you with your web programming endeavours. You're best bet is to spend some time learning basic SQL just using SQLite (it comes with python) and moving what's known as an ORM (Object Relational Mapper) such as SQLAlchemy\nThe current trends point towar...
[ 7, 0, 0, 0 ]
[]
[]
[ "django", "mysql", "new_operator", "python" ]
stackoverflow_0005643400_django_mysql_new_operator_python.txt
Q: Error while installing wxPython package in a non-standard path I am a relative newbie with Python and was trying to install wxPython 2.9 using Python 2.6. I did a build from source and then installed the package both being done in a non-standard (local) path. When I try and import wx (having provided the path to t...
Error while installing wxPython package in a non-standard path
I am a relative newbie with Python and was trying to install wxPython 2.9 using Python 2.6. I did a build from source and then installed the package both being done in a non-standard (local) path. When I try and import wx (having provided the path to the installation folder in my environment variable), I get the follo...
[ "Add the directory containing the library given in the error to your ld search paths. See the ldconfig(8) man page for details.\n" ]
[ 0 ]
[]
[]
[ "gtk", "python", "wxpython" ]
stackoverflow_0005660354_gtk_python_wxpython.txt
Q: Lingering Django Database I had to remove my Django Database (drop all the tables). Now when I try to run "manage.py syncdb" to recreate those tables I get the message "Table 'user_database.engine.city' doesn't exist" Is there a file lingering that is telling djnago these tables still exist? EDITED QUESTION: I had...
Lingering Django Database
I had to remove my Django Database (drop all the tables). Now when I try to run "manage.py syncdb" to recreate those tables I get the message "Table 'user_database.engine.city' doesn't exist" Is there a file lingering that is telling djnago these tables still exist? EDITED QUESTION: I had to remove my Django Database (...
[ "Looks like during model validation your massivecoupon module is doing some imports which trigger the deals module to fill it's cache.\nimports in python actually execute code in the imported module, and this is a classic case of poorly coded import routines having unintended consequences\nwhat i would suggest is t...
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003437375_django_python.txt
Q: Python distribution for Scientists on Linux I would like to find out if there is a Pythonxy.com equivalent for Linux/Mac OS X yet? any kind of pointers would be helpful? Thanks and best regards, Vishal Sapre A: Pythonxy exists for linux : http://pythonxy-linux.googlecode.com A: For linux, you don't need someth...
Python distribution for Scientists on Linux
I would like to find out if there is a Pythonxy.com equivalent for Linux/Mac OS X yet? any kind of pointers would be helpful? Thanks and best regards, Vishal Sapre
[ "Pythonxy exists for linux : http://pythonxy-linux.googlecode.com\n", "For linux, you don't need something like PythonXY, because it's already very easy to install packages with your package manager. Things are actually a lot better integrated under linux than under windows.\nWhat you need to do is pick a good li...
[ 5, 5, 2, 1, 0 ]
[]
[]
[ "distribution", "linux", "python", "pythonxy" ]
stackoverflow_0005659931_distribution_linux_python_pythonxy.txt
Q: When running Virtualenv 1.6 on Mac OS X 10.6.7, Python 2.7.1 I'm currently trying to set up pinax on top of Python 2.7.1 and Django 1.3. For the first few steps, one is required to set up virtualenv, with the following commands: $ virtualenv mysite-env $ source mysite-env/bin/activate (mysite-env)$ I execu...
When running Virtualenv 1.6 on Mac OS X 10.6.7, Python 2.7.1
I'm currently trying to set up pinax on top of Python 2.7.1 and Django 1.3. For the first few steps, one is required to set up virtualenv, with the following commands: $ virtualenv mysite-env $ source mysite-env/bin/activate (mysite-env)$ I execute the first command, and it creates a mysite-env directory, but g...
[ "\nNo such file or directory while executing command install_name_tool\n\ninstall_name_tool command is a part of Mac OS X Developer Tools. Install Xcode to get it.\n" ]
[ 6 ]
[]
[]
[ "django", "macos", "python", "python_2.7", "virtualenv" ]
stackoverflow_0005658504_django_macos_python_python_2.7_virtualenv.txt
Q: NumPy: using loadtxt or genfromtxt to read a ragged structure I need to read an ASCII file into Python, where an excerpt of the file looks like this: E M S T N... ... 9998 1 1 128 10097 10098 10199 10198 20298 20299 20400 20399 9999 1 1 128 10098 10099 10200 10199 20299 20300 20401 20400 10000 1 1 128 1009...
NumPy: using loadtxt or genfromtxt to read a ragged structure
I need to read an ASCII file into Python, where an excerpt of the file looks like this: E M S T N... ... 9998 1 1 128 10097 10098 10199 10198 20298 20299 20400 20399 9999 1 1 128 10098 10099 10200 10199 20299 20300 20401 20400 10000 1 1 128 10099 10100 10201 10200 20300 20301 20402 20401 10001 1 2 44 2071 21...
[ "You do need a custom \"split-cast\" for loop, as far as I know.\nIn fact, NumPy can read nested structures like yours, but they must have a fixed shape, like in\nnumpy.loadtxt('data.txt', dtype=[ ('time', np.uint64), ('pos', [('x', np.float), ('y', np.float)]) ])\n\nWhen trying to read your data with the dtype tha...
[ 2 ]
[]
[]
[ "genfromtxt", "load", "numpy", "python", "tuples" ]
stackoverflow_0005660612_genfromtxt_load_numpy_python_tuples.txt
Q: What is the equivalent in python to this code line in perl $conf{svnlook} log --revision $rev $repo What is the equivalent in python to this code line in perl $conf{svnlook} log --revision $rev $repo i'm looking in python for something as neat as that... A: That's not really valid Perl. Are you sure it wasn'...
What is the equivalent in python to this code line in perl $conf{svnlook} log --revision $rev $repo
What is the equivalent in python to this code line in perl $conf{svnlook} log --revision $rev $repo i'm looking in python for something as neat as that...
[ "That's not really valid Perl. Are you sure it wasn't something like this?\nmy $log = `$conf{svnlook} log --revision $rev $repo`;\n\nThat's calling the svnlook program, an external program not part of Perl. You can do the same thing in Python.\n", "To be exact, what you have there is not a perl command, that i...
[ 4, 3, 3 ]
[]
[]
[ "format", "formatting", "perl", "python", "string_formatting" ]
stackoverflow_0005661344_format_formatting_perl_python_string_formatting.txt
Q: Do PyQt classes inherit from object? Do PyQt classes inherit from object? A: >>> from PyQt4 import QtCore >>> QtCore.QObject.__mro__ (<class 'PyQt4.QtCore.QObject'>, <type 'sip.wrapper'>, <type 'sip.simplewrapper'>, <type 'object'>) So the answer is yes (at least QObject does, but I assume non-descendants of QO...
Do PyQt classes inherit from object?
Do PyQt classes inherit from object?
[ ">>> from PyQt4 import QtCore\n>>> QtCore.QObject.__mro__\n(<class 'PyQt4.QtCore.QObject'>, <type 'sip.wrapper'>, <type 'sip.simplewrapper'>, <type 'object'>)\n\nSo the answer is yes (at least QObject does, but I assume non-descendants of QObject do, too).\n" ]
[ 6 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0005661338_pyqt_python.txt
Q: Where has now() moved in DateTime 2.12 I have a product which I'm supporting which uses the now() method from the DateTime module. from DateTime import now However, in DateTime 2.12 this method no longer exists. Has it been moved to a new location, or is there a new/preferred idiom for getting the current time? ...
Where has now() moved in DateTime 2.12
I have a product which I'm supporting which uses the now() method from the DateTime module. from DateTime import now However, in DateTime 2.12 this method no longer exists. Has it been moved to a new location, or is there a new/preferred idiom for getting the current time?
[ "From this page:\nIf the function is called with no arguments, then the current date/ time is returned, represented in the timezone of the local machine.\nI browsed through the code of DateTime.py and I didn't see a now() method. So to answer your question, to get the current time just do a current = DateTime().\n"...
[ 10, 6, 3 ]
[]
[]
[ "datetime", "python", "zope" ]
stackoverflow_0005661293_datetime_python_zope.txt
Q: using exec() with python 3.2 so normally if i run these script with this code: x=5 exec("x+=1") output=str(x) If I execute the above in a python console, output has a value of "6" But if it's run inside a function, the exec doesn't change the value of x. Why does this happen, and how could I get the same behavio...
using exec() with python 3.2
so normally if i run these script with this code: x=5 exec("x+=1") output=str(x) If I execute the above in a python console, output has a value of "6" But if it's run inside a function, the exec doesn't change the value of x. Why does this happen, and how could I get the same behavior in a function as i do in the con...
[ "WSGI has nothing to do with it. Your test that works is not running the same or even similar code. Here is your WSGI code made into non-WSGI:\n>>> def app():\n... x=5\n... exec(\"x+=1\")\n... print(x)\n... \n>>> app()\n5\n\nAs you see, it also doesn't change x. The code that did was this:\n>>> x=5\n>>>...
[ 7 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0005657519_python_python_3.x.txt
Q: Mercurial CGI (hgweb.cgi) fails I have Mercurial 1.8.1, Python 2.6.6 installed on Win 2k8 R2 running on a vm. I have tried installing from msi, source and using tortisehg. Command-line Hg works fine but I get the same error when running the hgweb.cgi: Traceback (most recent call last): File ".\hgweb.cgi", line ...
Mercurial CGI (hgweb.cgi) fails
I have Mercurial 1.8.1, Python 2.6.6 installed on Win 2k8 R2 running on a vm. I have tried installing from msi, source and using tortisehg. Command-line Hg works fine but I get the same error when running the hgweb.cgi: Traceback (most recent call last): File ".\hgweb.cgi", line 17, in application = hgweb(confi...
[ "I had the same error using following system configuration\n\nPython-2.6.6 installed as msi\nmercurial-1.8.2-x86 installed as msi\nIIS7\n\nI solved this problem simply:\n\nPython has been installed early\nUninstall Mercurial msi package\nDownload and install \"Mercurial-1.8.2 (32-bit py2.6)\" installer from mercuri...
[ 18, 1 ]
[]
[]
[ "mercurial", "python", "windows_server_2008" ]
stackoverflow_0005318970_mercurial_python_windows_server_2008.txt
Q: Python Script works when run from command line but not when run from windows service I have created a windwos service utilising the following code: import win32service import win32serviceutil import win32api import win32con import win32event import win32evtlogutil import os, sys, string, time class aservice(win32...
Python Script works when run from command line but not when run from windows service
I have created a windwos service utilising the following code: import win32service import win32serviceutil import win32api import win32con import win32event import win32evtlogutil import os, sys, string, time class aservice(win32serviceutil.ServiceFramework): _svc_name_ = "PAStoDistillerIFC" _svc_display_name_ ...
[ "I didn't find the cause but I did find a workaround.\nI needed to import all the same libraries into the function too. Once I did that, worked like a charm.\nHope this can help someone else.\n" ]
[ 0 ]
[]
[]
[ "python", "windows_services" ]
stackoverflow_0005634753_python_windows_services.txt
Q: Tkinter OptionMenu Portable Message Box I am trying to create a light weight cross platform Message Box that contains a list of items. Ideally it has an API that allows you to pass in a message to to display, a title, and tuple of choices. When pressing OK it would return the currently selected choice. It would...
Tkinter OptionMenu Portable Message Box
I am trying to create a light weight cross platform Message Box that contains a list of items. Ideally it has an API that allows you to pass in a message to to display, a title, and tuple of choices. When pressing OK it would return the currently selected choice. It would also be preferred that the required modules ...
[ "The normal way dialogs work is something like this:\nmydialog = SomeDialogClass(...)\nresult = mydialog.Show()\nif result == \"OK\":\n print \"you clicked OK; dialog value is\", mydialog.GetValue()\nelse:\n print \"you clicked cancel\"\nmydialog.Destroy()\n\nThis is pseudocode, intended to be GUI toolkit ag...
[ 1 ]
[]
[]
[ "python", "tk_toolkit", "tkinter" ]
stackoverflow_0005658695_python_tk_toolkit_tkinter.txt
Q: Reading parts of binary data in a string in Python When you use the .read(n) method on a file object in python you get n amount of bytes back. What if I first load a file in a string, is there some function that lets me do the same thing? Because I guess it's not as easy filestring[0:5], because of different types...
Reading parts of binary data in a string in Python
When you use the .read(n) method on a file object in python you get n amount of bytes back. What if I first load a file in a string, is there some function that lets me do the same thing? Because I guess it's not as easy filestring[0:5], because of different types of encoding. (And I don't really want to pay attention ...
[ "If string is type str (not a Unicode string, type unicode), then it's a byte string and slicing will work as expected:\nprefixed_bits = \"extract this double:\\xc2\\x8eET\\xfb!\\t@\"\npos = prefixed_bits.index(\":\") + 1\nprint \"That looks like the value %f\" % struct.unpack(\"d\", prefixed_bits[pos:pos+8])\n\nTh...
[ 3 ]
[]
[]
[ "binary", "file", "python", "string" ]
stackoverflow_0005662592_binary_file_python_string.txt
Q: comparing lists with tuples in python I have a list containing two words list = ["the","end"] I have a list of tuples such as this bigramslist = [ ("the", "end"), ("end", "of"), ("of", "the"), ("the", "world") ] Is it possible to systematically go through each tuple in the bigramslist and see if both words in...
comparing lists with tuples in python
I have a list containing two words list = ["the","end"] I have a list of tuples such as this bigramslist = [ ("the", "end"), ("end", "of"), ("of", "the"), ("the", "world") ] Is it possible to systematically go through each tuple in the bigramslist and see if both words in the list match any of the tuples in the bi...
[ ">>> L1 = [\"the\",\"end\"]\n>>> bigramslist = [ (\"the\",\"end\"), (\"end\",\"of\"), (\"of\",\"the\"), (\"the\",\"world\") ]\n>>> tuple(L1) in bigramslist\nTrue\n\nedit for completeness:\n>>> bigramsset = set( [ (\"the\",\"end\"), (\"end\",\"of\"), (\"of\",\"the\"), (\"the\",\"world\") ] )\n>>> L1 = [\"the\",\"end...
[ 13, 0 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0005662758_list_python_tuples.txt
Q: python types in bencode.py Sorry for my simple question. I try to use bencode.py from deluge or bittorrent 5.0.8. But I find a string from types import StringType, IntType, LongType, DictType, ListType, TupleType but I do not know where this types is. What I need to install for use this types? A: Its part of th...
python types in bencode.py
Sorry for my simple question. I try to use bencode.py from deluge or bittorrent 5.0.8. But I find a string from types import StringType, IntType, LongType, DictType, ListType, TupleType but I do not know where this types is. What I need to install for use this types?
[ "Its part of the standard library. It should work right away.\n", "The module types is a standard Python module included in the Python distribution. You don't need to install anything in addition to Python itself.\nAs far as I remember, it has been around forever (which means at least since Python 1.5).\n" ]
[ 3, 2 ]
[]
[]
[ "bittorrent", "python", "types" ]
stackoverflow_0005663051_bittorrent_python_types.txt
Q: syncdb ignores imported models I have a project, structured like this: project/ __init__.py db/ models/ __init__.py article.py project.py ontology/ __init__.py coded.py It's a little bit bigger, but that's the idea. models.__init__.py contain...
syncdb ignores imported models
I have a project, structured like this: project/ __init__.py db/ models/ __init__.py article.py project.py ontology/ __init__.py coded.py It's a little bit bigger, but that's the idea. models.__init__.py contains: from db.models.article import * f...
[ "You need to add app_label = 'db' to your models' Meta inner classes.\n", "According to South (syncdb) docs: http://south.aeracode.org/docs/tutorial/part1.html It will create tables only for those models that are in INSTALLED_APPS section in settings.py file. If model is being used, but its changed and you don't ...
[ 4, 3, 0 ]
[]
[]
[ "django_models", "django_syncdb", "python" ]
stackoverflow_0005662313_django_models_django_syncdb_python.txt
Q: Why wont my Simple CGI Server handle AJAX Post requests? I have created my own CGI python server script (that serves on port 8000) by following a tutorial. The server works beautifully if I want to generate web pages from python scripts, or serve a native HTML page BUT it doesn't work for when I make an AJAX POST ...
Why wont my Simple CGI Server handle AJAX Post requests?
I have created my own CGI python server script (that serves on port 8000) by following a tutorial. The server works beautifully if I want to generate web pages from python scripts, or serve a native HTML page BUT it doesn't work for when I make an AJAX POST request? If I make an AJAX request to the python file aaa.py (...
[ "when you use the python http cgi server, cgi scripts have to be under the subdir (from you server script ) /cgi-bin \n" ]
[ 3 ]
[]
[]
[ "ajax", "cgi", "python" ]
stackoverflow_0005163118_ajax_cgi_python.txt
Q: Nullable ForeignKeys and deleting a referenced model instance I have a ForeignKey which can be null in my model to model a loose coupling between the models. It looks somewhat like that: class Message(models.Model): sender = models.ForeignKey(User, null=True, blank=True) sender_name = models.CharField(max_leng...
Nullable ForeignKeys and deleting a referenced model instance
I have a ForeignKey which can be null in my model to model a loose coupling between the models. It looks somewhat like that: class Message(models.Model): sender = models.ForeignKey(User, null=True, blank=True) sender_name = models.CharField(max_length=255) On save the senders name is written to the sender_name att...
[ "Django does indeed emulate SQL's ON DELETE CASCADE behaviour, and there's no out-of-the box documented way to change this. The docs where they mention this are near the end of this section: Deleting objects.\nYou are right that Django's collects all related model instances, then calls the pre-delete handler for ea...
[ 13, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0000681497_django_django_models_python.txt
Q: How to include the first few items of a numpy array with python I have array d, I want array d2 The rows do not have the same number of items. d= [ ['q', 'u', 's', 'a', 'p', 'e', 'a'] ['500', 'G', 'G', 'C', 'C', 'P', '04/12/2011', '' ] ['500', 'G', 'G', 'F', 'C', 'P', '04/12/2011', ''] ['5', '...
How to include the first few items of a numpy array with python
I have array d, I want array d2 The rows do not have the same number of items. d= [ ['q', 'u', 's', 'a', 'p', 'e', 'a'] ['500', 'G', 'G', 'C', 'C', 'P', '04/12/2011', '' ] ['500', 'G', 'G', 'F', 'C', 'P', '04/12/2011', ''] ['5', 'ZUMZ', 'ZUMZ', 'C', 'C', 'B', '04/12/2011', ''] ['2', 'ZUMZ', 'Z...
[ "How about:\nm = np.array([x[:5] for x in d], dtype=object)\n\nAlthough if they are all strings, you should use a string dtype instead.\n" ]
[ 1 ]
[]
[]
[ "numpy", "python", "row" ]
stackoverflow_0005663262_numpy_python_row.txt
Q: How to enable reCAPTCHA I try enable reCAPTCHA with the tag {{capture}} The expected output is the reCAPTCHA box. Instead I see this code displayed directly like code on the page looking like a bug: <script type="text/javascript" src="http://api.recaptcha.net/ challenge?k=6LckUsMSAAAAAGcZR3JZw6Dusn4wKBBfZxHXh8w5"...
How to enable reCAPTCHA
I try enable reCAPTCHA with the tag {{capture}} The expected output is the reCAPTCHA box. Instead I see this code displayed directly like code on the page looking like a bug: <script type="text/javascript" src="http://api.recaptcha.net/ challenge?k=6LckUsMSAAAAAGcZR3JZw6Dusn4wKBBfZxHXh8w5"></script> <noscript> <iframe...
[ "You're a victim of Django's autoescaping.\nTry {{capture|safe}}.\n", "The Django templating system defaults to automatically performing HTML escaping to prevent things like cross-site scripting attacks -- that's what's turning all of your html <tag>s into &lt;tag &gt; \nTo prevent this, you can invoke the safe f...
[ 5, 3 ]
[]
[]
[ "google_app_engine", "python", "recaptcha" ]
stackoverflow_0005662549_google_app_engine_python_recaptcha.txt
Q: How can I use a Python cgi script to kill the browser that launched it? I'm doing this in MacOs 10.4. My web page posts some data to a Python script, and I would like the script to finish off by shutting down the browser. I am trying to do this calling os.system("kill 210") # where 210, say, is the browser's id ...
How can I use a Python cgi script to kill the browser that launched it?
I'm doing this in MacOs 10.4. My web page posts some data to a Python script, and I would like the script to finish off by shutting down the browser. I am trying to do this calling os.system("kill 210") # where 210, say, is the browser's id number but this doesn't work. In the Apache error log I see the message: kil...
[ "How are you starting your web browser?\nYou should have a second script that would start the web browser, allow you to paste data -\nor automate the whole process, for that you could use \"selenium\" if you want and this script would have no issues with closing the browser.\n" ]
[ 1 ]
[]
[]
[ "apache", "cross_browser", "macos", "python" ]
stackoverflow_0005661370_apache_cross_browser_macos_python.txt
Q: laptop's power state on ubuntu How can I find out the power state(whether it's plugged to a power source, or not) of a laptop running on Ubuntu? I need to use that info. to trigger a python script, so I want to know if there is a way to do this using Python? A: On a sufficiently modern Ubuntu you might want to ...
laptop's power state on ubuntu
How can I find out the power state(whether it's plugged to a power source, or not) of a laptop running on Ubuntu? I need to use that info. to trigger a python script, so I want to know if there is a way to do this using Python?
[ "On a sufficiently modern Ubuntu you might want to use DBus (via its Python binding) to query the DeviceKit daemon.\nUpdate: actually, on modern Ubuntu installations DeviceKit-power is replace by UPower (but that's got its own, very similar DBus interface).\n", "Ubuntu has support for the acpi protocol. By using ...
[ 2, 0 ]
[]
[]
[ "python", "ubuntu" ]
stackoverflow_0005663506_python_ubuntu.txt
Q: PyCUDA / Copperhead doesn't appear to recognise 64-bit machines Two problems I'm having with copperhead at the minute, which I suspect are related. Running a sample file (samples/axpy.py) generated lots of little warnings, but this one stood out. g++ -pthread -fno-strict-aliasing -g -O2 -g -fwrapv -O2 -Wall -fPIC...
PyCUDA / Copperhead doesn't appear to recognise 64-bit machines
Two problems I'm having with copperhead at the minute, which I suspect are related. Running a sample file (samples/axpy.py) generated lots of little warnings, but this one stood out. g++ -pthread -fno-strict-aliasing -g -O2 -g -fwrapv -O2 -Wall -fPIC -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Xlinker -export-d...
[ "\nIt is finding libcudart. What you\nare seeing is only an informational\nwarning: -L options are\nsearched in order and the linker is\nfinding the 32 bit version first,\nbecause you gave\n-L/usr/local/cuda/lib before -L/usr/loca/cuda/lib64.\nFor the libboost_python problem,\njust link with -lboost_python. The\nUb...
[ 3 ]
[]
[]
[ "boost", "boost_python", "cuda", "pycuda", "python" ]
stackoverflow_0005662843_boost_boost_python_cuda_pycuda_python.txt
Q: Regex and grep exception matching I tested my regex for matching exceptions in a log file : http://gskinner.com/RegExr/ Regex is : .+Exception[^\n]+(\s+at.++)+ And it works for couple of cases I pasted here, but not when I'm using it with grep : grep '.+Exception[^\n]+(\s+at.++)+' server.log Does grep needs som...
Regex and grep exception matching
I tested my regex for matching exceptions in a log file : http://gskinner.com/RegExr/ Regex is : .+Exception[^\n]+(\s+at.++)+ And it works for couple of cases I pasted here, but not when I'm using it with grep : grep '.+Exception[^\n]+(\s+at.++)+' server.log Does grep needs some extra flags to make it work wit regex...
[ "Not all versions of grep understand the same syntax. \n\nYour pattern contains a + for 1 or more repeats, which means it is in egrep territory. \nBut it also has \\s for white space, which most versions of grep are ignorant of. \nFinally, you have ++ to mean a possessive match of the preceding atom, which only fai...
[ 2, 1, 0 ]
[]
[]
[ "grep", "linux", "perl", "python", "regex" ]
stackoverflow_0005662042_grep_linux_perl_python_regex.txt
Q: Object type casting in Python (design suggestion) Let's say there is a library function called get_pack() which returns a Pack object: class Pack(object): def __init__(self, name, weight): self.name = name self.weight = weight ... What I want to do is to wrap this object into my object...
Object type casting in Python (design suggestion)
Let's say there is a library function called get_pack() which returns a Pack object: class Pack(object): def __init__(self, name, weight): self.name = name self.weight = weight ... What I want to do is to wrap this object into my object which is let's say CommercialPack which has a couple o...
[ "Will this work for you?\n#!/usr/bin/python\nPER_KM_PRICE = 10\n\nclass Pack(object):\n def __init__(self, name, weight):\n self.name = name\n self.weight = weight\n\n def test_fn(self):\n print \"test\"\n\nclass CommercialPack(Pack):\n def __init__(self, pack):\n self.pack = pa...
[ 4, 1, 1 ]
[]
[]
[ "casting", "oop", "python" ]
stackoverflow_0005663630_casting_oop_python.txt
Q: sdist error: option --manifest-only not recognized Everytime I use sdist to creat the MANIFEST file with the command: 'python setup.py sdist --manifest-only' The terminal always outputs this error msg. error: option --manifest-only not recognized I don't know why and am looking for help. A: I guess you use ...
sdist error: option --manifest-only not recognized
Everytime I use sdist to creat the MANIFEST file with the command: 'python setup.py sdist --manifest-only' The terminal always outputs this error msg. error: option --manifest-only not recognized I don't know why and am looking for help.
[ "I guess you use\nfrom setuptools import setup\n\nin you setup.py ? Setuptools seems not to support this option. I prefer to stick to the standard Python way and use:\nfrom distutils.core import setup\n\n" ]
[ 7 ]
[]
[]
[ "python", "sdist" ]
stackoverflow_0005651806_python_sdist.txt
Q: Model IndexError after checking count() Here's my code: qs = MyModel.objects.filter(blah = blah) if qs.count() > 0: a = qs[0].value File "/home/libs/django/db/models/query.py", line 189, in __getitem__ return list(qs)[0] IndexError: list index out of range Is there any possibilty to cause thi...
Model IndexError after checking count()
Here's my code: qs = MyModel.objects.filter(blah = blah) if qs.count() > 0: a = qs[0].value File "/home/libs/django/db/models/query.py", line 189, in __getitem__ return list(qs)[0] IndexError: list index out of range Is there any possibilty to cause this error, other than the record being deleted ...
[ "Your code is not considering the possibility that no records are returned by the filter. Even though you use the qs.count() conditional, your return value assumes objects were returned. Perhaps you might consider a function:\ndef myquery():\n qs = MyModel.objects.filter(blah = blah)\n try:\n return q...
[ 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0005663345_django_django_models_python.txt
Q: How to populate xml file using xpath in Python I have an xpath for a node in an xml file which does not yet exist, and want to use it to generate the node in question. I've started work on a function to do this but was wondering if there's an existing library which can do it and save me some time? I'm currently ...
How to populate xml file using xpath in Python
I have an xpath for a node in an xml file which does not yet exist, and want to use it to generate the node in question. I've started work on a function to do this but was wondering if there's an existing library which can do it and save me some time? I'm currently working with pyxml but am considering porting it to ...
[ "Didn't find anything ready, \nbut it should be more or less straightforward using ElementTree (or even another xml library - it is just that I am more acquainted with ElementTree).\nThe snippet bellow seems to work for the limited subset of xpath that is needed for it:\n# -*- coding: utf-8 -*-\nfrom xml.etree impo...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0005661968_python.txt
Q: Creating a real time website using PHP I'm currently creating a website using PHP and the Kohana framework. I want to site to be able to use real time (or near real time) data (e.g. for chat and real time feeds). I need it to be able to scale to thousands of concurrent users. I've done a lot of reading and stil...
Creating a real time website using PHP
I'm currently creating a website using PHP and the Kohana framework. I want to site to be able to use real time (or near real time) data (e.g. for chat and real time feeds). I need it to be able to scale to thousands of concurrent users. I've done a lot of reading and still have no idea what the best method is for t...
[ "\nI've looked at node js and nowjs, but\n I'm weary about coding a while site in\n Express (I wonder about security\n holes, code maintainability, lack of a\n good ORM).\n\nI can personally vouch for code maintainability if you can do JavaScript. I personally find JavaScript more maintainable then PHP but that...
[ 2, 0 ]
[]
[]
[ "node.js", "php", "python", "real_time" ]
stackoverflow_0005664225_node.js_php_python_real_time.txt
Q: MySQLdb, Python raw query and customized ORDER BY I am trying to do the following : query = "SELECT * FROM table ORDER BY %s %s" parameters = ['avg', 'DESC'] But the parameters are not mapped correctly. SELECT * FROM table ORDER BY 'avg' 'DESC' Instead of SELECT * FROM table ORDER BY avg DESC Do you know why ?...
MySQLdb, Python raw query and customized ORDER BY
I am trying to do the following : query = "SELECT * FROM table ORDER BY %s %s" parameters = ['avg', 'DESC'] But the parameters are not mapped correctly. SELECT * FROM table ORDER BY 'avg' 'DESC' Instead of SELECT * FROM table ORDER BY avg DESC Do you know why ?
[ "You can't use parameters to dynamically specify field names. They specify values only.\n", "Using this: \n\"SELECT * FROM table ORDER BY %s %s\" % ('avg', 'DESC')\n\nshould do the trick.\n" ]
[ 1, 1 ]
[]
[]
[ "mysql_python", "python" ]
stackoverflow_0005664310_mysql_python_python.txt
Q: List comprehension (python)and array comprehension (php)? >>> lst = ['dingo', 'wombat', 'wallaby'] >>> [w.title() for w in lst] ['Dingo', 'Wombat', 'Wallaby'] >>> In python there is simple ways to todo with list comprehension. What about in php with array('dingo', 'wombat', 'wallaby'); ? Are there array comprehe...
List comprehension (python)and array comprehension (php)?
>>> lst = ['dingo', 'wombat', 'wallaby'] >>> [w.title() for w in lst] ['Dingo', 'Wombat', 'Wallaby'] >>> In python there is simple ways to todo with list comprehension. What about in php with array('dingo', 'wombat', 'wallaby'); ? Are there array comprehension or any build in function ,or normally loop on it? EDIT f...
[ "You can use array_map() with anonymous functions (closures are PHP 5.3+ only).\n$arr = array_map(function($el) { return $el[0]; }, array('dingo', 'wombat', 'wallaby'));\nprint_r($arr);\n\nOutput\nArray\n(\n [0] => d\n [1] => w\n [2] => w\n)\n\nEdit: OP's sample code\n$arr = array_map('ucwords', array('din...
[ 10, 2, 2 ]
[]
[]
[ "arraylist", "arrays", "php", "python" ]
stackoverflow_0005664484_arraylist_arrays_php_python.txt
Q: Enabling KMZ output with gzip When I try enable gzip for an output the following error appears: Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 634, in __call__ handler.get(*groups) File "/base/data/home/apps/my-app-ip/djang...
Enabling KMZ output with gzip
When I try enable gzip for an output the following error appears: Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 634, in __call__ handler.get(*groups) File "/base/data/home/apps/my-app-ip/django2.349712625627523096/main.py", lin...
[ "It looks like you need to set encoding to utf-8. See this question.\n" ]
[ 1 ]
[]
[]
[ "character_encoding", "google_app_engine", "kmz", "python", "unicode" ]
stackoverflow_0005664414_character_encoding_google_app_engine_kmz_python_unicode.txt
Q: how to raise this exception from shodan import WebAPI SHODAN_API_KEY = "MY API KEY" api = WebAPI(SHODAN_API_KEY) host = api.host('98.111.2.190') # Print general info try: print """ IP: %s Country: %s City: %s """ % (host['ip'], host.get('country', None), host.g...
how to raise this exception
from shodan import WebAPI SHODAN_API_KEY = "MY API KEY" api = WebAPI(SHODAN_API_KEY) host = api.host('98.111.2.190') # Print general info try: print """ IP: %s Country: %s City: %s """ % (host['ip'], host.get('country', None), host.get('city', None)) except WebAPIEr...
[ "You should firstly import the Exception from the package:\nfrom shodan.api import WebAPIError\n\nThen, when you catch the error you can re-raise it with your message:\ntry:\n # Here your code\nexcept WebAPIError as e:\n e.args = ('My new message',) # Remember the comma! It is a tuple\n raise # Re-raise th...
[ 2 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0005664455_python_sockets.txt
Q: With Python unittest, how do I create and use a "callable object that returns a test suite"? I'm learning Python and have been trying to understand more about the details of Python's unittest module. The documentation includes the following: For the ease of running tests, as we will see later, it is a good idea...
With Python unittest, how do I create and use a "callable object that returns a test suite"?
I'm learning Python and have been trying to understand more about the details of Python's unittest module. The documentation includes the following: For the ease of running tests, as we will see later, it is a good idea to provide in each test module a callable object that returns a pre-built test suite: def s...
[ "The very first error message you got is meaningful, and explains a lot.\nprint MyTestCase.suite # <unbound method MyTestCase.suite>\n\nUnbound. It means that you cannot call it unless you bind it to an instance. It's actually the same for MyTestCase.run:\nprint MyTestCase.run # <unbound method MyTestCase.run>\n\nM...
[ 6, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001053983_python.txt
Q: Custom Django Storage I have a web page where people can upload their own images and I want to store them in a salable storage. I was willing to use Amazon S3, but later I decided to use my own file servers with web servers for serving static content (images) But I'm not sure how to do this. What is the correct wa...
Custom Django Storage
I have a web page where people can upload their own images and I want to store them in a salable storage. I was willing to use Amazon S3, but later I decided to use my own file servers with web servers for serving static content (images) But I'm not sure how to do this. What is the correct way to do it and what custom ...
[ "Here's a start: Writing a custom storage system.\n" ]
[ 2 ]
[]
[]
[ "amazon_s3", "django", "django_storage", "python", "storage" ]
stackoverflow_0005665101_amazon_s3_django_django_storage_python_storage.txt