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: Python : Login to facebook to get user id... How to do it without a browser with python? I just want to get the user id of the user... (15 digit user id of facebook users) I am using this in a mobile application and want to avoid the web browser.. So.. can you suggest some sample code ? A: Use the graph API, do ...
Python : Login to facebook to get user id... How to do it without a browser with python?
I just want to get the user id of the user... (15 digit user id of facebook users) I am using this in a mobile application and want to avoid the web browser.. So.. can you suggest some sample code ?
[ "Use the graph API, do a GET request on https://graph.facebook.com/<username>\nThe returning JSON data will have the user id.\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0005928959_python.txt
Q: Some problem with dict function I'm trying to convert a list to a dictionary by using the dict function. inpu = input.split(",") dic = dict(inpu) The above code is trying to get a string and split it on ',' and afterwards I use the dict function to convert the list to a dictionary. However, I get this error: Va...
Some problem with dict function
I'm trying to convert a list to a dictionary by using the dict function. inpu = input.split(",") dic = dict(inpu) The above code is trying to get a string and split it on ',' and afterwards I use the dict function to convert the list to a dictionary. However, I get this error: ValueError: dictionary update sequence ...
[ "dict expects an iterable of 2-element containers (like a list of tuples). You can't just pass a list of items, it doesn't know what's a key and what's a value.\nYou are trying to do this:\n>>> range(10)\n<<< [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> dict(range(10))\n------------------------------------------------------...
[ 21, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005929397_python.txt
Q: Calling Python functions from inline C with scipy.weave Can I call a python function from inline C code (using weave)? Motivation: I have a bit of code that I'd like to optimize, and I've identified the bottleneck in one function. After my usual tricks, I usually turn to scipy.weave.inline for optimization. Unfort...
Calling Python functions from inline C with scipy.weave
Can I call a python function from inline C code (using weave)? Motivation: I have a bit of code that I'd like to optimize, and I've identified the bottleneck in one function. After my usual tricks, I usually turn to scipy.weave.inline for optimization. Unfortunately, in this case, my function is calling another python ...
[ "It's a little involved, as Weave doesn't have a way to automatically marshall the arguments and return value. You need to do a little more work:\ndef bar_weave():\n code = \"\"\"\n int a = 0;\n for (int i=0;i<10;++i){\n py::tuple arg(1);\n arg[0] = i;\n a += (int) foo.call(arg);\n ...
[ 11 ]
[]
[]
[ "inline", "performance", "python", "scipy" ]
stackoverflow_0005929600_inline_performance_python_scipy.txt
Q: Trying to log into an authenticated website I am trying to log into a web page and access an authenticated page. It isn't working. from __future__ import division from __future__ import unicode_literals from __future__ import print_function import re import mechanize br = mechanize.Browser() br.open("https://www.t...
Trying to log into an authenticated website
I am trying to log into a web page and access an authenticated page. It isn't working. from __future__ import division from __future__ import unicode_literals from __future__ import print_function import re import mechanize br = mechanize.Browser() br.open("https://www.thomsononeim.com/s-log_in.asp") br.select_form(nam...
[ "You can use urllib and submit post parameters.\nEx:\nimport urllib.parse as urlparse\nimport urllib.request as urlreq\n\nparams = urlparse.urlencode({'txtLoginId':'Username', 'txtPWD':'Password'})\n\nreq = urlreq.urlopen(\"http://www.your-site.com/login.php\", params)\npage = str(req.read())\n\npage is now a strin...
[ 0 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0005929738_mechanize_python.txt
Q: Why do `prev = poss[0]` and `prev = 0` behave differently? I have a question about this code: poss = [6,9,20] for n in range(6,66): if(n%6) == 0 or (n%9) == 0 or (n%20) == 0: poss.append(n) poss.sort() count = 0 prev = poss[0] for p in poss: print p if prev == p: del poss[count] ...
Why do `prev = poss[0]` and `prev = 0` behave differently?
I have a question about this code: poss = [6,9,20] for n in range(6,66): if(n%6) == 0 or (n%9) == 0 or (n%20) == 0: poss.append(n) poss.sort() count = 0 prev = poss[0] for p in poss: print p if prev == p: del poss[count] count += 1 prev = p print poss The 2nd for loop is int...
[ "I'm pretty sure that your second loop does not remove duplicates. I'm really not sure what it will do since you are modifying the list that you are iterating over and skipping values every time that you delete. I recommend using any of the following:\n# this is the same list w/o duplicates, this can replace the ...
[ 4, 3, 0 ]
[ "You also can use a dictionnary to remove duplicates (More info):\nposs = list({p:None for p in poss}.keys()) # for python 3.x\n\nor\nposs = list({}.fromkeys(poss).keys())\n\nBut you will need to sort again the list (So sort it only one time, after removing duplicates).\nposs[0] is 6 in your example, so prev = 0 is...
[ -2 ]
[ "python" ]
stackoverflow_0005929814_python.txt
Q: SOAPpy returning an XML string. How do I get the library to parse the xml for me? I am using SOAPpy, and Dive Into Python http://diveintopython3.ep.io/http-web-services.html says it should be returning a dictionary. I am making a simple request, that returns an xml response that has the escape characters. WSDLFILE...
SOAPpy returning an XML string. How do I get the library to parse the xml for me?
I am using SOAPpy, and Dive Into Python http://diveintopython3.ep.io/http-web-services.html says it should be returning a dictionary. I am making a simple request, that returns an xml response that has the escape characters. WSDLFILE = 'path/to/my/wsdl' _server = WSDL.Proxy(WSDLFILE) print _server.validServerMethod(cli...
[ "I think you need to unescape it : http://wiki.python.org/moin/EscapingHtml\n" ]
[ 0 ]
[]
[]
[ "python", "soap", "soappy" ]
stackoverflow_0005929230_python_soap_soappy.txt
Q: IOS smallSocket and python I'm working on an IOS app. I'm starting with a python server on mac that should connect to an iphone and print data sent from iphone. the connection seems to be established but python print infinite " b " " as data... I don't know why. the strange thing is that it happens also with cocoa...
IOS smallSocket and python
I'm working on an IOS app. I'm starting with a python server on mac that should connect to an iphone and print data sent from iphone. the connection seems to be established but python print infinite " b " " as data... I don't know why. the strange thing is that it happens also with cocoaAsynchronousSocket this is the s...
[ "Why did u add this line:\n\ndata = sock.recv(0)\n\nBesides that, your sever, while client might be a better name, seems good.\nIf it doesn't print what you expect, I suggest that you use some sniffer tools, like wireshark, to check what it really receives.\n" ]
[ 0 ]
[]
[]
[ "ios", "python", "sockets" ]
stackoverflow_0005926376_ios_python_sockets.txt
Q: Are there any all in one packages like XAMPP for Django? Like with XAMPP you can just install it and start developing because PHP/MySQL/Apache, etc. are all in there. Is there anything like this for Django? P.S. I meant just for developing on my local machine not for deployment. A: The closest thing I've seen i...
Are there any all in one packages like XAMPP for Django?
Like with XAMPP you can just install it and start developing because PHP/MySQL/Apache, etc. are all in there. Is there anything like this for Django? P.S. I meant just for developing on my local machine not for deployment.
[ "The closest thing I've seen is Bitnami's DjangoStack. There is arguably little need for a comparable XAMPP stack to get started with Django development, as the only thing you need to get started with Django is Python 2.x. Most linux distros and OSX include Python 2.x. The easiest way to install Django is to use ea...
[ 3, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005929696_django_python.txt
Q: Type error with model method I am trying to add a shortcut method to simplify output of a my data. I have written the following code (unnecessary bits redacted): address_line_one = models.CharField(max_length=100) address_line_two = models.CharField(max_length=100, blank=True) address_city = models.CharField(max_l...
Type error with model method
I am trying to add a shortcut method to simplify output of a my data. I have written the following code (unnecessary bits redacted): address_line_one = models.CharField(max_length=100) address_line_two = models.CharField(max_length=100, blank=True) address_city = models.CharField(max_length=50) address_state = models.C...
[ "Python is strongly typed. That means you can't concatenate an int to a string, without explicitly converting it.\nLuckily, there's a couple of shortcuts that will do the conversions, as well as making your code easier to read. \nFirstly, any time you find yourself concatenating variables to string literals, you sh...
[ 1, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0005929959_django_django_models_python.txt
Q: Delete / Insert Data in mmap'ed File I am working on a script in Python that maps a file for processing using mmap(). The tasks requires me to change the file's contents by Replacing data Adding data into the file at an offset Removing data from within the file (not whiting it out) Replacing data works great as ...
Delete / Insert Data in mmap'ed File
I am working on a script in Python that maps a file for processing using mmap(). The tasks requires me to change the file's contents by Replacing data Adding data into the file at an offset Removing data from within the file (not whiting it out) Replacing data works great as long as the old data and the new data have...
[ "In lack of an alternative, I went ahead and wrote two helper functions - deleteFromMmap() and insertIntoMmap() - to handle the low level file actions and ease the development.\nThe closing and reopening of the mmap instead of using resize() is do to a bug in python on unix derivates leading resize() to fail. (http...
[ 9, 2 ]
[]
[]
[ "insert", "mmap", "python" ]
stackoverflow_0005917047_insert_mmap_python.txt
Q: Python: fill in missing months with zero I have a list of dictionaries as shown below. Each dictionary holds the total for a particular month. If a month doesn't appear in the list, for example January, it's total should be zero. q = [{'total_item': 3, 'month': u'02'}, {'total_item': 1, 'month': u'03'}, {'total_i...
Python: fill in missing months with zero
I have a list of dictionaries as shown below. Each dictionary holds the total for a particular month. If a month doesn't appear in the list, for example January, it's total should be zero. q = [{'total_item': 3, 'month': u'02'}, {'total_item': 1, 'month': u'03'}, {'total_item': 1, 'month': u'05'}, {'total_item': 5, 'm...
[ "Just loop over the list, and assign according to the value of month.\ntotal_items = [0]*12\nfor d in q:\n month = int(d['month'], 10)\n total_items[month-1] = d['total_item']\n\n", "result = [0]*12\nfor r in q:\n result[int(r['month'])-1] = r['total_item']\n\n", "Use this:\nclass MyDict(dict):\n def __...
[ 3, 2, 1, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005929503_python.txt
Q: What are the pitfalls and workarounds when using Python virtual environments on Windows? Short Description The question is not meant to ask if using virtual environments are needed, but when using Ian Bicking's virtualenv what is the best way, if any, to manage environments in Windows. If you have multiple ideas...
What are the pitfalls and workarounds when using Python virtual environments on Windows?
Short Description The question is not meant to ask if using virtual environments are needed, but when using Ian Bicking's virtualenv what is the best way, if any, to manage environments in Windows. If you have multiple ideas, please answer multiple times so the best answers can be voted up. Thanks! Background When ...
[ "You might want to take a look at zc.buildout. Assuming the user has Python installed, you can double click on the bootstrap.py python script to generate the environment. \nOnce created, doubleclicking on bin\\buildout.exe will recursively install dependencies and run any pre/post hook methods you define. zc.buildo...
[ 2 ]
[]
[]
[ "python", "virtualenv", "windows" ]
stackoverflow_0005887018_python_virtualenv_windows.txt
Q: ANTLR get and split lexer content first, sorry about my english, i still learning. I writing Python module for my framework, which parsing CSS files. I try regex, ply (python lexer and parser), but i found myself in ANTLR. First try, i need to parse comments from CSS file. This is my CSS string to parse: /*test*/...
ANTLR get and split lexer content
first, sorry about my english, i still learning. I writing Python module for my framework, which parsing CSS files. I try regex, ply (python lexer and parser), but i found myself in ANTLR. First try, i need to parse comments from CSS file. This is my CSS string to parse: /*test*/ /* test1 /* /*test2/*nested*/comment...
[ "No, there is no easy way. Since NESTED_ML_COMMENT is a lexer rule (a \"simple\" token), you cannot let a parser rule create any more structure in source like /*test2/*nested*/comment*/: lexer rules will always stay a \"flat\" sequence of characters. Sure, there are (easy) ways to rewrite this character sequence (i...
[ 2, 0 ]
[]
[]
[ "antlr", "python" ]
stackoverflow_0005929797_antlr_python.txt
Q: Send bulk emails in Django with the same attachment I want to send emails to members of my site who are to attend a meeting (ie. guests), each with (the same) PDF attachment. I'm doing this with Django's built-in bulk email functionality, in connection.send_messages(messages). At the moment I'm doing this: guests ...
Send bulk emails in Django with the same attachment
I want to send emails to members of my site who are to attend a meeting (ie. guests), each with (the same) PDF attachment. I'm doing this with Django's built-in bulk email functionality, in connection.send_messages(messages). At the moment I'm doing this: guests = Guest.objects.all() connection = mail.get_connection() ...
[ "Looking at django/core/mail/message.py reveals attach_file is merely a convenience function that opens the file for you before calling attach:\ndef attach_file(self, path, mimetype=None):\n \"\"\"Attaches a file from the filesystem.\"\"\"\n filename = os.path.basename(path)\n content = open(path, 'rb').re...
[ 0 ]
[]
[]
[ "bulk_email", "django", "email", "python" ]
stackoverflow_0005930339_bulk_email_django_email_python.txt
Q: Json vs. SQL Recommendations I don't have that much programming experience beyond python and I am starting a project that is going to store info by a city/country, date, and then time. I have used simplejson before and find it incredibly useful, especially because how easy it is to sort through the json data with...
Json vs. SQL Recommendations
I don't have that much programming experience beyond python and I am starting a project that is going to store info by a city/country, date, and then time. I have used simplejson before and find it incredibly useful, especially because how easy it is to sort through the json data with python. If I used json I would ...
[ "JSON is for exchanging smallish amounts of data between processes on the same machine or over the web. You need a database.\nIf you use JSON, you need to read the whole structure into memory before you can query it or update it. You need to write the whole lot back to disk after each update (or risk losing data wh...
[ 4 ]
[]
[]
[ "json", "python", "sql" ]
stackoverflow_0005928921_json_python_sql.txt
Q: Reading input into dynamically-sized array What I've been trying to do, is read a line from stdin and split it, by using whitespace as seperators. Let's say I have this as input: 2 1 2 3 4 The first line gives me the amount of lines I'd like to read, they're all lines with integers seperated by an unknown am...
Reading input into dynamically-sized array
What I've been trying to do, is read a line from stdin and split it, by using whitespace as seperators. Let's say I have this as input: 2 1 2 3 4 The first line gives me the amount of lines I'd like to read, they're all lines with integers seperated by an unknown amount of whitespace (i.e. could be 1 space, but i...
[ "so given all you wanted is a nudge, here are a couple of hints..\nstd::getline() - allows you to read from a stream into a std::string. \nYou can then construct a std::istringstream using this string which you've just read in. Then use this stream to read your ints\nfor example:\nstd::string line;\nif(std::getline...
[ 1, 1 ]
[]
[]
[ "c++", "io", "python" ]
stackoverflow_0005930464_c++_io_python.txt
Q: Error Importing wxPython I've just installed wxPython with no problems. I'm on a Snow Leopard Mac using Python 2.6 and downloaded the corresponding wxPython version. I've started by typing a very basic wxPython app, but I'm getting the following error: ImportError: No module named wx The code is the following: i...
Error Importing wxPython
I've just installed wxPython with no problems. I'm on a Snow Leopard Mac using Python 2.6 and downloaded the corresponding wxPython version. I've started by typing a very basic wxPython app, but I'm getting the following error: ImportError: No module named wx The code is the following: import wx class Application(wx...
[ "You can't use wxPython in 64-bit mode. First, force Python to use the 32-bit binary:\ndefaults write com.apple.versioner.python Prefer-32-Bit -bool yes\n\nThen you can use the builtin Python and the builtin wxPython.\n", "Ok, the problem was I was running python 2.5.\nTo all MacOSX users who get stuck trying to ...
[ 1, 1, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0005923651_python_wxpython.txt
Q: System side programming - Which language? I have few questions over System side programming. Can Python be used for both Web and System like perl. Which language would you prefer me. I have a little knowledge on JavaScript and Java. If i want to develop a compiler what should i know and where should i start. ...
System side programming - Which language?
I have few questions over System side programming. Can Python be used for both Web and System like perl. Which language would you prefer me. I have a little knowledge on JavaScript and Java. If i want to develop a compiler what should i know and where should i start.
[ "\nYes.\nUse a language that the people around you use.\nYou should know about lexing, parsing, symbol tables, abstract syntax trees, optimisation, intermediate languages, stack-based and register-based architectures, code generation, object file formats, linkers, loaders, etc. There are many resources available in...
[ 3, 2, 1 ]
[]
[]
[ "java", "programming_languages", "python" ]
stackoverflow_0005930669_java_programming_languages_python.txt
Q: UnicodeDecodeError when saving non ascii character to mongo db Using mongoengine with mongodb when saving document which has value with non ascii character got UnicodeDecodeError (mongoengine wraps values with unicode() call) what's the way to deal with it? A: If you are calling unicode() you should provide the ...
UnicodeDecodeError when saving non ascii character to mongo db
Using mongoengine with mongodb when saving document which has value with non ascii character got UnicodeDecodeError (mongoengine wraps values with unicode() call) what's the way to deal with it?
[ "If you are calling unicode() you should provide the encoding your string is encoded in, so that the unicode() function knows how to convert the data. For example:\nv = \"myvalüe\"\nu = unicode(v, 'utf-8')\n\n" ]
[ 0 ]
[]
[]
[ "mongodb", "mongoengine", "python", "unicode" ]
stackoverflow_0005930272_mongodb_mongoengine_python_unicode.txt
Q: Am I just abusing Python's import system or is this okay? I'm building a web application with Twisted, and for the site resources I have a structure like this: /resources __init__.py file.py javascript.py images.py wsdl.py /pages __init__.py page.py static.py login.py ...etc...
Am I just abusing Python's import system or is this okay?
I'm building a web application with Twisted, and for the site resources I have a structure like this: /resources __init__.py file.py javascript.py images.py wsdl.py /pages __init__.py page.py static.py login.py ...etc... where file.py and page.py contain parent classes with comm...
[ "I agree with Ignacio. I'd also point out that doing an import and then assignment like you do:\nimport javascript\nJavascript = javascript.Javascript\n\n...makes Javascript available as both resources.javascript.Javascript and resources.Javascript. Is that intended? I always find that annoying when I'm introspecti...
[ 3, 2, 1 ]
[]
[]
[ "import", "python", "twisted" ]
stackoverflow_0005930558_import_python_twisted.txt
Q: How to modify an atom/rss feed in python? Here is what I want to do in python: take a feed add data to the feed re-publish the thus modified feed Feedparser does a good job at parsing, but it doesn't seem to provide a way to compose an XML document from a FeedParserDict object. Is there a simpler alternative to ...
How to modify an atom/rss feed in python?
Here is what I want to do in python: take a feed add data to the feed re-publish the thus modified feed Feedparser does a good job at parsing, but it doesn't seem to provide a way to compose an XML document from a FeedParserDict object. Is there a simpler alternative to writing my own composing function?
[ "I wrote my own Atom 1.0 serializer, using the Django templating engine. I went the extra mile of making it as complete as possible, so that it could be re-used by other people:\nimport feedparser\nfrom django.template import Template\nd = feedparser.parse(\"http://example.com/feed.xml\") # creating a FeedParserDic...
[ 2, 0 ]
[]
[]
[ "feedparser", "python" ]
stackoverflow_0005916486_feedparser_python.txt
Q: How to use CustomUser model and OpenID together in Django for authentication? I'm learning Python Django framework. Thanks to StackOverFlow Community, i have learned how to use open-id in django (social_auth i'm using ). with social_auth, sign in and sign out process are pretty easy and practical. But i want to b...
How to use CustomUser model and OpenID together in Django for authentication?
I'm learning Python Django framework. Thanks to StackOverFlow Community, i have learned how to use open-id in django (social_auth i'm using ). with social_auth, sign in and sign out process are pretty easy and practical. But i want to build friendship relationship between users, for this i created new model class wh...
[ "The way to extend the User class in Django is to provide user profile class. See here. You can then just use the User model as always and get the profile instance on demand.\n" ]
[ 2 ]
[]
[]
[ "django", "django_models", "openid", "python" ]
stackoverflow_0005929745_django_django_models_openid_python.txt
Q: Problems with installing ssl package in python 2.5 I noticed I have this warning: WARNING 2011-05-07 00:50:51,371 urlfetch_stub.py:106] No ssl package found. urlfetch will not be able to validate SSL certificates. So I downloaded the ssl 1.15 library. Tried to install using setup.py and got this: error: package d...
Problems with installing ssl package in python 2.5
I noticed I have this warning: WARNING 2011-05-07 00:50:51,371 urlfetch_stub.py:106] No ssl package found. urlfetch will not be able to validate SSL certificates. So I downloaded the ssl 1.15 library. Tried to install using setup.py and got this: error: package directory 'ssl' does not exist Update: I added python to ...
[ "After trying python 26 on my computer, the only conclusion is that I'm experiencing this bug: \nhttp://code.google.com/p/googleappengine/issues/detail?id=4824&q=ssl&colspec=ID%20Type%20Component%20Status%20Stars%20Summary%20Language%20Priority%20Owner%20Log\n(because python 26 is supposed to have ssl built in)\nOh...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "python", "ssl" ]
stackoverflow_0005918633_google_app_engine_python_ssl.txt
Q: creating a function to allow for a header row and row names column I'm defining a function that will return a list of lists where element zero is the 2Darray, element one is the header information, and element 2 is the rowname. How can I read this in from a file where the file looks like this: genes S1 S2 S3 ...
creating a function to allow for a header row and row names column
I'm defining a function that will return a list of lists where element zero is the 2Darray, element one is the header information, and element 2 is the rowname. How can I read this in from a file where the file looks like this: genes S1 S2 S3 S4 S5 100 -0.243 -0.021 -0.205 -1.283 0.411 10000 -1.178 -0.79 ...
[ "def input2DarrayData(fn):\n # define twoDarray, headerLine and rowLabels\n twoDarray = []\n headerLine = None\n rowLabels = []\n # open filehandle\n fh = open(fn)\n\n headerLine = fh.readline()\n headerLine = headerLine.strip().split('\\t')\n\n for line in fh:\n arrayCols = line.s...
[ 1, 1 ]
[]
[]
[ "bioinformatics", "function", "python" ]
stackoverflow_0005930817_bioinformatics_function_python.txt
Q: Simulating a browser on Google App Engine I want to use selenium or windmill inside google app engine in order to scrape a JS filled website. I know that windmill is written in python and javascript. Is this possible? If it is, how do insert the library? If not, could you explain why and provide alternatives? Than...
Simulating a browser on Google App Engine
I want to use selenium or windmill inside google app engine in order to scrape a JS filled website. I know that windmill is written in python and javascript. Is this possible? If it is, how do insert the library? If not, could you explain why and provide alternatives? Thanks. Update I searched a little more and saw tha...
[ "Any python \"scraping\" library is unlikely to be able to interpret the javascript for you on appengine since it would probably require some kind of C-extension (like a binding to spidermonkey or v8) which would be against the GAE sandboxing.\nBut, if you were to venture over to the Java side you might have more l...
[ 3, 1, 1 ]
[]
[]
[ "google_app_engine", "python", "scrapy", "selenium", "windmill" ]
stackoverflow_0005930379_google_app_engine_python_scrapy_selenium_windmill.txt
Q: Optimization of importing modules in Python I am reading David Beazley's Python Reference book and he makes a point: For example, if you were performing a lot of square root operations, it is faster to use 'from math import sqrt' and 'sqrt(x)' rather than typing 'math.sqrt(x)'. and: For calculations inv...
Optimization of importing modules in Python
I am reading David Beazley's Python Reference book and he makes a point: For example, if you were performing a lot of square root operations, it is faster to use 'from math import sqrt' and 'sqrt(x)' rather than typing 'math.sqrt(x)'. and: For calculations involving heavy use of methods or module lookups, ...
[ "The from collections import defaultdict and import collections should be outside the iterated timing loops, since you won't repeat doing them.\nI guess that the from syntax has to do more work that the import syntax.\nUsing this test code:\n#!/usr/bin/env python\n\nimport timeit\n\nfrom collections import defaultd...
[ 6, 4, 1, 1, 1, 0 ]
[]
[]
[ "premature_optimization", "python" ]
stackoverflow_0005926114_premature_optimization_python.txt
Q: Can I append items to a list that I am looping through in Python? Possible Duplicate: Python: Adding element to list while iterating This doesn't seem to work, but I am not sure why: for n in poss: poss.append(n+6) Is there some rule that says I can't append items to a list that I am currently looping ...
Can I append items to a list that I am looping through in Python?
Possible Duplicate: Python: Adding element to list while iterating This doesn't seem to work, but I am not sure why: for n in poss: poss.append(n+6) Is there some rule that says I can't append items to a list that I am currently looping through?
[ "Appending to the list while iterating through it will enter an infinite loop, since you are adding more elements to the loop in each iteration.\nYou should iterate on a copy of the list instead. For example, try the following:\nfor n in tuple(poss):\n poss.append(n+6)\n\n", "Your code actually works, but neve...
[ 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0005931223_python.txt
Q: How do I use Python 3.0 under Apache? I've searched for ages on how to use Python 3 under Apache. If there is a walkthrough anywhere, it's very well hidden. Thus, hopefully, one of you Python professionals could make a quick 1-2-3 on how it's done! I'm on Windows 7 using the newest version of XAMPP. A: Only on P...
How do I use Python 3.0 under Apache?
I've searched for ages on how to use Python 3 under Apache. If there is a walkthrough anywhere, it's very well hidden. Thus, hopefully, one of you Python professionals could make a quick 1-2-3 on how it's done! I'm on Windows 7 using the newest version of XAMPP.
[ "Only on Python 3.1:\n\nhttp://code.google.com/p/modwsgi/downloads/list\n\n", "Python 3.0 is only supported via CGI. Put your CGI script in cgi-bin\\. If you're willing to look at newer versions, preliminary support is available in mod_wsgi (but you'll probably have to build it yourself).\n", "If you want to wr...
[ 2, 1, 0 ]
[]
[]
[ "apache", "python", "python_3.x", "windows" ]
stackoverflow_0005930982_apache_python_python_3.x_windows.txt
Q: How do I stop setup.py from trying to include -arch ppc on MacOSX builds? It appears that Xcode4 doesn't include PPC as a build option anymore. When using setup.py for modules that include C extensions, setup.py always attempts the build with these options: gcc-4.2 ... -DMACOSX -arch i386 -arch ppc ... This fails...
How do I stop setup.py from trying to include -arch ppc on MacOSX builds?
It appears that Xcode4 doesn't include PPC as a build option anymore. When using setup.py for modules that include C extensions, setup.py always attempts the build with these options: gcc-4.2 ... -DMACOSX -arch i386 -arch ppc ... This fails with the error message /usr/libexec/gcc/powerpc-apple-darwin10/4.2.1/as: assem...
[ "\nRemove ppc from compilation flags in python setup scripts\n\nOr, fix Xcode 4 installation about ppc assembler.\n$ sudo ln -s /Developer/Platforms/iPhoneOS.platform/Developer/usr/libexec/gcc/darwin/ppc /Developer/usr/libexec/gcc/darwin\n$ sudo ln -s /Developer/Platforms/iPhoneOS.platform/Developer/usr/libexec/gcc...
[ 2 ]
[]
[]
[ "osx_snow_leopard", "python", "setup.py", "xcode4" ]
stackoverflow_0005930807_osx_snow_leopard_python_setup.py_xcode4.txt
Q: BST or Hash Table? I have large text files upon which all kinds of operations need to be performed, mostly involving row by row validations. The data are generally of a sales / transaction nature, and thus tend to contain a huge amount of redundant information across rows, such as customer names. Iterating and m...
BST or Hash Table?
I have large text files upon which all kinds of operations need to be performed, mostly involving row by row validations. The data are generally of a sales / transaction nature, and thus tend to contain a huge amount of redundant information across rows, such as customer names. Iterating and manipulating this data ha...
[ "Hash table resizing isn't a concern unless you have a requirement that each insert into the table should take the same amount of time. As long as you always expand the hash table size by a constant factor (e.g. always increasing the size by 50%), the computational cost of adding an extra element is amortized O(1)....
[ 1, 0, 0 ]
[]
[]
[ "c", "data_structures", "file_io", "python" ]
stackoverflow_0005931151_c_data_structures_file_io_python.txt
Q: django ForeignKey to any type of model So I have a model, Comment. In it, it must keep a reference to whatever it's commenting to. It can be a response to a blog post, or it can be a response to another comment, etc. So how do I go about storing that relationship? Typically, I would just store the information with...
django ForeignKey to any type of model
So I have a model, Comment. In it, it must keep a reference to whatever it's commenting to. It can be a response to a blog post, or it can be a response to another comment, etc. So how do I go about storing that relationship? Typically, I would just store the information with a ForeignKey. But a ForeignKey requires tha...
[ "Check out GenericForeignKey in the built-in contenttypes framework.\n", "You want Django's generic relations.\n" ]
[ 5, 3 ]
[]
[]
[ "django", "django_models", "foreign_keys", "python" ]
stackoverflow_0005931523_django_django_models_foreign_keys_python.txt
Q: Explicitly set docstring of a method I help to maintain a package for python called nxt-python. It uses metaclasses to define the methods of a control object. Here's the method that defines the available functions: class _Meta(type): 'Metaclass which adds one method for each telegram opcode' def __init__(...
Explicitly set docstring of a method
I help to maintain a package for python called nxt-python. It uses metaclasses to define the methods of a control object. Here's the method that defines the available functions: class _Meta(type): 'Metaclass which adds one method for each telegram opcode' def __init__(cls, name, bases, dict): super(_Me...
[ "For plain functions:\ndef f(): # for demonstration\n pass\n\nf.__doc__ = \"Docstring!\"\nhelp(f)\n\nThis works in both python2 and python3, on functions with and without docstrings defined. You can also do +=. Note that it is __doc__ and not __docs__.\nFor methods, you need to use the __func__ attribute of the...
[ 19, 3 ]
[]
[]
[ "nxt", "python" ]
stackoverflow_0005931386_nxt_python.txt
Q: Can't execute an INSERT statement in a Python script via MySQLdb I'm trying to execute a basic INSERT statement on a MySQL table from a Python script using MySQLdb. My table looks like this: CREATE TABLE `testtable` ( `id` int(11) NOT NULL AUTO_INCREMENT, `testfield` varchar(255) NOT NULL, PRIMARY KEY ...
Can't execute an INSERT statement in a Python script via MySQLdb
I'm trying to execute a basic INSERT statement on a MySQL table from a Python script using MySQLdb. My table looks like this: CREATE TABLE `testtable` ( `id` int(11) NOT NULL AUTO_INCREMENT, `testfield` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) Running this query from the MySQL command line works fine: I...
[ "You either need to set conn.autocommit(), or you need to do conn.commit() - see the FAQ\n", "you need to commit:\nconn.commit()\n\nhttp://mysql-python.sourceforge.net/FAQ.html#my-data-disappeared-or-won-t-go-away\n" ]
[ 13, 6 ]
[]
[]
[ "mysql", "python", "sql" ]
stackoverflow_0005931771_mysql_python_sql.txt
Q: Is there any way to get a widgets position relative to the entire screen in Tkinter? I would like to know where exactly a widget is on the screen. A: You want to use the winfo_rootx and winfo_rooty methods of a widget.
Is there any way to get a widgets position relative to the entire screen in Tkinter?
I would like to know where exactly a widget is on the screen.
[ "You want to use the winfo_rootx and winfo_rooty methods of a widget.\n" ]
[ 4 ]
[]
[]
[ "geometry", "python", "screen", "tkinter" ]
stackoverflow_0005930780_geometry_python_screen_tkinter.txt
Q: How to Access a List within a List in linear Time and Create Indeterminate Numbers of Objects In Python, I'm currently working on a project. I am storing lines from a file as a list. In these lines, I want to delimit the strings by spaces and store the individual words from the line in an object. Each line contain...
How to Access a List within a List in linear Time and Create Indeterminate Numbers of Objects
In Python, I'm currently working on a project. I am storing lines from a file as a list. In these lines, I want to delimit the strings by spaces and store the individual words from the line in an object. Each line contains three "words" spaced apart. I want to store each word as an element in a class object. Since I do...
[ "class MyClass(object):\n def __init__(self, word1, word2, word3):\n # your initialisation code here\n\nfor line in list_of_lines:\n words = line.split()\n assert len(words) == 3\n an_object = MyClass(*words)\n do_something_with(an_object)\n\nUpdate in response to comment:\nTo get a list of My...
[ 1, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0005931997_oop_python.txt
Q: Does the python stack grow with an iterative process that is executed by a recursive procedure? I know that Python doesn't support tail-call optimization. Does that mean a recursive procedure with an iterative process like the factorial I defined below would consume O(n) memory, or does the fact that there are no ...
Does the python stack grow with an iterative process that is executed by a recursive procedure?
I know that Python doesn't support tail-call optimization. Does that mean a recursive procedure with an iterative process like the factorial I defined below would consume O(n) memory, or does the fact that there are no deferred operations mean that space would be O(1)? def factorial(n, accum=1): if n == 0: ...
[ "The memory will be O(n). If python optimized that case, then an exception that happened deep in the recursion wouldn't have a full stack trace. You can test for yourself that it does by just making the base case raise an exception, and you will see the full stack trace.\n", "No tail-call optimization means that ...
[ 5, 2 ]
[]
[]
[ "python", "tail_call_optimization", "tail_recursion" ]
stackoverflow_0005932118_python_tail_call_optimization_tail_recursion.txt
Q: Internals of Python list, access and resizing runtimes Is Python's [] a list or an array? Is the access time of an index O(1) like an array or O(n) like a list? Is appending/resizing O(1) like a list or O(n) like an array, or is it a hybrid that can manage O(1) for accessing and resizing? I read here that array a...
Internals of Python list, access and resizing runtimes
Is Python's [] a list or an array? Is the access time of an index O(1) like an array or O(n) like a list? Is appending/resizing O(1) like a list or O(n) like an array, or is it a hybrid that can manage O(1) for accessing and resizing? I read here that array access is really slow in Python. However, when I wrote a memo...
[ "Python's [] is implemented as an array, not a linked list. Although resizing is O(n), appending to it is amortized O(1), because resizes happen very rarely. If you're not familiar with how this works, read this Wikipedia entry on dynamic arrays. Python's list doesn't expand by a factor of 2 each time, it's a bit m...
[ 47, 10, 2, 0 ]
[]
[]
[ "internals", "list", "python", "space", "time" ]
stackoverflow_0005932328_internals_list_python_space_time.txt
Q: Python: Install a module out of source code certainly you all know the answer and it's easy going, but I'm new to python :) I found a piece of code in the internet reading the stock price from yahoo finance #!/usr/bin/env python # # Copyright (c) 2007-2008, Corey Goldberg (corey@goldb.org) # # license: GNU LGPL...
Python: Install a module out of source code
certainly you all know the answer and it's easy going, but I'm new to python :) I found a piece of code in the internet reading the stock price from yahoo finance #!/usr/bin/env python # # Copyright (c) 2007-2008, Corey Goldberg (corey@goldb.org) # # license: GNU LGPL # # This library is free software; you can redi...
[ "You could simply place it in the same directory as your script and you will be able to import it.\nIf you want to \"install\" it, you can place it as C:\\Python31\\Lib\\site-packages\\ystockquote.py. You should then be able to import it with import ystockquote.\n", "This code is actually for python 2.x, and sinc...
[ 9, 1 ]
[]
[]
[ "installation", "module", "python" ]
stackoverflow_0004664075_installation_module_python.txt
Q: Python + Django or PHP + Zend Framework when building a web 2.0 application, which one is superior in terms of performance availability of features documentation ease of use Python + Django combination or PHP + Zend combination? Also how easy it is to migrate one to another, so if I have written stuff for PHP +...
Python + Django or PHP + Zend Framework
when building a web 2.0 application, which one is superior in terms of performance availability of features documentation ease of use Python + Django combination or PHP + Zend combination? Also how easy it is to migrate one to another, so if I have written stuff for PHP + Zend combination how easy is it to move them...
[ "There is no direct one-to-one step or howto available for migrating PHP+Zend to Python+Django as both are different, different languages and different design models. So, migration is not easy. For other comparison questions you have asked, the answer is it depends upon the use case. But just in case you are compa...
[ 3 ]
[]
[]
[ "django", "performance", "php", "python", "zend_framework" ]
stackoverflow_0005932747_django_performance_php_python_zend_framework.txt
Q: Error starting Pyro Daemon using a NameServer: "could not find NameServer" I'm trying to get a simple Pyro example running (taken from this page), this is the code: import Pyro.core import Pyro.naming class JokeGen(Pyro.core.ObjBase): def joke(self, name): return "Sorry "+name+", I don't know any jokes." d...
Error starting Pyro Daemon using a NameServer: "could not find NameServer"
I'm trying to get a simple Pyro example running (taken from this page), this is the code: import Pyro.core import Pyro.naming class JokeGen(Pyro.core.ObjBase): def joke(self, name): return "Sorry "+name+", I don't know any jokes." daemon=Pyro.core.Daemon() ns=Pyro.naming.NameServerLocator().getNS() daemon.useNa...
[ "Run pyro-ns in another terminial first. That is the Pyro object broker.\n" ]
[ 4 ]
[]
[]
[ "pyro", "python" ]
stackoverflow_0005933016_pyro_python.txt
Q: Netfilter and Scapy I'm playing around with netfilter hooks in a kernel module. And I want to be able to capture packets created by scapy. Both the hooks, and also the packet generation via scapy are running on the same physical host. It seems that none of the available netfilter hooks is able to capture the packe...
Netfilter and Scapy
I'm playing around with netfilter hooks in a kernel module. And I want to be able to capture packets created by scapy. Both the hooks, and also the packet generation via scapy are running on the same physical host. It seems that none of the available netfilter hooks is able to capture the packet. I also tried to send t...
[ "Sniffing with Scapy\n[mpenning@Bucksnort ~]$ sudo python\nPython 2.5.2 (r252:60911, Jan 24 2010, 14:53:14)\n[GCC 4.3.2] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> from scapy.all import sniff\n>>> from scapy.all import wrpcap\n>>> foo = sniff(filter=\"icmp\", coun...
[ 1 ]
[]
[]
[ "netfilter", "python", "scapy" ]
stackoverflow_0005059649_netfilter_python_scapy.txt
Q: Scapy: no reply on raw ICMP packet I've constructed a packet with scapy: a=IP(dst='192.168.0.1',proto=1)/'\x08\x00\xf7\xff\x00\x00\x00\x00' I run: send(a) Wireshark shows me that there is a ping request and ping response from 192.168.0.1 No warnings, all fields are correct But when I try: b=sr1(a) Then Scapy ca...
Scapy: no reply on raw ICMP packet
I've constructed a packet with scapy: a=IP(dst='192.168.0.1',proto=1)/'\x08\x00\xf7\xff\x00\x00\x00\x00' I run: send(a) Wireshark shows me that there is a ping request and ping response from 192.168.0.1 No warnings, all fields are correct But when I try: b=sr1(a) Then Scapy can't get an answer (Wireshark shows me ag...
[ "The problem is that scapy doesn't know how to recognize the response because you are honestly building an ICMP packet the hard way. If you build it with ICMP(), it will work...\n>>> from scapy.all import ICMP, IP, sr1\n>>> aa = IP(dst='192.168.0.1')/ICMP()\n>>> sr1(aa)\nBegin emission:\nFinished to send 1 packets...
[ 3 ]
[]
[]
[ "packet", "python", "scapy" ]
stackoverflow_0005389000_packet_python_scapy.txt
Q: Partitioning a string in Python by a regular expression I need to split a string into an array on word boundaries (whitespace) while maintaining the whitespace. For example: 'this is a\nsentence' Would become ['this', ' ', 'is', ' ', 'a' '\n', 'sentence'] I know about str.partition and re.split, but neither of...
Partitioning a string in Python by a regular expression
I need to split a string into an array on word boundaries (whitespace) while maintaining the whitespace. For example: 'this is a\nsentence' Would become ['this', ' ', 'is', ' ', 'a' '\n', 'sentence'] I know about str.partition and re.split, but neither of them quite do what I want and there is no re.partition. How ...
[ "Try this:\ns = \"this is a\\nsentence\"\nre.split(r'(\\W+)', s) # Notice parentheses and a plus sign.\n\nResult would be:\n['this', ' ', 'is', ' ', 'a', '\\n', 'sentence']\n\n", "Symbol of whitespace in re is '\\s' not '\\W'\nCompare:\nimport re\n\n\ns = \"With a sign # written @ the beginning , that's a\\nse...
[ 15, 4, 3 ]
[]
[]
[ "python", "regex", "split", "whitespace" ]
stackoverflow_0005932059_python_regex_split_whitespace.txt
Q: Storing encrypted files inside a database I'm using PyCrypto to store some files inside a SQLITE database. I'm using 4 fields : the name of the file, the length of the file (in bytes) the SHA512 hash of the file the encrypted file (with AES and then base64 to ASCII). I need all the fields to show some info about t...
Storing encrypted files inside a database
I'm using PyCrypto to store some files inside a SQLITE database. I'm using 4 fields : the name of the file, the length of the file (in bytes) the SHA512 hash of the file the encrypted file (with AES and then base64 to ASCII). I need all the fields to show some info about the file without decrypting it. The question is ...
[ "Data encrypted with AES has the same length as the plain data (give or take some block padding), so giving original length away doesn't harm security. SHA512 is a strong cryptographic hash designed to provide minimal information about the original content, so I don't see a problem here either.\nTherefore, I think ...
[ 3, 1, 1, 0 ]
[]
[]
[ "database", "encryption", "python", "security" ]
stackoverflow_0005919819_database_encryption_python_security.txt
Q: Python module for Apple HTTP Live streams (HLS)? Does anyone know of a Python module for HTTP Live streams? If not what would be the best module for creating a simple client that downloads the ts files locally? A: If your goal is only to download locally the chunks, you can have a look at this script . It's been...
Python module for Apple HTTP Live streams (HLS)?
Does anyone know of a Python module for HTTP Live streams? If not what would be the best module for creating a simple client that downloads the ts files locally?
[ "If your goal is only to download locally the chunks, you can have a look at this script . It's been written a while ago, it dowloads all chunks in all resolutions ( I used it to mirror data locally, so you might want to hack it a bit, depending what you wanna do )\n" ]
[ 2 ]
[]
[]
[ "http_live_streaming", "python", "streaming" ]
stackoverflow_0005933252_http_live_streaming_python_streaming.txt
Q: How can I learn more about Python’s internals? I have been programming using Python for slightly more than half an year now and I am more interested in Python internals rather than using Python to develop applications. Currently I am working on porting a few libraries from Python2 to Python3. However, I have a rat...
How can I learn more about Python’s internals?
I have been programming using Python for slightly more than half an year now and I am more interested in Python internals rather than using Python to develop applications. Currently I am working on porting a few libraries from Python2 to Python3. However, I have a rather abstract view on how to make port stuff over fro...
[ "It sounds like you want to know more about the rationale behind the design of the language, rather than internals. \"internals\" to me means things like how objects are laid out in memory, how reference counting works, and so on.\nIf you're looking for a deeper understanding of the design decisions, try reading t...
[ 41, 15, 5, 2, 1, 0 ]
[]
[]
[ "internals", "python", "python_3.x" ]
stackoverflow_0003298464_internals_python_python_3.x.txt
Q: how to remove a variable in conjunction of functions in the loop? def wpath(): defpath = '/home/me/documents/' os.chdir(defpath) path = str(input("would you like to change current working directory? [y/yes] if you want")) if path == 'yes' or path == 'y': while True: try: ...
how to remove a variable in conjunction of functions in the loop?
def wpath(): defpath = '/home/me/documents/' os.chdir(defpath) path = str(input("would you like to change current working directory? [y/yes] if you want")) if path == 'yes' or path == 'y': while True: try: os.chdir(input('Enter new path! \n')) break ...
[ "You invoke del d only if len(d) == 0. Does that happen? Can you insert a print call into that branch and see if del is actually called?\nThat said, del d is a code smell. I'm 99.99% sure you don't really need to use it here. Can you explain what it is you're trying to do exactly?\nBesides that, why do you need d a...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0005933313_python_python_3.x.txt
Q: Reading csv file and compare objects to a list I have a .txt file,primary list, with strings like this: f r y h g j and I have a .csv file,recipes list, with rows like this: d,g,r,e,w,s j,f,o,b,x,q,h y,n,b,w,q,j My programe is going throw each row and counts number of objects which belongs to primary list, for e...
Reading csv file and compare objects to a list
I have a .txt file,primary list, with strings like this: f r y h g j and I have a .csv file,recipes list, with rows like this: d,g,r,e,w,s j,f,o,b,x,q,h y,n,b,w,q,j My programe is going throw each row and counts number of objects which belongs to primary list, for example in this case outcome is: 2 3 2 I always get 0...
[ "The reading into primary_list adds \\n to each number - you should remove it:\nWhen appending to primary_list do:\nfor line in primary_data:\n primary_list.append(line.strip())\n\nNote the strip call. Also, as you can see, you don't really need realines, since for line in primary_data already does what you need...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005933605_python.txt
Q: Clarifying this output from the pstats module I ran the cProfile on my code and this is the output: % stats 10 646493 function calls (524209 primitive calls) in 3.606 CPU seconds Ordered by: cumulative time List reduced from 260 to 10 due to restriction <10> ncalls tottime percall cumtime percall filen...
Clarifying this output from the pstats module
I ran the cProfile on my code and this is the output: % stats 10 646493 function calls (524209 primitive calls) in 3.606 CPU seconds Ordered by: cumulative time List reduced from 260 to 10 due to restriction <10> ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 3...
[ "\nI think you cannot see whether time is spent because of the method calls, or due to the work done inside those method.\nI agree. That would be the place to start micro-optimizing python code. It may bring you some speedup but there is usually a better way to speed up some given task.\nNot really. First of all, i...
[ 2 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0005932462_performance_python.txt
Q: looping dictionaries of {tuple:NumPy.array} i have a set of dictionaries k of the form {(i,j):NumPy.array} over which I want to loop the NumPy.arrays for a certain evaluation. I made the dictionarries as follows: datarr = ['PowUse', 'PowHea', 'PowSol', 'Top'] for i in range(len(dat)): exec(datarr[i]+'={}') so i...
looping dictionaries of {tuple:NumPy.array}
i have a set of dictionaries k of the form {(i,j):NumPy.array} over which I want to loop the NumPy.arrays for a certain evaluation. I made the dictionarries as follows: datarr = ['PowUse', 'PowHea', 'PowSol', 'Top'] for i in range(len(dat)): exec(datarr[i]+'={}') so i can always change the set of data i want to eval...
[ "datarr = ['PowUse', 'PowHea', 'PowSol', 'Top']\nfor i in range(len(dat)): exec(datarr[i]+'={}')\n\nWhy don't you create them as a dictionary of dictionaries?\ndatarr = ['PowUse', 'PowHea', 'PowSol', 'Top']\ndata = dict((name, {}) for name in datarr)\n\nThen you can avoid all the eval().\nfor i in filarr:\n for ...
[ 4 ]
[]
[]
[ "dictionary", "eval", "for_loop", "numpy", "python" ]
stackoverflow_0005934151_dictionary_eval_for_loop_numpy_python.txt
Q: form.is_valid() always returning false Model class class Fuzz_Engine(models.Model): id = PositiveTinyIntField(primary_key = True) engine_name = models.CharField(max_length=16) version = models.CharField(max_length = 16) class Meta: db_table = 'fuzz_engine' unique_together = ('engin...
form.is_valid() always returning false
Model class class Fuzz_Engine(models.Model): id = PositiveTinyIntField(primary_key = True) engine_name = models.CharField(max_length=16) version = models.CharField(max_length = 16) class Meta: db_table = 'fuzz_engine' unique_together = ('engine_name', 'version') class AddFuzzEngineForm...
[ "Couple of issues, it's hard to debug the code if the code you paste in isn't formatted well. The indentations were a mess so I'm not sure if that's causing a problem.\nIt seems like you are manually assigning a foreign key for your model. I would suggest just letting django handle the id for the model:\nclass Fuzz...
[ 3, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005932024_django_python.txt
Q: Python: Creating possible sublists from 2 lists where the order is not changed I am having 2 lists and I need to create different sublists where the order shouldn't be used again ( refer to example for clarity) list1= [ a, b, c, d] list2= [A, B, C, D] I need all possible sublists like [a, B,C,D], [ a,b, C, D], [A...
Python: Creating possible sublists from 2 lists where the order is not changed
I am having 2 lists and I need to create different sublists where the order shouldn't be used again ( refer to example for clarity) list1= [ a, b, c, d] list2= [A, B, C, D] I need all possible sublists like [a, B,C,D], [ a,b, C, D], [A,B,c,d], [a,b,c,D] ... there are 2 pow 4 = 16 solutions [looking for 2 pow N solutio...
[ "list1 = ['a', 'b', 'c', 'd']\nlist2 = ['A', 'B', 'C', 'D']\n\nfor i in xrange(2**len(list1)):\n output = []\n for j in xrange(0, len(list1)):\n bit = i & (1 << j)\n if bit == 0:\n output.append(list1[j])\n else:\n output.append(list2[j])\n print output\n\n", "I...
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005933960_python.txt
Q: What's wrong with my twisted server that's supposed to take a .exe and send its stdio to anyone who asks. Instead, it doesn't send anything print 'Preall test works!' from twisted.internet import reactor, protocol from twisted.python import log import sys print 'Imports done' class PrgShell(protocol.Protocol): ...
What's wrong with my twisted server that's supposed to take a .exe and send its stdio to anyone who asks. Instead, it doesn't send anything
print 'Preall test works!' from twisted.internet import reactor, protocol from twisted.python import log import sys print 'Imports done' class PrgShell(protocol.Protocol): data = '' class PrgProto(protocol.ProcessProtocol): def __init__(self, out): print 'Prgproto instance made' ...
[ "Replace reactor.spawnProcess(proto, addr) with reactor.spawnProcess(proto, addr, ['maze'], {}).\nPast experience has show that if you don't pass exe name as the first argument then nothing useful happens. However I have yet to find a reasonable explanation for why this happens.\nAlso you don't need global reactor....
[ 1 ]
[]
[]
[ "python", "twisted", "windows_xp" ]
stackoverflow_0005838274_python_twisted_windows_xp.txt
Q: Better way to write this SQL in Python Is there anyway I can reduce the duplication of my arguments? For example, timepattern is repeated 4 times and it gets hard to keep track of queries that are big. sql = ( "SELECT IFNULL(b.inviters/COUNT(DISTINCT c.id),0), " "...
Better way to write this SQL in Python
Is there anyway I can reduce the duplication of my arguments? For example, timepattern is repeated 4 times and it gets hard to keep track of queries that are big. sql = ( "SELECT IFNULL(b.inviters/COUNT(DISTINCT c.id),0), " " FROM_UNIXTIME(c.registered_at, %s) ...
[ "try with this with using args as a parameters dictionnary and using explicit string interpolation args (ie %(parameter_name)s ) : \nsql = ( \"SELECT IFNULL(b.inviters/COUNT(DISTINCT c.id),0), \" \n \" FROM_UNIXTIME(c.registered_at, %(timepattern)s) ...
[ 5, 4 ]
[]
[]
[ "mysql", "mysql_python", "python" ]
stackoverflow_0005934468_mysql_mysql_python_python.txt
Q: How can write a windmill test which uses an to upload data to the server? Title says it pretty much all... I'm trying to automate tests on a web application with Windmill, and some of the test need to use forms with input type="file". I know it is not possible to manipulate this with js, but I'm wondering if the ...
How can write a windmill test which uses an to upload data to the server?
Title says it pretty much all... I'm trying to automate tests on a web application with Windmill, and some of the test need to use forms with input type="file". I know it is not possible to manipulate this with js, but I'm wondering if the Python API of windmill allows this. I could not find anything in the docs, thoug...
[ "http://groups.google.com/group/windmill-dev/browse_thread/thread/cf9dc969722bd6bb/01aa18fdd652f7ff says it is not possible. \n" ]
[ 0 ]
[]
[]
[ "automated_tests", "python", "windmill" ]
stackoverflow_0003710011_automated_tests_python_windmill.txt
Q: Needing Help Capturing STDOUT in real-time from pygtk GUI in python project I am working on a project in which I want to use the command line utility cdparanoia from a python pygtk GUI. I'm using Glade for UI development. I have tried importing subprocess and using subprocess.Popen. It works, but it freezes my GUI...
Needing Help Capturing STDOUT in real-time from pygtk GUI in python project
I am working on a project in which I want to use the command line utility cdparanoia from a python pygtk GUI. I'm using Glade for UI development. I have tried importing subprocess and using subprocess.Popen. It works, but it freezes my GUI (won't even allow repainting of the windows) while the process is executing. Not...
[ "I wrote a Python shell implementation once, and it did run wget and the actual Python console with fully functional output.\nYou need to use subprocess.Popen and write directly to sys.stdout:\nprocess = subprocess.Popen(shlex.split(command), stdout = subprocess.PIPE, stderr = subprocess.STDOUT)\ncomplete = False\n...
[ 2, 1, 0 ]
[]
[]
[ "capture", "pygtk", "python", "shell", "stdout" ]
stackoverflow_0005913794_capture_pygtk_python_shell_stdout.txt
Q: Python script to convert csv to dump into database I have exported a file as a CSV. In excel, the data is all in the first column (four columns per row), and it looks like this -- like "name" "email" "message" "yes" "John Smith" "John@gmail.com" "My message" ...etc. When I import the fil...
Python script to convert csv to dump into database
I have exported a file as a CSV. In excel, the data is all in the first column (four columns per row), and it looks like this -- like "name" "email" "message" "yes" "John Smith" "John@gmail.com" "My message" ...etc. When I import the file, this is what I get -- '"""like"",""name"",""email"",...
[ "Use Python's standard library to parse the CSV file and extract the data you need to put into your database:\nimport csv\nwith open('some.csv', 'rb') as f:\n reader = csv.reader(f, delimiter=' ')\n for row in reader:\n print row\n\nSource: http://docs.python.org/library/csv.html\n" ]
[ 2 ]
[]
[]
[ "python", "sql" ]
stackoverflow_0005934996_python_sql.txt
Q: I have a status bar but how do I make it work? This code shows me a status bar. However when I click a button it does not say that I have done so in the status bar. import pygtk pygtk.require('2.0') import gtk import subprocess class Example: def __init__(self): window = gtk.Window(gtk.WINDOW_TOPLEV...
I have a status bar but how do I make it work?
This code shows me a status bar. However when I click a button it does not say that I have done so in the status bar. import pygtk pygtk.require('2.0') import gtk import subprocess class Example: def __init__(self): window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.set_size_request(400, 500) ...
[ "You need to explicitly update the statusbar by pushing a message to it. The documentation has a brief example showing how the statusbar works:\nTry this part, and let me know if the message shows:\ndef clickedWrite(self, widget):\n # push a new message to the statusbar, using context_id 0\n self.statusbar.pu...
[ 1, 1 ]
[]
[]
[ "connect", "pygtk", "python", "statusbar" ]
stackoverflow_0005929241_connect_pygtk_python_statusbar.txt
Q: Python: Handling modules I wrote a program which uses a number of built in modules. The program is meant to be used by different persons on their systems. They dont have enough knowledge in python to install it when their system doesnt have the module needed to run the program. Is there any way of handling that. A...
Python: Handling modules
I wrote a program which uses a number of built in modules. The program is meant to be used by different persons on their systems. They dont have enough knowledge in python to install it when their system doesnt have the module needed to run the program. Is there any way of handling that. Also I want to package the prog...
[ "I think what you need is to create a debian package that handles the dependencies and the installation process.\nI'm an Ubuntu user but this Complete Ubuntu Packaging Guide should help you get started. Good luck!\n", "You can create an executable that contains your python modules and the python interpreter. You ...
[ 2, 1, 1 ]
[]
[]
[ "debian", "installation", "linux", "module", "python" ]
stackoverflow_0005935291_debian_installation_linux_module_python.txt
Q: Is it possible to have 2 testclasses in one file in Unittest import .... class Test1: @classmethod def setUpClass(self): ... def test_something(self): ... @classmethod def tearDownClass(self): ... class Test2: @classmethod def setUpClass(self): ... def test_anotherthing(self)...
Is it possible to have 2 testclasses in one file in Unittest
import .... class Test1: @classmethod def setUpClass(self): ... def test_something(self): ... @classmethod def tearDownClass(self): ... class Test2: @classmethod def setUpClass(self): ... def test_anotherthing(self): ... @classmethod def tearDownClass(self): ... if _...
[ "Of course it's possible, just make sure they inherit from unittest.TestCase. Then, unittest.main will discover and run them.\nYou can also run just some of the tests in a file, by using theunittest.TestLoader().loadTestsFromTestCase or unittest.TestLoader().loadTestsFromNames methods. \n", "Yes it is. Why don't ...
[ 3, 1 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0005934853_python_unit_testing.txt
Q: How can django sql queries use case insensitive and contains at the same time? Suppose I have two users with username 'AbA' and 'aBa' in the database. My query word is 'ab'. I used User.objects.filter(username__contains='ab') and User.objects.filter(username__iexact='ab') These two queries get empty result. Howe...
How can django sql queries use case insensitive and contains at the same time?
Suppose I have two users with username 'AbA' and 'aBa' in the database. My query word is 'ab'. I used User.objects.filter(username__contains='ab') and User.objects.filter(username__iexact='ab') These two queries get empty result. However, I want to use something like username__contains__iexact='ab' that can retrieve ...
[ "Use:\nUser.objects.filter(username__icontains='ab')\n\n", "icontains is case-insensitive - http://docs.djangoproject.com/en/dev/ref/models/querysets/#std:fieldlookup-icontains\n" ]
[ 75, 14 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005935447_django_python.txt
Q: Get Changed Environment Variable in Python I have a requirement where 1 process sets a value as environment variable and I read that value in python using os.environ As per python doc: This mapping is captured the first time the os module is imported, typically during Python startup as part of processing...
Get Changed Environment Variable in Python
I have a requirement where 1 process sets a value as environment variable and I read that value in python using os.environ As per python doc: This mapping is captured the first time the os module is imported, typically during Python startup as part of processing site.py. Changes to the environment made afte...
[ "I guess you can use os.getenv() to get the value of an environment variable any time, and this will reflect the most up-to-date state.\nUpdate: note that there is no such thing as one \"global\" environment, at least not on Linux. Quoting Wikipedia:\n\nIn all Unix and Unix-like systems, each process has its own pr...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005935404_python.txt
Q: How can I catch errors from subprocess in a python cgi script? I'm trying to write a Python CGI script that will call sox (an audio processing program) using subprocess. The problem is that when I get errors from the sox call, everything crashes and I get a "malformed header" error from Apache. The relevant bits:...
How can I catch errors from subprocess in a python cgi script?
I'm trying to write a Python CGI script that will call sox (an audio processing program) using subprocess. The problem is that when I get errors from the sox call, everything crashes and I get a "malformed header" error from Apache. The relevant bits: def downsample(in_file, in_location, sox, out_location): """ run ...
[ "import subprocess\np = subprocess.Popen(cmd) \n p.wait() \n if p.returncode: \n print \"failed with code: %s\" % str(p.returncode) \n\n", "It sounds like you are using buffered output. \nIf that is the case, the output from the command is printed before the HTTP headers, so the web browser gets confu...
[ 2, 1, 0 ]
[]
[]
[ "apache", "cgi", "python", "subprocess" ]
stackoverflow_0005653377_apache_cgi_python_subprocess.txt
Q: Python: problems with read() when it is reading larger data (binary mode) This code is working well: f = open("C:/Dokumente und Einstellungen/schnei17/Desktop/a.txt", "r") f.seek(0) print f.read(200) But here read() doesn't work properly: print f.read(2000) The output is very short now. Is this a bug? The file...
Python: problems with read() when it is reading larger data (binary mode)
This code is working well: f = open("C:/Dokumente und Einstellungen/schnei17/Desktop/a.txt", "r") f.seek(0) print f.read(200) But here read() doesn't work properly: print f.read(2000) The output is very short now. Is this a bug? The file contains unicode-data. Thanks in advance. Solution: f = open("C:/Dokumente und...
[ "What does this produce?\nimport os\nfilename = \"C:/Dokumente und Einstellungen/schnei17/Desktop/a.txt\"\nprint \"Filesize: %s\" % (os.path.getsize(filename),)\nf = open(filename, \"r\")\ndata = f.read(2000)\nprint \"Read %s bytes\" % (len(data),)\n\n\nFilesize: 62606 Read 692 bytes\n\nAnd changing the read mode t...
[ 2 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0005935996_file_io_python.txt
Q: sys.exc_info()[1] type and format in Python 2.71 In python 2.71 on Windows XP I need to use FTP. My code is : try: ftp = FTP(trec.address) ftp.login(trec.login, trec.passw) s = ftp.retrlines('LIST ' + trec.filetype) ftp.quit() except: (type, value, tb) = sys.exc_info() reponse = "%s" % val...
sys.exc_info()[1] type and format in Python 2.71
In python 2.71 on Windows XP I need to use FTP. My code is : try: ftp = FTP(trec.address) ftp.login(trec.login, trec.passw) s = ftp.retrlines('LIST ' + trec.filetype) ftp.quit() except: (type, value, tb) = sys.exc_info() reponse = "%s" % value But I have an error on the last line : UnicodeDec...
[ "value is an instance of the Error class. You want to format it as a string. This is impossible. It seems you want to get the message associated with the error. That message can be found in value.message. Try this:\ntry:\n ftp = FTP(trec.address)\n ftp.login(trec.login, trec.passw)\n s = ftp.retrlines('LIS...
[ 4, 0 ]
[]
[]
[ "python", "string_formatting", "unicode" ]
stackoverflow_0005736080_python_string_formatting_unicode.txt
Q: mac snow leopard setuptools stick to MacOSX10.4u.sdk when trying to install python-mysql when I try to install python-mysql today, I got a number of compilation error or complaining /Developer/SDKs/MacOSX10.4u.sdk not found, like the following: running build running build_py copying MySQLdb/release.py -> build/li...
mac snow leopard setuptools stick to MacOSX10.4u.sdk when trying to install python-mysql
when I try to install python-mysql today, I got a number of compilation error or complaining /Developer/SDKs/MacOSX10.4u.sdk not found, like the following: running build running build_py copying MySQLdb/release.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb running build_ext building '_mysql' extension Compiling with ...
[ "Check your environment for CFLAGS or LDFLAGS. Both of these can include the -isysroot argument that influences the SDK selection. The other place to start at is to look at the output of python2.6-config --cflags --ldflags since (I believe) that this influences the Makefile generation. Make sure to run easy_inst...
[ 0 ]
[]
[]
[ "compilation", "macos", "mysql", "osx_snow_leopard", "python" ]
stackoverflow_0005935910_compilation_macos_mysql_osx_snow_leopard_python.txt
Q: How to use Executemany in my situation? How can I get these sequence of SQL statements? to work? I have previously only dealt with single select statements and cursor.execute worked fine for that. I'm not sure what to do in this case now. The error I am getting is format requires a mapping args = { "timep...
How to use Executemany in my situation?
How can I get these sequence of SQL statements? to work? I have previously only dealt with single select statements and cursor.execute worked fine for that. I'm not sure what to do in this case now. The error I am getting is format requires a mapping args = { "timepattern" : timepattern, "datestart_int...
[ "Let's assume that your database software supports argument placeholders of the form %(name)s.\nLet's also assume that it supports multiple statements in one \"operation\". Note: the 3rd statement (SELECT ... UNION ALL SELECT ...) is missing a semicolon at the end.\nIn that case, all you need to do is use cursor.ex...
[ 2, 1 ]
[]
[]
[ "executemany", "mysql", "mysql_python", "python" ]
stackoverflow_0005935786_executemany_mysql_mysql_python_python.txt
Q: reusable function: substituting the values returned by another function Below is the snippet: I'm parsing job log and the output is the formatted result. def job_history(f): def get_value(j,n): return j[n].split('=')[1] lines = read_file(f) for line in lines: if line.find('Exit_status...
reusable function: substituting the values returned by another function
Below is the snippet: I'm parsing job log and the output is the formatted result. def job_history(f): def get_value(j,n): return j[n].split('=')[1] lines = read_file(f) for line in lines: if line.find('Exit_status=') != -1: nLine = line.split(';') jobID = '.'.join(n...
[ "Since you don't know LJ, LU, LH, LQ, LE until the for-loop ends, you have to complete this for-loop before you print.\n result=[]\n for line in lines:\n if line.find('Exit_status=') != -1:\n ...\n LJ = max(LJ, len(jobID))\n LU = max(LU, len(jUsr))\n LH = max...
[ 1, 0, 0 ]
[]
[]
[ "python", "python_2.4" ]
stackoverflow_0005936387_python_python_2.4.txt
Q: How to use beaker with GAE Hi I'm going to use an own session object and I'm trying to apply beaker with python. Can you tell me how to use it with google app engine? I've got the following code and then I'm unsure how to proceed: session_opts = { 'session.cookie_expires': True, 'session.type':...
How to use beaker with GAE
Hi I'm going to use an own session object and I'm trying to apply beaker with python. Can you tell me how to use it with google app engine? I've got the following code and then I'm unsure how to proceed: session_opts = { 'session.cookie_expires': True, 'session.type': 'ext:google', 'session....
[ "As the documentation says: \n\nOnce the SessionMiddleware is in\n place, a session object will be made\n available as beaker.session in the\n WSGI environ.\n\nIn Google App Engine you can access the beaker session dictonary object from a WebHandler with:\nsession = self.request.environ['beaker.session']\n\nthe ...
[ 4 ]
[]
[]
[ "beaker", "google_app_engine", "python", "session" ]
stackoverflow_0005935549_beaker_google_app_engine_python_session.txt
Q: python float class doesn't show up in class hierarchy unless "prodded" If I use this function to print out a python class hierarchy for some reason the type "float" doesn't show up in the output. def printHier(cls, indent = 0, tab = " "): print "%s%s" % (tab*indent, cls.__name__) try: subclasses...
python float class doesn't show up in class hierarchy unless "prodded"
If I use this function to print out a python class hierarchy for some reason the type "float" doesn't show up in the output. def printHier(cls, indent = 0, tab = " "): print "%s%s" % (tab*indent, cls.__name__) try: subclasses = cls.__subclasses__() except TypeError: subclasses = cls.__sub...
[ "It seems to be a problem with Python 2.6.1. float shows on my installations (2.6.4 and 2.7, both on Windows) and on other newer versions tested by Jay and samplebias.\nI looked for something relevant in the CPython changelog, but I couldn't find anything that seems to be related.\n" ]
[ 4 ]
[]
[]
[ "class", "floating_point", "hierarchy", "lazy_evaluation", "python" ]
stackoverflow_0005924054_class_floating_point_hierarchy_lazy_evaluation_python.txt
Q: Equation parsing in Python How can I (easily) take a string such as "sin(x)*x^2" which might be entered by a user at runtime and produce a Python function that could be evaluated for any value of x? A: Python's own internal compiler can parse this, if you use Python notation. If your change the notation slightl...
Equation parsing in Python
How can I (easily) take a string such as "sin(x)*x^2" which might be entered by a user at runtime and produce a Python function that could be evaluated for any value of x?
[ "Python's own internal compiler can parse this, if you use Python notation.\nIf your change the notation slightly, you'll be happier.\nimport compiler\neq= \"sin(x)*x**2\"\nast= compiler.parse( eq )\n\nYou get an abstract syntax tree that you can work with.\n", "You can use Python parser:\nimport parser\nfrom mat...
[ 52, 35, 15, 8, 3, 0, 0 ]
[]
[]
[ "equation", "parsing", "python" ]
stackoverflow_0000594266_equation_parsing_python.txt
Q: Resolve mac address by host name I've wrote several perl scripts during my internship, and I would like to simplify the use of them. The scripts asks in arg, a mac address, and returns which switch is connected, speed...etc. Instead of giving a mac address, I would like to give a host name of a computer. So, how c...
Resolve mac address by host name
I've wrote several perl scripts during my internship, and I would like to simplify the use of them. The scripts asks in arg, a mac address, and returns which switch is connected, speed...etc. Instead of giving a mac address, I would like to give a host name of a computer. So, how can I resolve the hostname to mac addre...
[ "Does this help?\n[mpenning@Bucksnort ~]$ arp -an\n? (4.121.8.3) at 08:00:27:f5:5b:6b [ether] on eth0\n? (4.121.8.4) at 08:00:27:f5:5b:6b [ether] on eth0\n? (4.121.8.1) at 00:1b:53:6b:c9:c4 [ether] on eth0\n[mpenning@Bucksnort ~]$\n\nIn python...\n#!/usr/bin/env python\nimport subprocess\nimport re\n\ndef parse_arp...
[ 2, 0 ]
[]
[]
[ "hostname", "ip", "mac_address", "perl", "python" ]
stackoverflow_0005936781_hostname_ip_mac_address_perl_python.txt
Q: How to pass values to pyparsing parseactions? Specifically I want to write a generic parseaction function which will verify ranges of numbers. I want to pass a min & max to the function. Is this possible ? A: Use a closure, something like this: def rangeCheck(minval=None, maxval=None): if minval is None and ...
How to pass values to pyparsing parseactions?
Specifically I want to write a generic parseaction function which will verify ranges of numbers. I want to pass a min & max to the function. Is this possible ?
[ "Use a closure, something like this:\ndef rangeCheck(minval=None, maxval=None):\n if minval is None and maxval is None:\n # this exception occurs not at parse time, but while defining the grammar\n raise ValueError(\"minval or maxval must be specified\")\n\n def rangeCheckParseAction(string, loc...
[ 6, 0 ]
[]
[]
[ "pyparsing", "python" ]
stackoverflow_0005935525_pyparsing_python.txt
Q: python mysql operationalerror I have a Python script that processes some data and then inserts it into mysql using MySQLdb. When I run the script on my local server all is well. When I run it on our server I straightaway get OperationalError: (2006, 'MySQL server has gone away') Any ideas? A: 2006, 'MySQL serve...
python mysql operationalerror
I have a Python script that processes some data and then inserts it into mysql using MySQLdb. When I run the script on my local server all is well. When I run it on our server I straightaway get OperationalError: (2006, 'MySQL server has gone away') Any ideas?
[ "2006, 'MySQL server has gone away' means time out. Most times when it happend to me when I try to connet to external mysql server and this server was not set up to accept external connections (from your localhost). Straightaway response would confirm it.\n", "Check the logs of your MySQL installation and see if ...
[ 0, 0, -2 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0005137996_mysql_python.txt
Q: email client for app engine GAE supports both incoming and outgoing emails: http://code.google.com/appengine/docs/python/mail/ Have any open source email clients been written for GAE? Something that handles encoding issues, attachments, grouping by conversations, etc. A: The Google App Engine SDK can send and re...
email client for app engine
GAE supports both incoming and outgoing emails: http://code.google.com/appengine/docs/python/mail/ Have any open source email clients been written for GAE? Something that handles encoding issues, attachments, grouping by conversations, etc.
[ "The Google App Engine SDK can send and receive email; however, there are certain limitations in place that would prevent an actual email client from being built:\n\nThe App Engine receives email at the following address: string@appid.appspotmail.com\n\nhttp://code.google.com/appengine/docs/python/mail/receivingma...
[ 6, 2, 1 ]
[]
[]
[ "email", "google_app_engine", "python", "webmail" ]
stackoverflow_0004572755_email_google_app_engine_python_webmail.txt
Q: How to check if an object already called in Python? I created an GUI using PyGTK. I want to add, in some cases, more UI elements to my GUI. I did something like that: try: self.main.addServer(self.factory.logingo) except: self.main = MainWindow(self.factory.loginfo) I want to call addServer when my object...
How to check if an object already called in Python?
I created an GUI using PyGTK. I want to add, in some cases, more UI elements to my GUI. I did something like that: try: self.main.addServer(self.factory.logingo) except: self.main = MainWindow(self.factory.loginfo) I want to call addServer when my object self.main (which is my gtk.Window object) already exist....
[ "if not hasattr(self, 'main'):\n self.main = MainWindow(self.factory.loginfo)\nself.main.addServer(self.factory.logingo)\n\nPS: be ware of try: ... except: ... without any specific exceptation, unless when you know what are you doing. because that hides probable (and unexpected) exceptations. Instead, for exampl...
[ 0 ]
[]
[]
[ "instantiation", "object", "pygtk", "python", "try_catch" ]
stackoverflow_0005935764_instantiation_object_pygtk_python_try_catch.txt
Q: a really strange bug when my python program working with mysqll here is the code sql="SELECT node_id FROM %s WHERE domain='%s';"%(config.nodetable,url) r=getBySql(sql) my problem is trying to save data in mysql db so this code should was executed repeatedly for like more than hundred thousands of times. and at t...
a really strange bug when my python program working with mysqll
here is the code sql="SELECT node_id FROM %s WHERE domain='%s';"%(config.nodetable,url) r=getBySql(sql) my problem is trying to save data in mysql db so this code should was executed repeatedly for like more than hundred thousands of times. and at the beginning everything went well, until several times the interpreto...
[ "MySQLdb will convert your parameter into a SQL literal, do not use single quotes in your sql string, or a semi-colon at the end, and don't use string interpolation:\nsql = \"SELECT node_id FROM %s WHERE domain=%s\" % (config.nodetable, url)\n\nDo this instead:\ncursor.execute(\"SELECT node_id FROM %s WHERE domain=...
[ 1 ]
[]
[]
[ "mysql", "mysql_python", "python" ]
stackoverflow_0005937471_mysql_mysql_python_python.txt
Q: String to dictionary I am trying to convert a string to dictionary. Example: Milk, Cheese, Bottle The program will convert it to dictionary. {"Milk":"NULL", "Cheese":"NULL", "Bottle":"NULL"} How do I do it? A: >>> string = 'Milk, Cheese, Bottle' >>> dict((key, None) for key in string.split(', ')) {'Cheese': No...
String to dictionary
I am trying to convert a string to dictionary. Example: Milk, Cheese, Bottle The program will convert it to dictionary. {"Milk":"NULL", "Cheese":"NULL", "Bottle":"NULL"} How do I do it?
[ ">>> string = 'Milk, Cheese, Bottle'\n>>> dict((key, None) for key in string.split(', '))\n{'Cheese': None, 'Milk': None, 'Bottle': None}\n\n", ">>> s = \"Milk, Cheese, Bottle\"\n>>> d = dict.fromkeys(s.split(', '),\"NULL\")\n>>> d\n{'Cheese': 'NULL', 'Milk': 'NULL', 'Bottle': 'NULL'}\n\n", "dict.fromkeys((k.st...
[ 8, 5, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005937629_python.txt
Q: Facebook api in python and sources to master it! I've good enough knowledge of python and I want to use facebook python api and for that I've got all the API key and App Secret etc from the developer site. Now what I want is a good source to provide me with good knowledge how to authenticate and retrieve data like...
Facebook api in python and sources to master it!
I've good enough knowledge of python and I want to use facebook python api and for that I've got all the API key and App Secret etc from the developer site. Now what I want is a good source to provide me with good knowledge how to authenticate and retrieve data like statuses etc using the Python IDLE(in win7). I search...
[ "You probably want to use the python version of the facebook-sdk. It contains a few examples.\n" ]
[ 5 ]
[]
[]
[ "api", "facebook", "python" ]
stackoverflow_0005938234_api_facebook_python.txt
Q: Python module name conflict I have come across two Python modules that have to be imported using the same module name, e.g. import foo I know that the one I want provides certain functions (e.g. foo.bar()), so is there a way to cycle through the modules with the same name until I find the one that provides those ...
Python module name conflict
I have come across two Python modules that have to be imported using the same module name, e.g. import foo I know that the one I want provides certain functions (e.g. foo.bar()), so is there a way to cycle through the modules with the same name until I find the one that provides those functions? Or is there no way aro...
[ "Here is a way :\nimport imp\nimport sys\n\n\ndef find_module(name, predicate=None):\n \"\"\"Find a module with the name if this module have the predicate true.\n\n Arguments:\n - name: module name as a string.\n - predicate: a function that accept one argument as the name of a module and return\n...
[ 6, 3, 0, 0 ]
[]
[]
[ "conflict", "module", "python" ]
stackoverflow_0005937739_conflict_module_python.txt
Q: Not able call a local method from setUpClass My code: class TestSystemPromotion(unittest2.TestCase): @classmethod def setUpClass(self): ... self.setup_test_data() .. def test_something(self): ... def setup_test_data(self): ... if __name__ == '__main__': unittest2.main() Error whi...
Not able call a local method from setUpClass
My code: class TestSystemPromotion(unittest2.TestCase): @classmethod def setUpClass(self): ... self.setup_test_data() .. def test_something(self): ... def setup_test_data(self): ... if __name__ == '__main__': unittest2.main() Error which I'm getting is: TypeError: unbound method setup...
[ "You can't call instance methods from class methods. Either consider using setUp instead, or make setup_test_data a class method too. Also, it's better if you called the argument cls instead of self to avoid the confusion - the first argument to the class method is the class, not the instance. The instance (self) d...
[ 19 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0005938517_python_unit_testing.txt
Q: Converting a nested dictionary to a list I know there are many dict to list questions on here but I can't quite find the information I need for my situation so I'm asking a new quetion. Some background: I'm using a hierarchical package for my models and the built-in function which generates the tree structure outp...
Converting a nested dictionary to a list
I know there are many dict to list questions on here but I can't quite find the information I need for my situation so I'm asking a new quetion. Some background: I'm using a hierarchical package for my models and the built-in function which generates the tree structure outputs a nested loop to indicate parents, childre...
[ "I think recursion can be your friend : \ntop = {\"<Part: 1.1>\": {\"<Part: 1.1.1>\": {\"<Part: 1.1.1.1>\": {}}, \"<Part: 1.1.2>\": {}}, \"<Part: 1.2>\": {\"<Part: 1.2.1>\": {}, \"<Part: 1.2.2>\": {}}, \"<Part: 1.3>\": {}}\n\n def grab_children(father):\n local_list = []\n for key, value in father.iteritems()...
[ 12, 2, 1, 0, 0 ]
[]
[]
[ "django", "django_templates", "django_views", "python" ]
stackoverflow_0005938125_django_django_templates_django_views_python.txt
Q: What would I need to code in order for one user to download files from another users computer, through a website? I am trying to make a web application where a user can leave his computer on, and multiple other users can download a specified file off of his computer. But without a main server... so the user's comp...
What would I need to code in order for one user to download files from another users computer, through a website?
I am trying to make a web application where a user can leave his computer on, and multiple other users can download a specified file off of his computer. But without a main server... so the user's computer would be the server. (maybe some how like limewire did it?) And most importantly it all has to be on a website... ...
[ "It's not possible without the user downloading and explicitly installing something, it's for obvious security reasons!!\n", "Maybe I missed something in your description but as I see it you just described an ordinary website. you could run a webserver on the computer with directory listing of some kind and just ...
[ 2, 0, 0 ]
[]
[]
[ "flash", "java", "python", "websocket" ]
stackoverflow_0005937984_flash_java_python_websocket.txt
Q: How can I make it so that the file opens when i click it import pygtk pygtk.require('2.0') import gtk # Check for new pygtk: this is new class in PyGtk 2.4 if gtk.pygtk_version < (2,3,90): print "PyGtk 2.3.90 or later required for this example" raise SystemExit dialog = gtk.FileChooserDialog("Open..", ...
How can I make it so that the file opens when i click it
import pygtk pygtk.require('2.0') import gtk # Check for new pygtk: this is new class in PyGtk 2.4 if gtk.pygtk_version < (2,3,90): print "PyGtk 2.3.90 or later required for this example" raise SystemExit dialog = gtk.FileChooserDialog("Open..", None, ...
[ "This is of course for Linux only:\nimport subprocess\n\nsubprocess.call(['/usr/bin/terminal','-x','/usr/bin/vim', dialog.get_filename()])\n\n" ]
[ 0 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0005930271_pygtk_python.txt
Q: Bug or misunderstanding in Python 2.7? Possible Duplicate: “Least Astonishment” in Python: The Mutable Default Argument Am I missing something here or is this really a bug? Below is a recursive function that generates a multi-dimensional list from a tuple specification, for example. dim((2,3)) returns [[[],[...
Bug or misunderstanding in Python 2.7?
Possible Duplicate: “Least Astonishment” in Python: The Mutable Default Argument Am I missing something here or is this really a bug? Below is a recursive function that generates a multi-dimensional list from a tuple specification, for example. dim((2,3)) returns [[[],[],[]],[[],[],[]]] The only problem is that...
[ "def dim(t, c = [])\nIt's a bug (in your code). That c = [] part is only evaluated once during the entire program. When you call dim, c is being continuously appended to. A better approach would be this:\ndef dim(t, c=None):\n if c is None:\n c = []\n ...\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0005939015_python.txt
Q: Upload pic from another website using django I want to make an image uploader using images links on the internet (eq: wwww.google.com/image.jpg). The user writes the previous url and then my model upload it. This my code: form <input id="id_name" type="text" name="name" maxlength="255" value="www.example.com/main....
Upload pic from another website using django
I want to make an image uploader using images links on the internet (eq: wwww.google.com/image.jpg). The user writes the previous url and then my model upload it. This my code: form <input id="id_name" type="text" name="name" maxlength="255" value="www.example.com/main.jpg" /> view.py def Post_date(): if request....
[ "What are you taking from the user input? Is it Image file or the image URL?\nIf it is image URL then, make the field a forms.URLField and do the post and save like you are doing now.\nIf it is a image file, then don't extract the image file from the POST request. After you take out the file, (via read()) form.is_v...
[ 0, 0 ]
[]
[]
[ "django", "html", "python" ]
stackoverflow_0005935064_django_html_python.txt
Q: Suds: Type not found on response I'm having a hard time getting a python SOAP client based on suds to parse a response: the client is constructed correctly and parses the WSDL just fine. As far as I can see there are no imports in the WSDL, so this doesn't seem like a typical ImportDoctor issue. Relevant bits from...
Suds: Type not found on response
I'm having a hard time getting a python SOAP client based on suds to parse a response: the client is constructed correctly and parses the WSDL just fine. As far as I can see there are no imports in the WSDL, so this doesn't seem like a typical ImportDoctor issue. Relevant bits from the WSDL: <xsd:complexType na...
[ "This might be a job for the ImportDoctor. It's surprisingly common to run across broken WSDLs. \nTry this:\nfrom suds.client import Client\nfrom suds.xsd.doctor import Import, ImportDoctor\n\nwsdl_url = settings.WSDL_URL\n\n# Fix missing types with ImportDoctor\nschema_url = 'http://www.type-applications.com/cha...
[ 6, 2 ]
[]
[]
[ "python", "response", "suds", "types", "wsdl" ]
stackoverflow_0005654805_python_response_suds_types_wsdl.txt
Q: How to call a javascript method from python on SL4A? I am writing an Android app using Python and SL4A. The app uses a webview that I wish to refresh. I plan on doing this by utilising javascript location.replace() within a wrapping doRefresh() javascript function. The problem I have is that I do not know how to c...
How to call a javascript method from python on SL4A?
I am writing an Android app using Python and SL4A. The app uses a webview that I wish to refresh. I plan on doing this by utilising javascript location.replace() within a wrapping doRefresh() javascript function. The problem I have is that I do not know how to call the javascript function from within my main event loop...
[ "You'll need to wait for a refresh event (this would be a custom event) in your JavaScript that is waiting for an event posted from your Python script. The only communication layer between JavaScript and Python is via events.\n" ]
[ 2 ]
[]
[]
[ "android", "javascript", "python", "sl4a" ]
stackoverflow_0005934326_android_javascript_python_sl4a.txt
Q: Django CMS / WYMEditor Stop Stripping of Whitespace I'm aware of what WYMEditor is all about and that using Paragraphs for spacing is not intended, however the problem here is with the client requiring that we give them this functionality. I've looked high and low to find where WYMEditor does it's stripping of whi...
Django CMS / WYMEditor Stop Stripping of Whitespace
I'm aware of what WYMEditor is all about and that using Paragraphs for spacing is not intended, however the problem here is with the client requiring that we give them this functionality. I've looked high and low to find where WYMEditor does it's stripping of whitespace and can't seem to find it at all. It seems that w...
[ "Turns out, the function that does this stripping is very simply named, for some reason I missed it in (multiple!) searches for the word 'empty' in the script file.\nIt's located in jquery.wymeditor.js, line ~3440 there is the function WYMeditor.XhtmlSaxListener.prototype.removeEmptyTags, simply stop the replacemen...
[ 2 ]
[]
[]
[ "django", "django_cms", "javascript", "python", "wymeditor" ]
stackoverflow_0005938956_django_django_cms_javascript_python_wymeditor.txt
Q: working with html on python code so in PHP it's possible to have an entire section of php source be filled with direct raw html: <?php function doThis(){ ?> <html> <a>LOOL</a> </html> <?php } doThis(); ?> and calling doThis() will print out all the html code between the...
working with html on python code
so in PHP it's possible to have an entire section of php source be filled with direct raw html: <?php function doThis(){ ?> <html> <a>LOOL</a> </html> <?php } doThis(); ?> and calling doThis() will print out all the html code between the curly braces...is there a similar fu...
[ "Python is not a pseudo-template language like PHP, if you want to generate HTML use a template engine like Jinja2.\n", "I'm not certain I fully understand your question, but if you need to have long blocks of arbitrary text in Python the best way I've found is like so:\nmyHTML = \"\"\"\n<html>\n<head>\n<title>I ...
[ 4, 4, 2, 1, 0 ]
[]
[]
[ "html", "php", "python" ]
stackoverflow_0005939429_html_php_python.txt
Q: Watching sockets with Glib on Windows puts them in non-blocking mode The following code does not work correctly on Windows (but does on Linux): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setblocking(True) sock.connect(address) gobject.io_add_watch( sock.fileno(), ...
Watching sockets with Glib on Windows puts them in non-blocking mode
The following code does not work correctly on Windows (but does on Linux): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setblocking(True) sock.connect(address) gobject.io_add_watch( sock.fileno(), gobject.IO_OUT | gobject.IO_ERR | gobject.IO_HUP, call...
[ "Is there a problem with doing non-blocking I/O? It seems kind of strange to use polling loops if you're using blocking I/O.\nWhen I write programs like this I tend to do the following:\n\nBuffer the bytes I want to send to the file descriptor.\nOnly ask for IO_OUT (or the poll() equivalent, POLLOUT) events when s...
[ 1, 1, 0, 0 ]
[]
[]
[ "gio", "glib", "pygtk", "python", "windows" ]
stackoverflow_0001648631_gio_glib_pygtk_python_windows.txt
Q: Passing Command Line argument to Python script to be able to open a connection to a web server I'm writing some shell scripts to check if I can manipulate information on a web server. I use a bash shell script as a wrapper script to kick off multiple python scripts in sequential order The wrapper script takes the ...
Passing Command Line argument to Python script to be able to open a connection to a web server
I'm writing some shell scripts to check if I can manipulate information on a web server. I use a bash shell script as a wrapper script to kick off multiple python scripts in sequential order The wrapper script takes the web server's host name and user name and password. and after performing some tasks, hand's it to the...
[ "You need to quote the string when doing variable substitution: \nhttp://%s/path/file.php % value # Does not work\n\"http://%s/path/file.php\" % value # Works\n'http://%s/path/file.php' % value # Also works\n\"\"\"http://%s/path/file.php\"\"\" % value # Also works\n\nPython does not do string interpolation the way...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005939850_python.txt
Q: Python, default keyword arguments after variable length positional arguments I thought I could use named parameters after variable-length positional parameters in a function call in Python 2, but I get a SyntaxError when importing a python class. I'm writing with the following "get" method, for example: class Foo(...
Python, default keyword arguments after variable length positional arguments
I thought I could use named parameters after variable-length positional parameters in a function call in Python 2, but I get a SyntaxError when importing a python class. I'm writing with the following "get" method, for example: class Foo(object): def __init__(self): print "You have created a Foo." def ...
[ "It does work, but only in Python 3. See PEP 3102. From glancing over the \"what's new\" documents, it seems that there is no 2.x backport, so you're out of luck. You'll have to accept any keyword arguments (**kwargs) and manually parse it. You can use d.get(k, default) to either get d[k] or default if that's not t...
[ 74, 50 ]
[]
[]
[ "default_parameters", "named_parameters", "python", "python_2.x", "variadic_functions" ]
stackoverflow_0005940180_default_parameters_named_parameters_python_python_2.x_variadic_functions.txt
Q: Convex Hull reading XY co-ords in Python I need to come up with a convex hull algorithm to read through a bunch of X , Y co-ordinates and outline the image.. i'm coding in python Any ideas? A: Are there any more details or constraints to your question? After searching wikipedia for "Convex hull algorithms", it ...
Convex Hull reading XY co-ords in Python
I need to come up with a convex hull algorithm to read through a bunch of X , Y co-ordinates and outline the image.. i'm coding in python Any ideas?
[ "Are there any more details or constraints to your question? After searching wikipedia for \"Convex hull algorithms\", it gave me a list of algorithms, of which I clicked \"Monotone Chain\"\nhttp://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain\n" ]
[ 2 ]
[]
[]
[ "convex_hull", "convex_polygon", "python" ]
stackoverflow_0005940278_convex_hull_convex_polygon_python.txt
Q: How to make FileField in django optional? I have form with a textbox and filefield in django. It should let the use either paste the text into that box or upload a file. If the user has pasted the text into the box, I needn't check the fileField. How do I make the forms.FileField() optional? A: If you're using a...
How to make FileField in django optional?
I have form with a textbox and filefield in django. It should let the use either paste the text into that box or upload a file. If the user has pasted the text into the box, I needn't check the fileField. How do I make the forms.FileField() optional?
[ "If you're using a forms.FileField() in a forms.Form derived class, you can set:\nclass form(forms.Form):\n file = forms.FileField(required=False)\n\nIf you're using a models.FileField() and have a forms.ModelForm assigned to that model, you can use\nclass amodel(models.Model):\n file = models.FileField(blank...
[ 56, 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0005940308_django_django_forms_python.txt
Q: Python decorator with parameters, to run the functions multiple times? I want to write a python decorator to decorate a test function of a unittest.TestCase, to decide the target host this function should run against. See this example: class MyTestCase(unittest.TestCase): @target_host(["host1.com", "host2.com"...
Python decorator with parameters, to run the functions multiple times?
I want to write a python decorator to decorate a test function of a unittest.TestCase, to decide the target host this function should run against. See this example: class MyTestCase(unittest.TestCase): @target_host(["host1.com", "host2.com"]) def test_my_command(self): #do something here against the tar...
[ "You can return exactly one object (so technically, you could return a collections of functions). If you want to avoid astonishing everyone and if you want to call the result, you better return a single function though. But that function may very well call several other function in a loop... do you see where this l...
[ 11, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005940402_python.txt
Q: Pythonic way to do Ruby-like regular expression replace while evaluating the matched string I have this simple regexp replacement code with a block in it. When Ruby does the gsub the match is passed to the block and whatever is returned from the block is used as replacement. string = "/foo/bar.####.tif" string.gsu...
Pythonic way to do Ruby-like regular expression replace while evaluating the matched string
I have this simple regexp replacement code with a block in it. When Ruby does the gsub the match is passed to the block and whatever is returned from the block is used as replacement. string = "/foo/bar.####.tif" string.gsub(/#+/) { | match | "%0#{match.length}d" } # => "/foo/bar.%04d.tif" Is there a way to do this in...
[ "re.sub accepts a function as replacement. It gets the match object as sole parameter and returns the replacement string.\nIf you want to keep it a oneliner, a lambda will do work: re.sub(r'#+', lambda m: \"%0\"+str(len(m.group(0))), string). I'd just use a small three-line def to avoid having all those parens in o...
[ 8, 1 ]
[]
[]
[ "block", "coding_style", "python", "regex", "ruby" ]
stackoverflow_0005940567_block_coding_style_python_regex_ruby.txt
Q: Python return function error While running this function to validate captcha key and value i am not able to return it show error like this "AttributeError: 'bool' object has no attribute 'status_code'" def validate(request): id=request.GET.get('id','') key=request.GET.get('key','') captchavalue = mc.get(str(i...
Python return function error
While running this function to validate captcha key and value i am not able to return it show error like this "AttributeError: 'bool' object has no attribute 'status_code'" def validate(request): id=request.GET.get('id','') key=request.GET.get('key','') captchavalue = mc.get(str(id)) if captchavalue == key: ...
[ "By reading the code and the error, I assume that validate is a view. A view must always return a HttpResponse. So if you want to return a response indicating a boolean value, indicating if captchavalue == key, do:\nfrom django.http import HttpResponse\n\ndef validate(request):\n id=request.GET.get('id','')\n key=r...
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005940675_django_python.txt
Q: using two regular expressions to search a file Both my regular expressions work, what I am trying to do is have the first one read the file and print every time there is a match(this works) then when it finds a match for the second expression it prints a match for it. So in the file I am importing, it will match ...
using two regular expressions to search a file
Both my regular expressions work, what I am trying to do is have the first one read the file and print every time there is a match(this works) then when it finds a match for the second expression it prints a match for it. So in the file I am importing, it will match all the numbers then once it finds 'BREAK' it print ...
[ "The problem is that when you search for \"BREAK\" you are searching the whole text and not the text that appears after the number you found. Because of this, if the text has \"BREAK\" anywhere in it, it will always be found.\nIt seems like finditer() might not be the best thing to use for your situation. It would ...
[ 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005939380_python_regex.txt
Q: Compress a series of 1s and 0s into the shortest possible ascii string How could you convert a series of 1s and 0s into the shortest possible form consisting of URL safe ascii characters? eg. s = '00100101000101111010101' compress(s) Resulting in something like: Ysi8aaU And obviously: decompress(compress(s)) == s...
Compress a series of 1s and 0s into the shortest possible ascii string
How could you convert a series of 1s and 0s into the shortest possible form consisting of URL safe ascii characters? eg. s = '00100101000101111010101' compress(s) Resulting in something like: Ysi8aaU And obviously: decompress(compress(s)) == s (I ask this question purely out of curiousity)
[ "Here's the solution I came up with (+ far too many comments):\n# A set of 64 characters, which allows a maximum chunk length of 6 .. because\n# int('111111', 2) == 63 (plus zero)\ncharset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'\n\ndef encode(bin_string):\n # Split the string of 1s a...
[ 9, 6, 1 ]
[]
[]
[ "base64", "coffeescript", "compression", "python" ]
stackoverflow_0005940416_base64_coffeescript_compression_python.txt