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: What are your "must-have" Python Packages for Finance? With the recent SEC proposal requiring that most Asset-Backed Securities issuers file a python computer program to document the flow of funds (or waterfall) provisions of the transaction, I thought it timely to ask what you thought the "Must-Have" Python Packa...
What are your "must-have" Python Packages for Finance?
With the recent SEC proposal requiring that most Asset-Backed Securities issuers file a python computer program to document the flow of funds (or waterfall) provisions of the transaction, I thought it timely to ask what you thought the "Must-Have" Python Packages for Finance would be. PS: apart from answering here, ple...
[ "http://code.google.com/p/pandas/ is also developed with a quantitative finance background.\nI guess then the usual suspects:\n\nnumpy\nscipy\nrpy\nmatplotlib\n...\n\nFor my quant-development I usual start with pythonxy (http://www.pythonxy.com/) as a basis.\nIn the past I used also some python bindings for quantli...
[ 7, 6, 3, 3 ]
[]
[]
[ "finance", "python", "scientific_computing" ]
stackoverflow_0002870661_finance_python_scientific_computing.txt
Q: Need to get the uploaded file to my local PC I have created a test form which will ask users to enter a name and upload the image file: <html lang="en"> <head> <title>Testing image upload</title> </head> <body> <form action="/services/upload" method="POST" enctype="multipart/form-data"> File Descriptio...
Need to get the uploaded file to my local PC
I have created a test form which will ask users to enter a name and upload the image file: <html lang="en"> <head> <title>Testing image upload</title> </head> <body> <form action="/services/upload" method="POST" enctype="multipart/form-data"> File Description: <input name='fdesc' type='text'><br> File n...
[ "mod_python includes the FieldStorage class which allows you access to uploaded form data. In order to use it, you'd put something like the following in your Python script:\nreq.form = FieldStorage(req)\ndescription = req.form['fdesc']\n\nSince fdesc is a text input, description will be a string (more precisely, a ...
[ 1, 0, 0 ]
[]
[]
[ "file", "file_upload", "python", "upload" ]
stackoverflow_0002880475_file_file_upload_python_upload.txt
Q: How to think in Python after working in C++? I'm brand new to Python and trying to learn it by replicating the following C++ function into python // determines which words in a vector consist of the same letters // outputs the words with the same letters on the same line void equivalentWords(vector <string> words,...
How to think in Python after working in C++?
I'm brand new to Python and trying to learn it by replicating the following C++ function into python // determines which words in a vector consist of the same letters // outputs the words with the same letters on the same line void equivalentWords(vector <string> words, ofstream & outFile) { outFile << "Equivalent ...
[ "Keeping things simple, this is O(N) complexity and should be sufficient if you don't have GBs of word data. Note that set() and dict() basically is a hashed index (free and builtin!).\nindex = {}\nfor word, s_word in words:\n index[s_word] = index.get(s_word, []) + [word]\n\nfor similar_words in index.values():...
[ 5, 3, 3, 1, 0, 0, 0 ]
[]
[]
[ "c++", "python" ]
stackoverflow_0002879055_c++_python.txt
Q: Python: When passing variables between methods, is it necessary to assign it a new name? I'm thinking that the answer is probably 'no' if the program is small and there are a lot of methods, but what about in a larger program? If I am going to be using one variable in multiple methods throughout the program, is it...
Python: When passing variables between methods, is it necessary to assign it a new name?
I'm thinking that the answer is probably 'no' if the program is small and there are a lot of methods, but what about in a larger program? If I am going to be using one variable in multiple methods throughout the program, is it smarter to: Come up with a different phrasing for each method (to eliminate naming conflicts)...
[ "When passing variables between methods ... there are no naming conflicts, since the variable is local in each method, the same name in both methods eliminates confusion.\ndef printIt(num):\n print(num)\n\ndef f():\n num = 2\n printIt(num)\n\n", "I tend to reuse variable names in local functions a lot, a...
[ 4, 3, 2, 1, 1, 1 ]
[]
[]
[ "coding_style", "methods", "python" ]
stackoverflow_0002886048_coding_style_methods_python.txt
Q: Testing Django Inline ModelForms: How to arrange POST data? I have a Django 'add business' view which adds a new business with an inline 'business_contact' form. The form works fine, but I'm wondering how to write up the unit test - specifically, the 'postdata' to send to self.client.post(settings.BUSINESS_ADD_URL...
Testing Django Inline ModelForms: How to arrange POST data?
I have a Django 'add business' view which adds a new business with an inline 'business_contact' form. The form works fine, but I'm wondering how to write up the unit test - specifically, the 'postdata' to send to self.client.post(settings.BUSINESS_ADD_URL, postdata) I've inspected the fields in my browser and tried add...
[ "The problem is you have not included the management form in your data. You need to include form-TOTAL_FORMS (total number of forms in the formset, default is 2), form-INITIAL_FORMS (the initial number of forms in the formset, default is 0) and form-MAX_NUM_FORMS (the maximum number of forms in the formset, defaul...
[ 3 ]
[]
[]
[ "django", "inline", "python", "testing" ]
stackoverflow_0002887464_django_inline_python_testing.txt
Q: combine lines from 2 prints to single line and insert into mysql database Hello everyone i currently have this: import feedparser d = feedparser.parse('http://store.steampowered.com/feeds/news.xml') for i in range(10): print d.entries[i].title print d.entries[i].date How would i go about making it so tha...
combine lines from 2 prints to single line and insert into mysql database
Hello everyone i currently have this: import feedparser d = feedparser.parse('http://store.steampowered.com/feeds/news.xml') for i in range(10): print d.entries[i].title print d.entries[i].date How would i go about making it so that the title and date are on the same line? Also it doesn't need to print i just...
[ "If you want to print on the same line, just add a comma:\nprint d.entries[i].title, # <- comma here\nprint d.entries[i].date\n\nTo insert to MySQL, you'd do something like this:\nto_db = []\nfor i in range(10):\n to_db.append((d.entries[i].title, d.entries[i].date))\n\nimport MySQLdb\nconn = MySQLdb.connect(hos...
[ 2, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0002887688_mysql_python.txt
Q: Python regex on list I am trying to build a parser and save the results as an xml file but i have problems.. Would you experts please have a look at my code ? Traceback :TypeError: expected string or buffer import urllib2, re from xml.dom.minidom import Document from BeautifulSoup import BeautifulSoup as bs osc =...
Python regex on list
I am trying to build a parser and save the results as an xml file but i have problems.. Would you experts please have a look at my code ? Traceback :TypeError: expected string or buffer import urllib2, re from xml.dom.minidom import Document from BeautifulSoup import BeautifulSoup as bs osc = open('OSCTEST.html','r') ...
[ "It's good that you're trying to using BeautifulSoup to parse HTML but this won't work:\nre.compile('<h1 class=\"title metadata_title content_perceived_text(.*?)`</h1>',\n re.DOTALL | re.IGNORECASE).findall(soup)\n\nYou're trying to parse a BeautifulSoup object using a regular expression. Instead you shou...
[ 5 ]
[]
[]
[ "parsing", "python", "xml" ]
stackoverflow_0002887769_parsing_python_xml.txt
Q: Random function in Python How can I use the random function (in Python) to choose a string from a txt list? i want random from a list : import random import sys filename = sys.argv[1] f = open(filename) f.close() print random.choice(f) is this code ok ? A: > import random > list_of_strings = open(sys.argv[1]...
Random function in Python
How can I use the random function (in Python) to choose a string from a txt list? i want random from a list : import random import sys filename = sys.argv[1] f = open(filename) f.close() print random.choice(f) is this code ok ?
[ "> import random\n> list_of_strings = open(sys.argv[1]).readlines()\n> randomly_chosen_string = random.choice(list_of_strings)\n> help(random.choice)\nHelp on method choice in module random:\n\nchoice(self, seq) method of random.Random instance\nChoose a random element from a non-empty sequence.\n\n", "import ran...
[ 3, 1 ]
[]
[]
[ "function", "python", "random" ]
stackoverflow_0002886716_function_python_random.txt
Q: Object-oriented GUI development in python Hey guys, new programmer here. I have an assignment for class and I'm stuck... What I need to do is a create a GUI that gives someone a basic arithmetic problem in one box, asks the person to answer it, evaluates it, and tells you if you're right or wrong... Basically, wh...
Object-oriented GUI development in python
Hey guys, new programmer here. I have an assignment for class and I'm stuck... What I need to do is a create a GUI that gives someone a basic arithmetic problem in one box, asks the person to answer it, evaluates it, and tells you if you're right or wrong... Basically, what I have is this: class Lesson(Frame): def...
[ "Do you want to change the Label or the contents of the Entry? I'll assume the latter. The short answer is\nent.delete(0, END)\nent.insert(END, 'stringy thing')\n\nbut nothing is going to change in the interface until the Tk() instance mainloop() method is called.\n", "Change the \ntext=\"\"\n\nin the Label objec...
[ 0, 0 ]
[]
[]
[ "oop", "python", "user_interface" ]
stackoverflow_0002886938_oop_python_user_interface.txt
Q: Need help/guidance about creating a desktop application with gui I'm planning to do an Desktop application using Python, to learn some Desktop concepts. I'm going to use GTK or Qt, I still haven't decided which one. Fact is: I would like to create an application with the possibility to be called from command line,...
Need help/guidance about creating a desktop application with gui
I'm planning to do an Desktop application using Python, to learn some Desktop concepts. I'm going to use GTK or Qt, I still haven't decided which one. Fact is: I would like to create an application with the possibility to be called from command line, AND using a GUI. So it would be useful for cmd fans, and GUI users as...
[ "Decoupling the presentation layer from application logic makes it possible!.\nYou can divide your application into layers, a layer is a reusable portion of code that performs a specific function.\nFor example, you can divide the application into two or more layers, one layer with the presentation of the applicati...
[ 1, 1 ]
[]
[]
[ "cross_platform", "gtk", "python", "qt" ]
stackoverflow_0002860835_cross_platform_gtk_python_qt.txt
Q: Reading a series of input / output in Python For my app, I need to print out a series of outputs and then accepts inputs from the user. What would be the best way of doing this? Like: print '1' x = raw_input() print '2' y = raw_input() Something like this, but it would go on for at least 10 times. My only concer...
Reading a series of input / output in Python
For my app, I need to print out a series of outputs and then accepts inputs from the user. What would be the best way of doing this? Like: print '1' x = raw_input() print '2' y = raw_input() Something like this, but it would go on for at least 10 times. My only concern with doing the above is that it would make up fo...
[ "First one note: raw_input() takes an optional argument ... a prompt string.\nRegarding the broader question, a simplistic approach would be to create a class which defines the elements of your form and provides the functions for their input, validation, and later manipulations or output.\nWith such a class instan...
[ 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002887767_python.txt
Q: Where is a good place/way to store Windows config files for Python scripts? I have a script/program I am working on that requires a configuration file (I am using ConfigParser). On linux, I will default to store these variables in ~/.myscript using the os.getenv('HOME') function. With Windows, I know I can use ...
Where is a good place/way to store Windows config files for Python scripts?
I have a script/program I am working on that requires a configuration file (I am using ConfigParser). On linux, I will default to store these variables in ~/.myscript using the os.getenv('HOME') function. With Windows, I know I can use os.getenv('USERPROFILE') to find the User's "home" directory, however, is it a go...
[ "os.environ['AppData']\n\nIt's usual to create a folder inside with your organisation name and put any files inside that. There's no need to ‘hide’ the files, and . at the start of a filename isn't valid in Windows.\nOr put the settings in the registry.\n" ]
[ 2 ]
[]
[]
[ "configparser", "configuration", "python", "windows" ]
stackoverflow_0002888100_configparser_configuration_python_windows.txt
Q: Django Import Error with URLS and ROOT_URLCONF confusion In httpd conf, <VirtualHost *:8080> ServerName tweet_search_engine DocumentRoot /var/www/microblogsearchengine/twingle </VirtualHost> <Directory /var/www/microblogsearchengine/twingle> SetHandler python-program PythonHandler django.core.handlers...
Django Import Error with URLS and ROOT_URLCONF confusion
In httpd conf, <VirtualHost *:8080> ServerName tweet_search_engine DocumentRoot /var/www/microblogsearchengine/twingle </VirtualHost> <Directory /var/www/microblogsearchengine/twingle> SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE settings PythonOp...
[ "Typo in your PythonOption line:\ndjango.rooti instead of django.root\nFurthermore you might have to add something like this inside your Directory section:\nPythonPath \"['/var/www/microbloggingsearchengine','/var/www/microbloggingsearchengine/twingle'] + sys.path\"\n\n" ]
[ 3 ]
[]
[]
[ "django", "python", "url" ]
stackoverflow_0002888179_django_python_url.txt
Q: Django - markup parser in template or view? I am building a website where my pages are written in MediaWiki Markup, for which I have a working parser function in Python. Where exactly do I parse my markup: in the view's code, or in the template? My first guess would be something like: return render_to_response( 'b...
Django - markup parser in template or view?
I am building a website where my pages are written in MediaWiki Markup, for which I have a working parser function in Python. Where exactly do I parse my markup: in the view's code, or in the template? My first guess would be something like: return render_to_response( 'blog/post.html', {'post': post, ...
[ "The general rule for deciding whether or not to place your code in the view or the template is this:\n\nIf your code is going to modify the\n data, put it into the view. If your\n code will only effect the display of\n the data, put it into the template.\n\nI'm not very familiar with the markup formatting, but ...
[ 3 ]
[]
[]
[ "django", "django_templates", "django_views", "python" ]
stackoverflow_0002888142_django_django_templates_django_views_python.txt
Q: Getting two characters from string in python how to get in python from string not one character, but two? I have: long_str = 'abcd' for c in long_str: print c and it gives me like a b c d but i need to get ab cd I'm new in python.. is there any way? A: You can use slice notation. long_str[x:y] will give y...
Getting two characters from string in python
how to get in python from string not one character, but two? I have: long_str = 'abcd' for c in long_str: print c and it gives me like a b c d but i need to get ab cd I'm new in python.. is there any way?
[ "You can use slice notation. long_str[x:y] will give you characters in the range [x, y) (where x is included and y is not).\n>>> for i in range(0, len(long_str) - 1, 2):\n... print long_str[i:i+2]\n... \nab\ncd\n\nHere I am using the three-argument range operator to denote start, end, and step (see http://docs.p...
[ 13, 7 ]
[]
[]
[ "character", "for_loop", "loops", "python" ]
stackoverflow_0002888281_character_for_loop_loops_python.txt
Q: information hiding in python in python tutorial added that python cannot hide its attributes from other classes. some thing such as private data in C++ or java..But also i know that we can use _ or __ to set some variables as privated one but it is not enogh. I think it is a weak if it is not any thing to do it. ...
information hiding in python
in python tutorial added that python cannot hide its attributes from other classes. some thing such as private data in C++ or java..But also i know that we can use _ or __ to set some variables as privated one but it is not enogh. I think it is a weak if it is not any thing to do it.
[ "Data encapsulation in Python is enforced by convention and peer review. Surprisingly, having every attribute effectively be public hasn't caused a problem for the majority of Python programmers.\n", "Using an underscore at the start of the name for an element or a method signals to the reader that what they're ...
[ 4, 4, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002888035_python.txt
Q: Huffman coding two characters as one I need huffman code(best in python or in java), which could encode text not by one character (a = 10, b = 11), but by two (ab = 11, ag = 10). Is it possible and if yes, where could i find it, maybe it's somewhere in the internet and i just can'd find it? A: Huffman code doesn...
Huffman coding two characters as one
I need huffman code(best in python or in java), which could encode text not by one character (a = 10, b = 11), but by two (ab = 11, ag = 10). Is it possible and if yes, where could i find it, maybe it's somewhere in the internet and i just can'd find it?
[ "Huffman code doesn't care about characters, it cares about symbols. Generally, it is used to encode the alphabet / other single characters, but can very easily be generalized to encode strings of characters. Basically, you would just take an existing implementation and allow symbols to be strings rather than cha...
[ 6, 1, 0 ]
[]
[]
[ "huffman_code", "java", "python" ]
stackoverflow_0002888468_huffman_code_java_python.txt
Q: sqlite3.OperationalError The "python manage.py syncdb" command is giving me the following error: sqlite3.OperationalError: unable to open database file I'm following the step by step instructions in Practical Django Projects, so I think this has to do something with the Windows Operating system acting quirky! Th...
sqlite3.OperationalError
The "python manage.py syncdb" command is giving me the following error: sqlite3.OperationalError: unable to open database file I'm following the step by step instructions in Practical Django Projects, so I think this has to do something with the Windows Operating system acting quirky! Things I've checkde: 1.The path...
[ "You haven't shown exactly how the path is represented in your settings.py file. But if you've done it how you show here, it won't work. You need to use forward slashes (/) or double backwards slashes (\\\\).\nThis is because in Python a backslash usually means to escape the following character.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002888326_django_python.txt
Q: Do something every 3 loops in django-templates? I wanna make change in css class every 3 loops. In the first three I want to use the CSS class A, in the next three I want to use the CSS class B, in the next three I want to use the CSS class A again and so on. can anyone help? Thanks A: {% cycle "A" "A" "A" "B" "...
Do something every 3 loops in django-templates?
I wanna make change in css class every 3 loops. In the first three I want to use the CSS class A, in the next three I want to use the CSS class B, in the next three I want to use the CSS class A again and so on. can anyone help? Thanks
[ "{% cycle \"A\" \"A\" \"A\" \"B\" \"B\" \"B\" %}\n\n" ]
[ 3 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0002888598_django_django_templates_python.txt
Q: how to pass in dynamic data to decorators I am trying to write a base crud controller class that does the following: class BaseCrudController: model = "" field_validation = {} template_dir = "" @expose(self.template_dir) def new(self, *args, **kwargs) .... @validate(self.field_val...
how to pass in dynamic data to decorators
I am trying to write a base crud controller class that does the following: class BaseCrudController: model = "" field_validation = {} template_dir = "" @expose(self.template_dir) def new(self, *args, **kwargs) .... @validate(self.field_validation, error_handler=new) @expose() d...
[ "Perhaps using a factory to create the class would be better than subclassing:\ndef CrudControllerFactory(model, field_validation, template_dir):\n class BaseCrudController:\n @expose(template_dir)\n def new(self, *args, **kwargs)\n ....\n\n @validate(field_validation, error_handl...
[ 1, 0 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0002884771_decorator_python.txt
Q: How to Redirect a Python Console output to a QTextBox I'm working on developing a GUI for the recompilation of Linux kernel. For this I need to implement 4-5 Linux commands from Python. I use Qt as GUI designer. I have successfully implemented the commands using os.system() call. But the output is obtained at the...
How to Redirect a Python Console output to a QTextBox
I'm working on developing a GUI for the recompilation of Linux kernel. For this I need to implement 4-5 Linux commands from Python. I use Qt as GUI designer. I have successfully implemented the commands using os.system() call. But the output is obtained at the console. The real problem is the output of command is a l...
[ "self.process = QProcess()\nself.connect(self.process, SIGNAL(\"readyReadStdout()\"), self.readOutput)\nself.connect(self.process, SIGNAL(\"readyReadStderr()\"), self.readErrors)\ntarsourcepath=\"sudo tar xvpf \"+ self.path1\nself.process.setArguments(QStringList.split(\" \",tarsourcepath))\nself.process.start()\n\...
[ 7, 1, 0 ]
[]
[]
[ "console", "python", "qwidget", "redirect" ]
stackoverflow_0002859256_console_python_qwidget_redirect.txt
Q: Python handwriting recognition software? Is there a Python handwriting recognition library? What are the inputs to hand writing recognition packages, .jpg images? .pdf images? A: Zinnia is a C/C++ library with SWIG generated wrappers for Perl/Python/Ruby. It has a BSD license and converts user pen strokes prov...
Python handwriting recognition software?
Is there a Python handwriting recognition library? What are the inputs to hand writing recognition packages, .jpg images? .pdf images?
[ "Zinnia is a C/C++ library with SWIG generated wrappers for Perl/Python/Ruby. It has a BSD license and converts user pen strokes provided as coordinates into character best matches. It also has a training module.\nIt looks like it performs single character recognition, so you might need to build something on top of...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0002888613_python.txt
Q: Help Me: Loading Qt dialogs from python Scripts im a novice into developing an application using backend as Python (2.5) and Qt(3) as front end GUI designer. I have 5 diffrent dialogs to implement the scripts. i just know to load the window (main window) from qt import * from dialogselectkernelfile import...
Help Me: Loading Qt dialogs from python Scripts
im a novice into developing an application using backend as Python (2.5) and Qt(3) as front end GUI designer. I have 5 diffrent dialogs to implement the scripts. i just know to load the window (main window) from qt import * from dialogselectkernelfile import * from formcopyextract import * import sys ...
[ "Are you connecting the button click signals to handler functions?\nIf you are able to get one dialog to open, getting the other dialogs to open should be as simple as instantiating the new dialog and calling the .show() method in the first dialog's button handler.\nMaybe you could upload your code somewhere so we ...
[ 0, 0 ]
[]
[]
[ "dialog", "editing", "python", "qt", "signals" ]
stackoverflow_0002844365_dialog_editing_python_qt_signals.txt
Q: What framework is trac based on? I just downloaded this tracking system and curious what framework this great system uses? A: Trac does not use any overarching external "framework". You can see its complete list of external dependencies (beyond a Python interpreter itself) in the setup.py file from the distribut...
What framework is trac based on?
I just downloaded this tracking system and curious what framework this great system uses?
[ "Trac does not use any overarching external \"framework\". You can see its complete list of external dependencies (beyond a Python interpreter itself) in the setup.py file from the distribution:\n install_requires = [\n 'setuptools>=0.6b1',\n 'Genshi>=0.6',\n ],\n extras_require = {\n ...
[ 9 ]
[]
[]
[ "frameworks", "python", "trac" ]
stackoverflow_0002888879_frameworks_python_trac.txt
Q: Nested navigation menu using a recursive Python function I want to render this data structure as an unordered list. menu = [ [1, 0], [2, 1], [3, 1], [4, 3], [5, 3], [6, 5], [7,1] ] [n][0] is the key [n][1] references the ...
Nested navigation menu using a recursive Python function
I want to render this data structure as an unordered list. menu = [ [1, 0], [2, 1], [3, 1], [4, 3], [5, 3], [6, 5], [7,1] ] [n][0] is the key [n][1] references the parent key The desired output is: <ul> <li>Node 1</li> <ul> ...
[ "def render(nodes, parent = 0):\n if parent not in nodes:\n return\n print('<ul>')\n for n in nodes[parent]:\n print('<li>Node %d</li>' % n)\n render(nodes, n)\n print('</ul>')\n\nHere is the output\n>>> nodes = {}\n>>> for n in menu:\n if n[1] not in nodes:\n nodes[n[1]] ...
[ 3, 2 ]
[]
[]
[ "menu", "navigation", "python", "recursion" ]
stackoverflow_0002888810_menu_navigation_python_recursion.txt
Q: What exactly is a web application framework? I'm getting into python for cgi and came across Django. I'm not quite sure I understand it very much. Is it something I have to install inside apache or is it just something I can use with my cgi? Wanted to know because I'd love to learn it but my server I'm using doesn...
What exactly is a web application framework?
I'm getting into python for cgi and came across Django. I'm not quite sure I understand it very much. Is it something I have to install inside apache or is it just something I can use with my cgi? Wanted to know because I'd love to learn it but my server I'm using doesn't give me a lot of privileges. thanks
[ "While you could run a Python web framework on top of CGI, I don't think you want to: a web framework provides you with lots of extra functionality to make your coding easier, but part of the price you pay for that is that the framework has lots of extra code to supply that functionality -- that code needs to get l...
[ 4, 0, 0, 0 ]
[]
[]
[ "cgi", "django", "python", "web_frameworks" ]
stackoverflow_0002886466_cgi_django_python_web_frameworks.txt
Q: Errno socket error in python i wrote this code : import random import sys import urllib openfile = open(sys.argv[1]).readlines() c = random.choice(openfile) i = 0 while i < 5: i=i+1 c = random.choice(openfile) proxies = {'http': c} opener = urllib.FancyURLopener(proxies).open("http://whatismyip.com.au/").read...
Errno socket error in python
i wrote this code : import random import sys import urllib openfile = open(sys.argv[1]).readlines() c = random.choice(openfile) i = 0 while i < 5: i=i+1 c = random.choice(openfile) proxies = {'http': c} opener = urllib.FancyURLopener(proxies).open("http://whatismyip.com.au/").read() ::: I put 3 proxy in a txt fil...
[ "The first proxy you list is giving my telnet an ECONNRESET too. What makes you think these are valid proxies?\nIncidentally, if you are trying to find out their DNS names, they don't have any.\n$ dig -x 211.161.159.74 \n;; connection timed out; no servers could be reached\n\n" ]
[ 2 ]
[]
[]
[ "proxy", "python", "sockets", "urllib" ]
stackoverflow_0002888973_proxy_python_sockets_urllib.txt
Q: Mutate an object into an instance of one its subclasses Is it possible to mutate an object into an instance of a derived class of the initial's object class? Something like: class Base(): def __init__(self): self.a = 1 def mutate(self): self = Derived() class Derived(Base): def __init...
Mutate an object into an instance of one its subclasses
Is it possible to mutate an object into an instance of a derived class of the initial's object class? Something like: class Base(): def __init__(self): self.a = 1 def mutate(self): self = Derived() class Derived(Base): def __init__(self): self.b = 2 But that doesn't work. >>> obj ...
[ "Responding to the original question as posed, changing the mutate method to:\ndef mutate(self):\n self.__class__ = Derived\n\nwill do exactly what was requested -- change self's class to be Derived instead of Base. This does not automatically execute Derived.__init__, but if that's desired it can be explicitly...
[ 7, 6, 1, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0002887643_oop_python.txt
Q: Why is my code shown as messy while it isn't? class sss(webapp.RequestHandler): def get(self): url = "http://www.google.com/" result = urlfetch.fetch(url) if result.status_code == 200: self.response.out.write(result.content) When I change code to this: if result.status_code == 200: ...
Why is my code shown as messy while it isn't?
class sss(webapp.RequestHandler): def get(self): url = "http://www.google.com/" result = urlfetch.fetch(url) if result.status_code == 200: self.response.out.write(result.content) When I change code to this: if result.status_code == 200: self.response.out.write(result.content.decode('u...
[ "Google is probably serving you ISO-8859-1. At least, that is what they serve me for the User-Agent \"AppEngine-Google; (+http://code.google.com/appengine)\" (which urlfetch uses). The Content-Type header value is:\ntext/html; charset=ISO-8859-1\n\nSo you would use:\nresult.content.decode('ISO-8859-1')\n\nIf you ...
[ 3, 1 ]
[]
[]
[ "encode", "google_app_engine", "python", "urlfetch" ]
stackoverflow_0002887734_encode_google_app_engine_python_urlfetch.txt
Q: finding a solution to a giving maze txt.file how can i fix this program, the problem is when it print out the coordinate it give me a 7 for the start and finish, i would appreciated you help, thanks start = (len(data)) finish = (len(data)) pos= [] for i in range(len(pos)): for j in range(len(pos[i])): ...
finding a solution to a giving maze txt.file
how can i fix this program, the problem is when it print out the coordinate it give me a 7 for the start and finish, i would appreciated you help, thanks start = (len(data)) finish = (len(data)) pos= [] for i in range(len(pos)): for j in range(len(pos[i])): if pos[i][j] == "S": start=(i,j) ...
[ "Look at the start of your code:\nstart = (len(data))\nfinish = (len(data))\npos= []\nfor i in range(len(pos)):\n\nlen(pos) is zero, of course (you've just assigned the empty list to pos, so what else could that length possibly be but 0?!), so the loop executes zero times, start and finish never change, and what yo...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0002889073_python.txt
Q: How to verify object creation in Django? I want to verify that the object I created was really created, and return True or False according to that: obj = object(name='plop') try: obj.save() return True except ???: return False How can object creation be verified? A: First of all - that's a not good practice...
How to verify object creation in Django?
I want to verify that the object I created was really created, and return True or False according to that: obj = object(name='plop') try: obj.save() return True except ???: return False How can object creation be verified?
[ "First of all - that's a not good practice that you are doing\n2nd the only case when exception can happen is database connection fail or some constrains or required required fields not set.. in that case db-backend.OperationalError is raised\nUpdate: on constrains fail there is a IntegrityError exception\n", "sa...
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002889523_django_python.txt
Q: Creating collaborative whiteboard drawing application I have my own drawing program in place, with a variety of "drawing tools" such as Pen, Eraser, Rectangle, Circle, Select, Text etc. It's made with Python and wxPython. Each tool mentioned above is a class, which all have polymorphic methods, such as left_down()...
Creating collaborative whiteboard drawing application
I have my own drawing program in place, with a variety of "drawing tools" such as Pen, Eraser, Rectangle, Circle, Select, Text etc. It's made with Python and wxPython. Each tool mentioned above is a class, which all have polymorphic methods, such as left_down(), mouse_motion(), hit_test() etc. The program manages a lis...
[ "Making any real-time collaborative tool/game boils down to efficiently synchronizing changes on a minimal shared data structure between clients. Network bandwidth is the bottleneck. Send only information absolutely needed to synchronize the shared data. You are on the right track by storing shapes instead of indiv...
[ 14 ]
[]
[]
[ "paint", "python", "twisted", "whiteboard", "wxpython" ]
stackoverflow_0002889363_paint_python_twisted_whiteboard_wxpython.txt
Q: Python: How can I subclass a class I'm nesting in? I am trying to do the following in a bit of python code: class Parent: class Child(Parent): pass And it does not work. Is there any python syntax I can use to achieve the same result? Thanks. A: You can't do that because at the point where Child is...
Python: How can I subclass a class I'm nesting in?
I am trying to do the following in a bit of python code: class Parent: class Child(Parent): pass And it does not work. Is there any python syntax I can use to achieve the same result? Thanks.
[ "You can't do that because at the point where Child is being defined, Parent is not defined yet (definition in progress). Nested classes are not usually used in Python, you can just declare different classes in the same module. However, if you absolutely need to achieve the outlined setup, you can do this:\nclass...
[ 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002889739_python.txt
Q: Returning JSON from JavaScript to Python I'm writing a simple App Engine app. I have a simple page that allows a user to move a marker on a Google map instance. Each time the user drops the marker, I want to return the long/lat to my Python app. function initialize() { ... // Init map var marker = new GMarke...
Returning JSON from JavaScript to Python
I'm writing a simple App Engine app. I have a simple page that allows a user to move a marker on a Google map instance. Each time the user drops the marker, I want to return the long/lat to my Python app. function initialize() { ... // Init map var marker = new GMarker(center, {draggable: true}); GEvent.addList...
[ "The way to prevent a page reload is to handle this with AJAX on the web page side.\nUsing jquery, you might do something like this:\n$(\"#testform\").submit(function() {\n // post the form values via AJAX...\n var postdata = {lat: $(\"#lat\").val(), long: $(\"#long\").val()} ;\n $.post('/submit', postdata...
[ 7, 1 ]
[]
[]
[ "google_app_engine", "javascript", "python" ]
stackoverflow_0002796736_google_app_engine_javascript_python.txt
Q: How to extract comment out of header file using python, perl, or sed? I have a header file like this: /* * APP 180-2 ALG-254/258/772 implementation * Last update: 03/01/2006 * Issue date: 08/22/2004 * * Copyright (C) 2006 Somebody's Name here * All rights reserved. * * Redistribution and use in source and...
How to extract comment out of header file using python, perl, or sed?
I have a header file like this: /* * APP 180-2 ALG-254/258/772 implementation * Last update: 03/01/2006 * Issue date: 08/22/2004 * * Copyright (C) 2006 Somebody's Name here * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that...
[ "This should work for you:\nsed -n '/\\*\\//q; /^\\/\\*/d; s/^ \\* \\?//p' <file.h >comment.txt\n\nHere's an explanation: sed (as you may know) is a command that goes through a file applying a list of rules to each line. Each rule consists of a \"selector\" and commands that are applied to that line only if the sel...
[ 5, 4 ]
[ "sed -i -r \"s/[\\/\\ ]{1}\\*[\\/\\ ]?//g\" YOURFILENAME\n\nThis replaces trims comments from your file, keeping the content. This will modify YOURFILENAME file though. If you don't want that remove -i from the line\n" ]
[ -1 ]
[ "c++", "extraction", "perl", "python", "sed" ]
stackoverflow_0002889771_c++_extraction_perl_python_sed.txt
Q: How Can I: Generate 40/64 Bit WEP Key In Python? So, I've been beating my head against the wall of this issue for several months now, partly because it's a side interest and partly because I suck at programming. I've searched and researched all across the web, but have not had any luck (except one small bit of suc...
How Can I: Generate 40/64 Bit WEP Key In Python?
So, I've been beating my head against the wall of this issue for several months now, partly because it's a side interest and partly because I suck at programming. I've searched and researched all across the web, but have not had any luck (except one small bit of success; see below), so I thought I might try asking the ...
[ "That C code you linked to would have been awfully helpful to include in the question ;-) Anyway, I went ahead and translated it into Python. Before you read it, let me say that I highly encourage you to try it yourself and only use my transcription as a guide. Translating algorithms from one programming language t...
[ 5, 1 ]
[]
[]
[ "python", "wep", "xor" ]
stackoverflow_0002890438_python_wep_xor.txt
Q: How to map one class against multiple tables with SQLAlchemy? Lets say that I have a database structure with three tables that look like this: items - item_id - item_handle attributes - attribute_id - attribute_name item_attributes - item_attribute_id - item_id - attribute_id - attribute_value I would l...
How to map one class against multiple tables with SQLAlchemy?
Lets say that I have a database structure with three tables that look like this: items - item_id - item_handle attributes - attribute_id - attribute_name item_attributes - item_attribute_id - item_id - attribute_id - attribute_value I would like to be able to do this in SQLAlchemy: item = Item('item1') item....
[ "This is called the entity-attribute-value pattern. There is an example about this under the SQLAlchemy examples directory: vertical/.\nIf you are using PostgreSQL, then there is also the hstore contrib module that can store a string to string mapping. If you are interested then I have some code for a custom type t...
[ 8, 6 ]
[]
[]
[ "database", "database_design", "python", "sqlalchemy" ]
stackoverflow_0001300433_database_database_design_python_sqlalchemy.txt
Q: AppEngine dev_appserver.py aborts with no error message I have an app which works well live on AppEngine. However, when I try to run it locally with the dev_appserver.py, it aborts within ~1 second with: ~/ dev_appserver.py --debug_imports myapp /opt/local/share/google_appengine/google/appengine/api/datastore_...
AppEngine dev_appserver.py aborts with no error message
I have an app which works well live on AppEngine. However, when I try to run it locally with the dev_appserver.py, it aborts within ~1 second with: ~/ dev_appserver.py --debug_imports myapp /opt/local/share/google_appengine/google/appengine/api/datastore_file_stub.py:40: DeprecationWarning: the md5 module is deprec...
[ "Edit: the answer below is potentially no longer relevant depending on individual use-case as Python 2.7 is now supported on App Engine.\n\nApp Engine only works with Python 2.5.x\nInstall 2.5, and run explicitly.\nFor example:\n\npython2.5 /path/to/dev_appserver.py myapp\n\n", "I had the same problem, it seems t...
[ 4, 1 ]
[]
[]
[ "django", "google_app_engine", "macos", "python" ]
stackoverflow_0002624686_django_google_app_engine_macos_python.txt
Q: In Ruby or Python can the very concept of Class be rewritten? first time at stack overflow. I'm looking into using some of the metaprogramming features provided by Ruby or Python, but first I need to know the extent to which they will allow me to extend the language. The main thing I need to be able to do is to r...
In Ruby or Python can the very concept of Class be rewritten?
first time at stack overflow. I'm looking into using some of the metaprogramming features provided by Ruby or Python, but first I need to know the extent to which they will allow me to extend the language. The main thing I need to be able to do is to rewrite the concept of Class. This doesn't mean that I want to rewr...
[ "Sounds like duck typing to me. Just declare the methods you want and remember that it's easier to ask forgiveness than permission:\ntry:\n poodle.wear()\nexcept (AttributeError, TypeError):\n pass\n\n", "I agree with Samir that it just sounds like duck typing. You don't need to care what 'type' an object r...
[ 8, 7, 6, 2, 1 ]
[]
[]
[ "class", "metaprogramming", "ontology", "python", "ruby" ]
stackoverflow_0002890229_class_metaprogramming_ontology_python_ruby.txt
Q: Is there really no binary distribution of MySQLdb for Windows? You have to build it yourself? Or am I missing something. A: There are, however, oursql binaries for Windows. Read about oursql here. A: There's no "official" binary, but I found some on this site (for 2.6 32 or 64 bit, or 2.5 64 bit) via the MySQL...
Is there really no binary distribution of MySQLdb for Windows?
You have to build it yourself? Or am I missing something.
[ "There are, however, oursql binaries for Windows. Read about oursql here.\n", "There's no \"official\" binary, but I found some on this site (for 2.6 32 or 64 bit, or 2.5 64 bit) via the MySQLdb page on Pypi. Also, this blog has instructions on how to build MySQLdb on Windows if you're feeling up to the task.\n"...
[ 2, 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0002890551_mysql_python.txt
Q: How to generate graphs and statistics from SQLAlchemy tables? After running a bunch of simulations I'm going to be outputting the results into a table created using SQLAlchemy. I plan to use this data to generate statistics - mean and variance being key. These, in turn, will be used to generate some graphs - histo...
How to generate graphs and statistics from SQLAlchemy tables?
After running a bunch of simulations I'm going to be outputting the results into a table created using SQLAlchemy. I plan to use this data to generate statistics - mean and variance being key. These, in turn, will be used to generate some graphs - histograms/line graphs, pie-charts and box-and-whisker plots specificall...
[ "It looks like matplotlib takes simple python data types -- lists of numbers, etc, so you'll be need to write custom code to massage what you pull out of mysql/sqlalchemy for input into the graphing functions...\n" ]
[ 1 ]
[]
[]
[ "matplotlib", "python", "sqlalchemy" ]
stackoverflow_0002890564_matplotlib_python_sqlalchemy.txt
Q: Why program with php frameworks if it can be done better with ruby on rails, python or java? We have discussion in my job place about question (We use 1 of the php frameworks): Why program with php frameworks big web application if it can be done better with ruby on rails, python or java? Please say our opinion t...
Why program with php frameworks if it can be done better with ruby on rails, python or java?
We have discussion in my job place about question (We use 1 of the php frameworks): Why program with php frameworks big web application if it can be done better with ruby on rails, python or java? Please say our opinion thanks
[ "If you only know PHP and you don't feel like learning Ruby/Python/Java. Seriously, if it can be done better with another tool, it should be done with another tool. Of course, this assumes the other tools are actually better. That part is arguable. Some people are so stuck up on their \"my way is the best way\" tha...
[ 3, 2 ]
[]
[]
[ "django", "java", "php", "python", "ruby_on_rails" ]
stackoverflow_0002891017_django_java_php_python_ruby_on_rails.txt
Q: Reading lines including space I want to read file including spaces in each lines My current code def data(): f = open("save.aln") for line in f.readlines(): print "</br>" print line I am using python and output embedded in html File to be read - http://pastebin.com/EaeKsyvg Thanks A: It seems that y...
Reading lines including space
I want to read file including spaces in each lines My current code def data(): f = open("save.aln") for line in f.readlines(): print "</br>" print line I am using python and output embedded in html File to be read - http://pastebin.com/EaeKsyvg Thanks
[ "It seems that your problem is that you need space preserving in HTML. The simple solution would be to put your output between <pre> elemenets\ndef data(): \n print \"<pre>\"\n f = open(\"save.aln\") \n for line in f.readlines(): \n print line\n print \"</pre>\"\n\nNote that in this case you don'...
[ 2, 1, 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0002890988_file_io_python.txt
Q: Using a dictionary to assign misspelled words to its line number This is the code I currently have: from collections import defaultdict goodwords = set() with open("soccer.txt", "rt") as f: for word in f.readlines(): goodwords.add(word.strip()) badwords = defaultdict(list) with open("soccer.txt", ...
Using a dictionary to assign misspelled words to its line number
This is the code I currently have: from collections import defaultdict goodwords = set() with open("soccer.txt", "rt") as f: for word in f.readlines(): goodwords.add(word.strip()) badwords = defaultdict(list) with open("soccer.txt", "rt") as f: for line_no, line in enumerate(f): for word in...
[ "When you insert the new counter into d, you check first word is contained in words. Probably you wanted to check if word is already contained in d:\nif word not in d:\n d[word] = [counter]\nelse:\n d[word].append(counter)\n\nThe check if the word is contained in words or line should be a separate if.\nYou co...
[ 1, 0 ]
[]
[]
[ "dictionary", "python", "spell_checking" ]
stackoverflow_0002891632_dictionary_python_spell_checking.txt
Q: psycopg2 can't find my python26 installation I believe it's because I installed python using SciPy, so apparently it's not in the registry where the psycopg2 installer is looking. Anyway to fix this without installing python26 over the existing install? I'm not sure if that will corrupt it. EDIT: My PYTHONPATH loo...
psycopg2 can't find my python26 installation
I believe it's because I installed python using SciPy, so apparently it's not in the registry where the psycopg2 installer is looking. Anyway to fix this without installing python26 over the existing install? I'm not sure if that will corrupt it. EDIT: My PYTHONPATH looks like the following: 'C:\\Python26\\scripts', 'C...
[ "I found this script which can fix it:\nhttp://effbot.org/zone/python-register.htm\n" ]
[ 1 ]
[]
[]
[ "postgresql", "psycopg2", "python" ]
stackoverflow_0002890749_postgresql_psycopg2_python.txt
Q: File management I am working on python and biopython right now. I have a file upload form and whatever file is uploaded suppose(abc.fasta) then i want to pass same name in execute (abc.fasta) function parameter and display function parameter (abc.aln). Right now i am changing file name manually, but i want to have...
File management
I am working on python and biopython right now. I have a file upload form and whatever file is uploaded suppose(abc.fasta) then i want to pass same name in execute (abc.fasta) function parameter and display function parameter (abc.aln). Right now i am changing file name manually, but i want to have it automatically. Wo...
[ "You need to read the uploaded file out of the cgi.FieldStorage() and save it onto the server. Ususally a temp directory (/tmp on Linux) is used for this. You should remove these files after processing or on some schedule to clean up the drive.\ndef main():\n import cgi\n import cgitb; cgitb.enable()\n f1 = cg...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0002891998_python.txt
Q: Bypassing import in Python so that I don't have to upload multiple libraries and classes? For example, I have a few python scripts, that link together and some libraries for it that need to be imported. I'm trying to reduce it to only one script. So instead of: import library.py Can I just take the coding from li...
Bypassing import in Python so that I don't have to upload multiple libraries and classes?
For example, I have a few python scripts, that link together and some libraries for it that need to be imported. I'm trying to reduce it to only one script. So instead of: import library.py Can I just take the coding from library.py and put into the main script?
[ "There are no limits to the size of a .py file, so you can certainly perform the copy and paste (and edit) operations you have in mind.\nSome caveats:\nimport library.py\n\nis unlikely to do what you want: it imports a module named py from a package named library. Thus it requires the existence of a directory libra...
[ 1, 0 ]
[]
[]
[ "import", "python" ]
stackoverflow_0002892128_import_python.txt
Q: how to print the linenumber of incorrectwords located in a txt file? i have this piece of code which only prints the line number of the incorrect words. i want it to print the linenumbers of the incorrect words from the txt file. Am i able to modify this code to do that? # text1 is my incorrect words # words is my...
how to print the linenumber of incorrectwords located in a txt file?
i have this piece of code which only prints the line number of the incorrect words. i want it to print the linenumbers of the incorrect words from the txt file. Am i able to modify this code to do that? # text1 is my incorrect words # words is my text file where my incorrect word are in from collections import defaul...
[ "You could completely rewrite this code to do what you mention -- this code's structure has no relation whatsoever to what you require.\nSince you need \"line numbers from a text file\", you'll need an object representing the text file (either as a list of lines in memory, or as an open file object). You say you h...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0002892161_python.txt
Q: Making only a part of model field available in Django I have a such model: GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female') ) class Profile(models.Model): user = models.ForeignKey(User) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) class FrontPage(models.Model): female = models.Fore...
Making only a part of model field available in Django
I have a such model: GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female') ) class Profile(models.Model): user = models.ForeignKey(User) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) class FrontPage(models.Model): female = models.ForeignKey(User,related_name="female") male = models.Foreig...
[ "ForeignKey's limit_choices_to argument will allow you to limit the choices available via the admin interface.\n" ]
[ 2 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0002892581_django_django_admin_django_models_python.txt
Q: Confused as to use a class or a function: Writing XML files using lxml and Python I need to write XML files using lxml and Python. However, I can't figure out whether to use a class to do this or a function. The point being, this is the first time I am developing a proper software and deciding where and why to use...
Confused as to use a class or a function: Writing XML files using lxml and Python
I need to write XML files using lxml and Python. However, I can't figure out whether to use a class to do this or a function. The point being, this is the first time I am developing a proper software and deciding where and why to use a class still seems mysterious. I will illustrate my point. For example, consider the ...
[ "The following code works:\ndef createSubElement(text, tagText = \"\"):\n elem = etree.SubElement(root, text)\n elem.text = tagText\n\ncreateSubElement('firstChild', 'first one')\ncreateSubElement('SecondChild', 'second one')\n\nprint etree.tostring(root)\n\nUsing a class rather than a function has mostly to ...
[ 3 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0002892528_lxml_python.txt
Q: Web framework recommendation for python (webservices, auth, cache, ...) Googling for the past week, but cannot finally decide which python web framework would be right for me. The web app I'm about to develop would be almost completely "pure" html with js (jQuery). Server side would have to do the following: auth...
Web framework recommendation for python (webservices, auth, cache, ...)
Googling for the past week, but cannot finally decide which python web framework would be right for me. The web app I'm about to develop would be almost completely "pure" html with js (jQuery). Server side would have to do the following: authentication session management caching web services (almost all the on page da...
[ "The best way to do web services in Django, if you choose that route, is to use piston. The combination of Django and Piston can certainly fulfil all the requirements you specify.\n", "For me - there are two choices:\n\nDjango - I find it much, much easier to learn and to work with than Pylons. Most of the time i...
[ 3, 2, 1 ]
[]
[]
[ "frameworks", "jquery", "python", "security", "web_services" ]
stackoverflow_0002892720_frameworks_jquery_python_security_web_services.txt
Q: Stepping over a yield statement When in the Python debugger (pdb) I want to step over a yield statement, but hitting (n) for next brings me to the destination of the yield i.e. the consumer of the generator. I want to go to the next line that is executed within the generator. Is there any way to do this? I'm us...
Stepping over a yield statement
When in the Python debugger (pdb) I want to step over a yield statement, but hitting (n) for next brings me to the destination of the yield i.e. the consumer of the generator. I want to go to the next line that is executed within the generator. Is there any way to do this? I'm using Python 2.6
[]
[]
[ "If your debugger allows you to use breakpoints and change variable values when you're there, it's as simple as [in pseudo code]\nSet Boolean yieldValue to true;\n[breakpoint after that line is executed, you can set yieldValue to false here]\nif yieldValue, yield value;\n\nin other words:\n\nbool yieldValue = true;...
[ -2, -2 ]
[ "generator", "pdb", "python" ]
stackoverflow_0002892746_generator_pdb_python.txt
Q: verbose_name for a model's method How can I set a verbose_name for a model's method, so that it might be displayed in the admin's change_view form? example: class Article(models.Model): title = models.CharField(max_length=64) created_date = models.DateTimeField(....) def created_weekday(self): ...
verbose_name for a model's method
How can I set a verbose_name for a model's method, so that it might be displayed in the admin's change_view form? example: class Article(models.Model): title = models.CharField(max_length=64) created_date = models.DateTimeField(....) def created_weekday(self): return self.created_date.strftime("%A")...
[ "list_display\ncreated_weekday.short_description = 'Foo'\n\nThis solution requires the method to be defined in the ModelAdmin class. You can call a Model method (eg: get_created_weekday) from ModelAdmin like: \ndef created_weekday(self, obj):\n return obj.get_created_weekday()\n\n" ]
[ 23 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0002892999_django_django_admin_django_models_python.txt
Q: Python modules import error Very strange for me: # uname -a Linux localhost.localdomain 2.6.18-194.3.1.el5 #1 SMP Thu May 13 13:09:10 EDT 2010 i686 i686 i386 GNU/Linux # pwd /root # python Python 2.6.5 (r265:79063, Apr 11 2010, 22:34:44) [GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2 Type "help", "copyright", ...
Python modules import error
Very strange for me: # uname -a Linux localhost.localdomain 2.6.18-194.3.1.el5 #1 SMP Thu May 13 13:09:10 EDT 2010 i686 i686 i386 GNU/Linux # pwd /root # python Python 2.6.5 (r265:79063, Apr 11 2010, 22:34:44) [GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2 Type "help", "copyright", "credits" or "license" for more i...
[ "What's dns.__file__ in the first case? I suspect it's not coming from the directory you cded into the second time (the current directory when you start Python goes at the front of sys.path) but rather from a package containing that crucial resolver module which the second one appears to be lacking.\n" ]
[ 4 ]
[]
[]
[ "centos", "linux", "python" ]
stackoverflow_0002893033_centos_linux_python.txt
Q: 404 not found in telnet, works fine in browser i am having a very irritating problem, when i open a url ( http://celebs.widewallpapers.net/md/a/adriana-lima/1440/Adriana-Lima-1440x900-002.jpg ) in browser, it works fine.. but when i try to access it by telnet on bash, i get 404 not found!! my exact terminal: $ tel...
404 not found in telnet, works fine in browser
i am having a very irritating problem, when i open a url ( http://celebs.widewallpapers.net/md/a/adriana-lima/1440/Adriana-Lima-1440x900-002.jpg ) in browser, it works fine.. but when i try to access it by telnet on bash, i get 404 not found!! my exact terminal: $ telnet celebs.widewallpapers.net 80 HEAD /md/a/adriana-...
[ "You aren't passing a host header. As per HTTP/1.1 you need to tell the web server which virtual host you are expecting to talk to. And 99% of servers today will only talk HTTP/1.1 even if you specify HTTP/1.0 in the request.\njb@apto % telnet celebs.widewallpapers.net 80\n...\nHEAD /md/a/adriana-lima/1440/Adriana-...
[ 10 ]
[]
[]
[ "c", "http", "python", "telnet" ]
stackoverflow_0002893063_c_http_python_telnet.txt
Q: How should I go about learning Python? I am currently learning PHP and want to learn about OOP. I know Python is a well-organized and is all OOP, so would learning Python be a wise choose to learn OOP? The thing is I am more towards web development then just general programming, and I know Python is just a gene...
How should I go about learning Python?
I am currently learning PHP and want to learn about OOP. I know Python is a well-organized and is all OOP, so would learning Python be a wise choose to learn OOP? The thing is I am more towards web development then just general programming, and I know Python is just a general purpose language, but there is Django. ...
[ "I would pick up a good O'Reilly book on Python and build a strong understanding of the fundamentals before delving into more web specific ventures. Once you've got the essentials then I'd branch out to things like Django. \nHere's a good starting page:\nO'Reilly - Python\nAnd here's a good tutorial if you'd rather...
[ 4, 4, 2, 2, 2, 2, 1, 0, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002876337_django_python.txt
Q: Building a balanced binary search tree Is there a method to build a balanced binary search tree? Example: 1 2 3 4 5 6 7 8 9 5 / \ 3 etc / \ 2 4 / 1 I'm thinking there is a method to do this, without using the more complex self-balancing trees. Otherwise I can do it on my own, but ...
Building a balanced binary search tree
Is there a method to build a balanced binary search tree? Example: 1 2 3 4 5 6 7 8 9 5 / \ 3 etc / \ 2 4 / 1 I'm thinking there is a method to do this, without using the more complex self-balancing trees. Otherwise I can do it on my own, but someone probably have done this already :) ...
[ "For each subtree:\n\nFind the middle element of the subtree and put that at the top of the tree.\nFind all the elements before the middle element and use this algorithm recursively to get the left subtree.\nFind all the elements after the middle element and use this algorithm recursively to get the right subtree.\...
[ 10, 5, 2 ]
[]
[]
[ "binary_tree", "c#", "python" ]
stackoverflow_0002893318_binary_tree_c#_python.txt
Q: Dealing with external processes I've been working on a gui app that needs to manage external processes. Working with external processes leads to a lot of issues that can make a programmer's life difficult. I feel like maintenence on this app is taking an unacceptably long time. I've been trying to list the thin...
Dealing with external processes
I've been working on a gui app that needs to manage external processes. Working with external processes leads to a lot of issues that can make a programmer's life difficult. I feel like maintenence on this app is taking an unacceptably long time. I've been trying to list the things that make working with external pr...
[ "Check out the subprocess module. It should help with output separation. I don't see any way around either separate output streams or some kind of output tagging in a single stream. \nThe hanging process problem is difficult as well. The only solution I have been able to make is to put a timer on the external p...
[ 2 ]
[]
[]
[ "external_process", "pyqt", "python", "subprocess", "user_interface" ]
stackoverflow_0002892756_external_process_pyqt_python_subprocess_user_interface.txt
Q: How to run own python script in Trac I want to customize the project page (trac/templates/index.html). I want to use a table to show more project-specific information. For instance the admin list of each project, the build status of each project. These information are stored in trac's database. I am afraid that ...
How to run own python script in Trac
I want to customize the project page (trac/templates/index.html). I want to use a table to show more project-specific information. For instance the admin list of each project, the build status of each project. These information are stored in trac's database. I am afraid that the default template engine is not able to...
[ "I've customized trac in a more simple way by adding an iframe to the top of all trac project pages. You can do this by going to templates directory in the trac environment directory, and adding a site.html file.\nI have something like:\n <html xmlns=\"http://www.w3.org/1999/xhtml\"\n xmlns:py=\"http://genshi.edge...
[ 1, 1 ]
[]
[]
[ "customization", "interface", "python", "trac" ]
stackoverflow_0002809310_customization_interface_python_trac.txt
Q: How to set a local image in pynotify? If I run the following in python in Ubuntu 10.04: >>> import pynotify >>> p = pynotify.Notification ("Notice","","/home/george/Pictures/test.png") >>> p.show() true The message displays as expected, except the image does not appear in the OSD. How can I display a local image?...
How to set a local image in pynotify?
If I run the following in python in Ubuntu 10.04: >>> import pynotify >>> p = pynotify.Notification ("Notice","","/home/george/Pictures/test.png") >>> p.show() true The message displays as expected, except the image does not appear in the OSD. How can I display a local image? In fact, for what I need, it would be bett...
[ "The following definitely works for me:\n>>> import pynotify\n>>> p = pynotify.Notification(\"Notice\", \"\", \"/usr/share/pixmaps/firefox.png\")\n>>> p.show()\n\nalt text http://www.imagebanana.com/img/qfmebkr5/screenshot_009.png\nAre you sure the image is there? With correct permissions?\n", "That works for me....
[ 4, 1 ]
[]
[]
[ "pynotify", "python", "ubuntu" ]
stackoverflow_0002893462_pynotify_python_ubuntu.txt
Q: StringListProperty limited to 500 char strings (Google App Engine / Python) It seems that StringListProperty can only contain strings up to 500 chars each, just like StringProperty... Is there a way to store longer strings than that? I don't need them to be indexed or anything. What I would need would be something...
StringListProperty limited to 500 char strings (Google App Engine / Python)
It seems that StringListProperty can only contain strings up to 500 chars each, just like StringProperty... Is there a way to store longer strings than that? I don't need them to be indexed or anything. What I would need would be something like a "TextListProperty", where each string in the list can be any length and n...
[ "Alex already answered long ago, but in case someone else comes along with the same issue: \nYou'd just make item_type equal to db.Text (as OP mentions in a comment).\nHere's a simple example: \nfrom google.appengine.ext import db\nclass LargeTextList(db.Model):\n large_text_list = db.ListProperty(item_type=db...
[ 4, 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002893102_google_app_engine_python.txt
Q: Visual Python - Visualize graphs relating to a movement I'm working with visual python on a project where I need to simulate a physical movement. I'd like to present, in a different window than the one the actual, 3D sim is running, two graphs, both related to the movement: How the velocity and angular velocity p...
Visual Python - Visualize graphs relating to a movement
I'm working with visual python on a project where I need to simulate a physical movement. I'd like to present, in a different window than the one the actual, 3D sim is running, two graphs, both related to the movement: How the velocity and angular velocity progress over time. How the movement and rotation progress ove...
[ "If you're looking to do plots of live data you can use matplotlib. Here's a live plotting example:\nhttp://eli.thegreenplace.net/files/prog_code/wx_mpl_dynamic_graph.py.txt | Screenshot\nIt uses wx but matplotlib has bindings for QT or GTK. Alternatively you could use the rpy2 interface to hook into R which has ...
[ 2, 1 ]
[]
[]
[ "graphics", "python" ]
stackoverflow_0002891709_graphics_python.txt
Q: Non-Standard Optional Argument Defaults I have two functions: def f(a,b,c=g(b)): blabla def g(n): blabla c is an optional argument in function f. If the user does not specify its value, the program should compute g(b) and that would be the value of c. But the code does not compile - it says name 'b' is n...
Non-Standard Optional Argument Defaults
I have two functions: def f(a,b,c=g(b)): blabla def g(n): blabla c is an optional argument in function f. If the user does not specify its value, the program should compute g(b) and that would be the value of c. But the code does not compile - it says name 'b' is not defined. How to fix that? Someone suggeste...
[ "def f(a,b,c=None):\n if c is None:\n c = g(b)\n\nIf None can be a valid value for c then you do this:\nsentinel = object()\ndef f(a,b,c=sentinel):\n if c is sentinel:\n c = g(b)\n\n", "You cannot do it that way.\nInside the function, check if c is specified. If not, do the calculation.\ndef f...
[ 28, 3, 2, 1, 0 ]
[]
[]
[ "optional_arguments", "python" ]
stackoverflow_0001118454_optional_arguments_python.txt
Q: Where to use a pyc file I want to know what a pyc file(python bytecode) is. I want to know all the details. I want to know about how pyc files interface with the compiler. Is it a replacement for exe? Does it need to be run by python? Is it as portable as the .py file is? Where should I use this? A: To supplemen...
Where to use a pyc file
I want to know what a pyc file(python bytecode) is. I want to know all the details. I want to know about how pyc files interface with the compiler. Is it a replacement for exe? Does it need to be run by python? Is it as portable as the .py file is? Where should I use this?
[ "To supplement Mike Graham's answer there are some interesting comments here giving some information on pyc files. Most interestingly I suspect for you is the line:\n\nA program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster a...
[ 17, 9, 6 ]
[]
[]
[ "python" ]
stackoverflow_0002893686_python.txt
Q: Find the closest vector Recently I wrote the algorithm to quantize an RGB image. Every pixel is represented by an (R,G,B) vector, and quantization codebook is a couple of 3-dimensional vectors. Every pixel of the image needs to be mapped to (say, "replaced by") the codebook pixel closest in terms of euclidean dist...
Find the closest vector
Recently I wrote the algorithm to quantize an RGB image. Every pixel is represented by an (R,G,B) vector, and quantization codebook is a couple of 3-dimensional vectors. Every pixel of the image needs to be mapped to (say, "replaced by") the codebook pixel closest in terms of euclidean distance (more exactly, squared e...
[ "One simple optimization is to drop the sqrt call. x is monotonic with sqrt(x), and since you don't need the actual distance, just the min distance, use x^2 instead. Should help a bit since sqrt is expensive.\nThis trick is used a lot when working with distances. For instance, if you have a distance threshold, y...
[ 4, 2, 0 ]
[]
[]
[ "optimization", "python" ]
stackoverflow_0002892933_optimization_python.txt
Q: I'm writing a spellchecking program, how do I replace ch in a string? What am I doing wrong/what can I do? import sys import string def remove(file): punctuation = string.punctuation for ch in file: if len(ch) > 1: print('error - ch is larger than 1 --| {0} |--'.format(ch)) if ...
I'm writing a spellchecking program, how do I replace ch in a string?
What am I doing wrong/what can I do? import sys import string def remove(file): punctuation = string.punctuation for ch in file: if len(ch) > 1: print('error - ch is larger than 1 --| {0} |--'.format(ch)) if ch in punctuation: ch = ' ' return ch else:...
[ "In this code...:\nfor ch in file:\n if len(ch) > 1:\n\nthe weirdly-named file (besides breaking the best practice of not hiding builtin names with your own identifier) is not a file, it's a string -- which means unicode, in Python 3, but that makes no difference to the fact that the loop is returning single...
[ 2, 1, 0 ]
[]
[]
[ "python", "python_3.x", "string" ]
stackoverflow_0002893875_python_python_3.x_string.txt
Q: Can I use setuptools without permissions to /usr/local etc I want to use some packages (i.e., IPython or zdaemon), butI am doing this on a system (my university) that does not give me permissions for /usr/local, /usr/bin, or all these directories. Is there a way around it? A: Sure, you can use a configuration fi...
Can I use setuptools without permissions to /usr/local etc
I want to use some packages (i.e., IPython or zdaemon), butI am doing this on a system (my university) that does not give me permissions for /usr/local, /usr/bin, or all these directories. Is there a way around it?
[ "Sure, you can use a configuration file that specifies an alternate installation directory, or use the --install-dir option. The standard place to put Python packages in your own user account is, I think, in $HOME/.local/ (if you're using Python 2.6). So for instance, pure-Python packages will wind up in $HOME/.loc...
[ 5, 2, 1 ]
[]
[]
[ "python", "setuptools" ]
stackoverflow_0002893787_python_setuptools.txt
Q: Socket connection to a telnet-based server hangs on read I'm trying to write a simple socket-based client in Python that will connect to a telnet server. I can test the server by telnetting to its port (5007), and entering text. It responds with a NAK (error) or an AK (success), sometimes accompanied by other te...
Socket connection to a telnet-based server hangs on read
I'm trying to write a simple socket-based client in Python that will connect to a telnet server. I can test the server by telnetting to its port (5007), and entering text. It responds with a NAK (error) or an AK (success), sometimes accompanied by other text. Seems very simple. I wrote a client to connect and commun...
[ "You probably need to terminate your msg with some kind of \"line-ending characters\" -- perhaps \\r\\n, perhaps just one of the two. When you're in telnet, didn't you terminate your typed text by hitting a Return or Enter key? In the Python code, you're not doing the equivalent of that.\n", "You need to flush ...
[ 7, 0 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0002893562_python_sockets.txt
Q: What is an efficient way to write password cracking algorithm (python) This problem might be relatively simple, but I'm given two text files. One text file contains all encrypted passwords encrypted via crypt.crypt in python. The other list contains over 400k+ normal dictionary words. The assignment is that given ...
What is an efficient way to write password cracking algorithm (python)
This problem might be relatively simple, but I'm given two text files. One text file contains all encrypted passwords encrypted via crypt.crypt in python. The other list contains over 400k+ normal dictionary words. The assignment is that given 3 different functions which transform strings from their normal case to all ...
[ "Without knowing details about the underlying hash algorithm and possible weaknesses of the algorithm all you can do is to run a brute-force attack trying all possible transformations of the words in your password list. \nThe only way to speed up such a brute-force attack is to get more powerful hardware and to spl...
[ 3, 2 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0002893391_algorithm_python.txt
Q: gae error : Error: Server Error, how to debug it when i upload my project to google-app-engine , it show this : Error: Server Error The server encountered an error and could not complete your request. If the problem persists, please report your problem and mention this error message and the query that caused it....
gae error : Error: Server Error, how to debug it
when i upload my project to google-app-engine , it show this : Error: Server Error The server encountered an error and could not complete your request. If the problem persists, please report your problem and mention this error message and the query that caused it. why ? how can i debug this error ? thanks
[ "Look at the logs in the online administrative console of your App Engine account. That's where the info about the \"why\" hides;-).\nIncidentally, it's very unlikely (although not impossible) that you'd immediately see such an error on the actual online App Engine without hints in your local development toolkit e...
[ 1 ]
[]
[]
[ "debugging", "google_app_engine", "python" ]
stackoverflow_0002894357_debugging_google_app_engine_python.txt
Q: for x in y, type iteration in python. Can I find out what iteration I'm currently on? I have a question about the loop construct in Python in the form of: for x in y: In my case y is a line read from a file and x is separate characters. I would like to put a space after every pair of characters in the output, like...
for x in y, type iteration in python. Can I find out what iteration I'm currently on?
I have a question about the loop construct in Python in the form of: for x in y: In my case y is a line read from a file and x is separate characters. I would like to put a space after every pair of characters in the output, like this: aa bb cc dd etc. So, I would like to know the current iteration. Is it possible, or ...
[ "for i,x in enumerate(y):\n ....\n\n", "Use enumerate:\nfor index,x in enumerate(y):\n # do stuff, on iteration #index\n\nAlternatively, just create a variable and increment it inside the loop body. This isn't quite as 'pythonic', though.\ncur = 0\nfor x in y:\n cur += 1\n # do stuff, on iteration #cu...
[ 23, 3, 0, 0 ]
[]
[]
[ "iteration", "python" ]
stackoverflow_0002894323_iteration_python.txt
Q: Is there a more up to date RSS feed API for Python than Feedparser? Seems it hasn't been updated in a while, and lacks support for things like sy:updateFrequency. A: feedparser trunk in it's SVN repository was last updated a few days ago: feedparser.py You can try it to see if it fits your needs, or even look in...
Is there a more up to date RSS feed API for Python than Feedparser?
Seems it hasn't been updated in a while, and lacks support for things like sy:updateFrequency.
[ "feedparser trunk in it's SVN repository was last updated a few days ago: feedparser.py\nYou can try it to see if it fits your needs, or even look in it's source to see if it can be extended to support what you need...\nI also found this one but I have never used it...\nhope it helps.\n" ]
[ 2 ]
[]
[]
[ "feedparser", "python", "rdf", "rss" ]
stackoverflow_0002894407_feedparser_python_rdf_rss.txt
Q: How to customize a many-to-many inline model in django admin I'm using the admin interface to view invoices and products. To make things easy, I've set the products as inline to invoices, so I will see the related products in the invoice's form. As you can see I'm using a many-to-many relationship. In models.py: ...
How to customize a many-to-many inline model in django admin
I'm using the admin interface to view invoices and products. To make things easy, I've set the products as inline to invoices, so I will see the related products in the invoice's form. As you can see I'm using a many-to-many relationship. In models.py: class Product(models.Model): name = models.TextField() pr...
[ "I think is simple, don't use the inline, just use the property ModelAdmin.filter_horizontal \n" ]
[ 4 ]
[]
[]
[ "django", "django_admin", "django_forms", "many_to_many", "python" ]
stackoverflow_0002893924_django_django_admin_django_forms_many_to_many_python.txt
Q: Why is this dictionary line number count not working? I have this piece of code, the last bit of the code starting from d = {}. I'm trying to print the words with its line number located in the text but it is not working, it's only printing the words - anyone know why? import sys import string text = [] infile = ...
Why is this dictionary line number count not working?
I have this piece of code, the last bit of the code starting from d = {}. I'm trying to print the words with its line number located in the text but it is not working, it's only printing the words - anyone know why? import sys import string text = [] infile = open(sys.argv[1], 'r').read() for punct in string.punctuati...
[ "text is a list of WORDS, it's not a list of LINES. When you do:\ntext = infile.split()\n\nyou're irreversibly, forever throwing away all connections between a word and the line it was in. So when you later write\nfor lines in text:\n\nit's a lie: text's items are words, not lines. If they weren't, then this oth...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0002894668_python.txt
Q: Most efficient way to update attribute of one instance I'm creating an arbitrary number of instances (using for loops and ranges). At some event in the future, I need to change an attribute for only one of the instances. What's the best way to do this? Right now, I'm doing the following: 1) Manage the instances in...
Most efficient way to update attribute of one instance
I'm creating an arbitrary number of instances (using for loops and ranges). At some event in the future, I need to change an attribute for only one of the instances. What's the best way to do this? Right now, I'm doing the following: 1) Manage the instances in a list. 2) Iterate through the list to find a key value. 3)...
[ "As you mention, you need to keep an auxiliary dictionary with the key value as the key and the instance (or list of instance with that value for their attribute) as the value(s) -- way more efficient. Indeed, there's nothing more efficient than a dictionary for such uses.\n", "\nShould I be storing the Instance...
[ 1, 1, 1 ]
[]
[]
[ "dictionary", "list", "multiple_instances", "oop", "python" ]
stackoverflow_0002894733_dictionary_list_multiple_instances_oop_python.txt
Q: Advice on translating code from very unrelated languages (in this case Scheme to Python)? Reasoning: I'm trying to convert a large library from Scheme to Python Are there any good strategies for doing this kind of conversion? Specifically cross-paradigm in this case since Python is more OO and Scheme is Functional...
Advice on translating code from very unrelated languages (in this case Scheme to Python)?
Reasoning: I'm trying to convert a large library from Scheme to Python Are there any good strategies for doing this kind of conversion? Specifically cross-paradigm in this case since Python is more OO and Scheme is Functional. Totally subjective so I'm making it community wiki
[ "I would treat the original language implementation almost like a requirements specification, and write up a design based on it (most importantly including detailed interface definitions, both for the external interfaces and for those between modules within the library). Then I would implement from that design. \nW...
[ 7, 6, 1, 0, 0 ]
[]
[]
[ "code_translation", "python", "scheme" ]
stackoverflow_0002893313_code_translation_python_scheme.txt
Q: Up To Date Documentation on Wrapping gobjects with Python I'm looking for up-to-date documentation and tutorials on creating Python bindings for gobjects. Everything I can find on the web is either incomplete or out of date. A: gobject's aren't special - the standard Python documentation is what you want. Check...
Up To Date Documentation on Wrapping gobjects with Python
I'm looking for up-to-date documentation and tutorials on creating Python bindings for gobjects. Everything I can find on the web is either incomplete or out of date.
[ "gobject's aren't special - the standard Python documentation is what you want. Check out the Extending and Embedding Tutorial (at least the \"Extending\" parts), and then keep a copy of the Python/C API in your back pocket.\nAlso, Google Code Search is generally your friend when the tutorials don't have examples ...
[ 0 ]
[]
[]
[ "gobject", "pygobject", "python" ]
stackoverflow_0002895054_gobject_pygobject_python.txt
Q: How to use python to create a GUI application which have cool animation/effects under Linux (like 3D wall in Cooliris, compiz effects etc...) I am not sure if my question title makes sense to you or not. I am seeing many cool applications which have cool animations/effects. I would like to learn how to use python ...
How to use python to create a GUI application which have cool animation/effects under Linux (like 3D wall in Cooliris, compiz effects etc...)
I am not sure if my question title makes sense to you or not. I am seeing many cool applications which have cool animations/effects. I would like to learn how to use python to create this kind of GUI applications under Linux. "cool animation/effects" like 3D wall in Cooliris which is written in flash and compiz effect...
[ "http://techbase.kde.org/Development/Languages/Python\nMany KDE styles use SVG and plenty of animation. The user can always change themes. I think you should be more specific about what kind of animations you want to do. I don't think 3D wall type affects really fall into the widget category that QT is. It sounds t...
[ 3, 0 ]
[]
[]
[ "pyqt", "python", "user_interface", "wxpython" ]
stackoverflow_0002895404_pyqt_python_user_interface_wxpython.txt
Q: prints line number in both txtfile and list? i have this code which prints the line number in infile but also the linenumber in words what do i do to only print the line number of the txt file next to the words??? d = {} counter = 0 wrongwords = [] for line in infile: infile = line.split() wrongwords.extend(infil...
prints line number in both txtfile and list?
i have this code which prints the line number in infile but also the linenumber in words what do i do to only print the line number of the txt file next to the words??? d = {} counter = 0 wrongwords = [] for line in infile: infile = line.split() wrongwords.extend(infile) counter += 1 for word in infile: if word no...
[ "Four things:\n\nYou can keep track of the line number by doing this instead of handling a\ncounter on your own:\nfor line_no, word in enumerate(infile):\n\nAs sateesh pointed out above, you probably need an else in your\nconditions:\nif word not in d:\n d[word] = [counter]\nelse:\n d[word].append(counter)\n\...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0002895428_python.txt
Q: Python del() built-in can't be used in assignment? I noticed a problem when I was trying to use del in a lambda to thin out a list of threads to just those running: map(lambda x: del(x) if not x.isAlive() else x, self.threads) Ignore for a second that this doesn't do anything, I'm just fooling around with map, re...
Python del() built-in can't be used in assignment?
I noticed a problem when I was trying to use del in a lambda to thin out a list of threads to just those running: map(lambda x: del(x) if not x.isAlive() else x, self.threads) Ignore for a second that this doesn't do anything, I'm just fooling around with map, reduce, and lambda. This fails with a syntax error at del(...
[ "The limitation is that del is a statement and not an expression. It doesn't \"return a value\" because statements don't return values in Python.\nThe lambda form only allows you to mention expressions (because there is an implicit return before the expression), while the def form allows a single statement function...
[ 15, 13 ]
[]
[]
[ "built_in", "python" ]
stackoverflow_0002895629_built_in_python.txt
Q: How can I set Invitee in Google Calendar through Python? I am Setting Google Calendar via python command like this def _InsertQuickAddEvent(self, content="Tennis with dddddd on 5/19/2010 4am-5:30am"): """Creates an event with the quick_add property set to true so the content is processed as quick add content in...
How can I set Invitee in Google Calendar through Python?
I am Setting Google Calendar via python command like this def _InsertQuickAddEvent(self, content="Tennis with dddddd on 5/19/2010 4am-5:30am"): """Creates an event with the quick_add property set to true so the content is processed as quick add content instead of as an event description.""" event = gdata.calendar.Ca...
[ "I got after lots of Research in this.....\nevent_audit=gdata.calendar.AttendeeStatus(\"http://schemas.google.com/g/2005#event.invited\")\nevent.who.append(gdata.calendar.Who(email=\"xyz@pqr.com\",rel=\"http://schemas.google.com/g/2005#event.invited\"))\n\n" ]
[ 0 ]
[]
[]
[ "google_apps", "python" ]
stackoverflow_0002887612_google_apps_python.txt
Q: Java code translation of Python array-splitting code Can someone please give the Java equivalent of the below python (which slices a given array into given parts) which was originally written by ChristopheD here: def split_list(alist, wanted_parts=1): length = len(alist) return [ alist[i*length // wanted_par...
Java code translation of Python array-splitting code
Can someone please give the Java equivalent of the below python (which slices a given array into given parts) which was originally written by ChristopheD here: def split_list(alist, wanted_parts=1): length = len(alist) return [ alist[i*length // wanted_parts: (i+1)*length // wanted_parts] for i in ra...
[ "Maybe something like this:\nList<List<T>> splitList(List<T> alist, int wantedParts) {\n ArrayList<List<T>> result = new ArrayList<List<T>>();\n int length = alist.length;\n\n for (int i = 0; i < wantedParts; i++) {\n result.append(alist.subList(i*length/wantedParts,\n ...
[ 1, 0 ]
[]
[]
[ "java", "python" ]
stackoverflow_0002895664_java_python.txt
Q: Inserting rows while fetching(from another table) in SQLite I'm getting this error no matter what with python and sqlite. File "addbooks.py", line 77, in saveBook conn.commit() sqlite3.OperationalError: cannot commit transaction - SQL statements in progress The code looks like this: conn = sqlite3.conn...
Inserting rows while fetching(from another table) in SQLite
I'm getting this error no matter what with python and sqlite. File "addbooks.py", line 77, in saveBook conn.commit() sqlite3.OperationalError: cannot commit transaction - SQL statements in progress The code looks like this: conn = sqlite3.connect(fname) cread = conn.cursor() cread.execute('''select book_te...
[ "The problem is that you've left the connection in auto-commit mode. Wrap a single transaction around the whole lot so that a commit only happens after you've done all the updates, and it should all work fine.\n", "Don't know if this count as \"dirty tricks\" too ;-)\nMy solution to this problem is to use SELECT....
[ 2, 1, 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0002844267_python_sqlite.txt
Q: how do i edit a running python program? scenario: a modular app that loads .py modules on the fly as it works. programmer (me) wishes to edit the code of a module and then re-load it into the program without halting execution. can this be done? i have tried running import a second time on an updated module.py, but...
how do i edit a running python program?
scenario: a modular app that loads .py modules on the fly as it works. programmer (me) wishes to edit the code of a module and then re-load it into the program without halting execution. can this be done? i have tried running import a second time on an updated module.py, but the changes are not picked up
[ "While reload does reload a module, as the other answer mentions, you need quite a few precautions to make it work smoothly -- and for some things you might believe would work easily, you're in for quite a shock in terms of amount of work actually needed.\nIf you ever use the form from module import afunction, then...
[ 6, 0, 0, 0, 0 ]
[]
[]
[ "import", "modular", "python" ]
stackoverflow_0002894235_import_modular_python.txt
Q: Show me some cool python list comprehensions One of the major strengths of python and a few other (functional) programming languages are the list comprehension. They allow programmers to write complex expressions in 1 line. They may be confusing at first but if one gets used to the syntax, it is much better than...
Show me some cool python list comprehensions
One of the major strengths of python and a few other (functional) programming languages are the list comprehension. They allow programmers to write complex expressions in 1 line. They may be confusing at first but if one gets used to the syntax, it is much better than nested complicated for loops. With that said, ple...
[ "A lot of people don't know that Python allows you to filter the results of a list comprehension using if:\n>>> [i for i in range(10) if i % 2 == 0]\n[0, 2, 4, 6, 8]\n\n", "I often use comprehensions to construct dicts:\nmy_dict = dict((k, some_func(k)) for k in input_list)\n\nNote Python 3 has dict comprehension...
[ 16, 9, 8, 8, 8, 4, 3, 2 ]
[]
[]
[ "algorithm", "list_comprehension", "python" ]
stackoverflow_0002893569_algorithm_list_comprehension_python.txt
Q: Any PHP or Python alternatives for Liferay and Alfresco? My company wants to use Liferay for developing a portal and integrate Alfresco with it for document management. But both Liferay and Alfresco are Java based and i would like to know if there are any alternatives to Liferay and Alfresco in PHP or Python. Tha...
Any PHP or Python alternatives for Liferay and Alfresco?
My company wants to use Liferay for developing a portal and integrate Alfresco with it for document management. But both Liferay and Alfresco are Java based and i would like to know if there are any alternatives to Liferay and Alfresco in PHP or Python. Thank You
[ "Maybe you can have a look at KnowledgeTree as a substitution of Alfresco. It's mainly written in PHP.\n", "It seems both are content management systems. Here you'll find a couple of proprietary PHP based CMS. As for opensource solutions, there are many.\n\nPHP\n\n\nJoomla \nDrupal\nAnd many more\n\nPython\n\n\nD...
[ 3, 0 ]
[]
[]
[ "alfresco", "java", "liferay", "php", "python" ]
stackoverflow_0002896269_alfresco_java_liferay_php_python.txt
Q: Creating a sliding frame containing widgets in tkinter in python I am trying really hard to make a sliding frame containing widgets in tkinter in python. There is this frame inside a big window with different widgets. And as soon as i click on the next button on that frame the frame should slowly slide towards the...
Creating a sliding frame containing widgets in tkinter in python
I am trying really hard to make a sliding frame containing widgets in tkinter in python. There is this frame inside a big window with different widgets. And as soon as i click on the next button on that frame the frame should slowly slide towards the left and vanish ultimately. As soon as it vanishes, i want new frame ...
[ "How you do it depends on the geometry manager, but the basic idea is simply to set the width of the frame to smaller and smaller values until it has a width of zero. You don't need a loop though -- the code is already running in the event loop, so take advantage of that. Use 'after' to schedule a job that changes ...
[ 0 ]
[]
[]
[ "frame", "python", "sliding", "tkinter", "user_interface" ]
stackoverflow_0002882060_frame_python_sliding_tkinter_user_interface.txt
Q: Can DBRefs contain additional fields? I've encountered several situations when using MongoDB that require the use of DBRefs. However, I'd also like to cache some fields from the referenced document in the DBRef itself. {$ref:'user', $id:'10285102912A', username:'Soviut'} For example, I may want to have the usern...
Can DBRefs contain additional fields?
I've encountered several situations when using MongoDB that require the use of DBRefs. However, I'd also like to cache some fields from the referenced document in the DBRef itself. {$ref:'user', $id:'10285102912A', username:'Soviut'} For example, I may want to have the username available even though the user document...
[ "\nUltimately, I'm wondering if it's considered good form to store additional fields on my DBRefs?\n\nIt might be cleaner to have separate \"cached\" and \"ref\" fields... it depends one what your data is like.\n\nWill I lose my data each time a reference is rewritten?\n\nYou could, but not if you're careful. If y...
[ 5 ]
[]
[]
[ "dbref", "mongodb", "nosql", "pymongo", "python" ]
stackoverflow_0002893858_dbref_mongodb_nosql_pymongo_python.txt
Q: how can i increase the speed of socket how can i increase speed of socket in python ? my code : import urllib proxies = {'http': 'http://75.21.47.2:8080/'} opener = urllib.FancyURLopener(proxies) r = opener.open("http://www.python.org/") print r.read() A: 75.21.47.2:8080 seems to be a public HTTP proxy server? ...
how can i increase the speed of socket
how can i increase speed of socket in python ? my code : import urllib proxies = {'http': 'http://75.21.47.2:8080/'} opener = urllib.FancyURLopener(proxies) r = opener.open("http://www.python.org/") print r.read()
[ "75.21.47.2:8080 seems to be a public HTTP proxy server? these are invariably slow because of what they are.\nIf you want better performance via a proxy, implement your own or use a commercial service.\n", "Measure all stages of the pipeline (Opening the connection, sending the message, receiving the response etc...
[ 2, 0, 0 ]
[ "What is the baud rate you are using? You can probably increase it.\nOk, now once the question has been cleared, I shall recommend to opt for a better solution (like implementing your own) rather than using the public proxy service. It is slow.\n" ]
[ -1 ]
[ "python", "sockets" ]
stackoverflow_0002896193_python_sockets.txt
Q: Server side command line queuing Is it possible to have a server side program that queues and manages processes that are executed at the command line? The project I am working on takes an image from the user, modifies the image then applies it as a texture to a 3D shape. This 3D scene is generated by blender/Cinem...
Server side command line queuing
Is it possible to have a server side program that queues and manages processes that are executed at the command line? The project I am working on takes an image from the user, modifies the image then applies it as a texture to a 3D shape. This 3D scene is generated by blender/Cinema 4d at the command line which outputs...
[ "Lacking more details about how/why you're doing queuing (can only run so many at a time, things need to be done in the right order, etc?), it's hard to suggest a specific solution. However, the basic answer for any situation is that you want to use the subprocess module to fire off the processes, and then you can...
[ 1 ]
[]
[]
[ "command_line", "python", "queue", "rendering" ]
stackoverflow_0002896614_command_line_python_queue_rendering.txt
Q: Best resources for learning PyGame? Just curious if anyone knows of good sites for learning and understanding PyGame. I've programmed a bunch in Python, so I'm well-equipped with that. Just curious if anyone knows a good site or more for learning PyGame. Thanks for any help! A: I have several Pygame bookmarks on...
Best resources for learning PyGame?
Just curious if anyone knows of good sites for learning and understanding PyGame. I've programmed a bunch in Python, so I'm well-equipped with that. Just curious if anyone knows a good site or more for learning PyGame. Thanks for any help!
[ "I have several Pygame bookmarks on my delicious page that I think are worth a look. The links cover both tutorials and libraries to make your Pygame development easier. It would also be worth looking at a good, complete game written with Pygame to get an idea of how it should be structured. There are plenty of exc...
[ 5, 3, 2, 1, 0, 0, 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0002865003_pygame_python.txt
Q: Python: UTF16 decoding adds a new blank line on Windows boxes I'm running into an issue with extra newlines on windows versus *nix platforms. file = open('UTF16file.xml', 'rb') html = file.read().decode('utf-16') file.close() regexp = re.compile(self.originalurl, re.S) (html, changes) = regexp.subn(self.newurl, ...
Python: UTF16 decoding adds a new blank line on Windows boxes
I'm running into an issue with extra newlines on windows versus *nix platforms. file = open('UTF16file.xml', 'rb') html = file.read().decode('utf-16') file.close() regexp = re.compile(self.originalurl, re.S) (html, changes) = regexp.subn(self.newurl, html) file = open('UTF16file-regexed.xml', 'w+') file.write(html.e...
[ "C:\\Documents and Settings\\Nick>python\nActivePython 2.6.4.10 (ActiveState Software Inc.) based on\nPython 2.6.4 (r264:75706, Jan 22 2010, 16:41:54) [MSC v.1500 32 bit (Intel)]...\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> txt = \"\"\"here\n... is all\n... my text n stuff...
[ 0 ]
[]
[]
[ "python", "utf_16" ]
stackoverflow_0002897252_python_utf_16.txt
Q: Python templates for huge HTML/XML Recently I needed to generate a huge HTML page containing a report with several thousand row table. And, obviously, I did not want to build the whole HTML (or the underlying tree) in memory. As result, I built the page with the old good string interpolation, but I do not like the...
Python templates for huge HTML/XML
Recently I needed to generate a huge HTML page containing a report with several thousand row table. And, obviously, I did not want to build the whole HTML (or the underlying tree) in memory. As result, I built the page with the old good string interpolation, but I do not like the solution. Thus, I wonder whether there ...
[ "Most popular template engines have a way to generate or write rendered result to file objects with chunks. For example:\n\nTemplate.generate() in Jinja2\nTemplate.render_context() in Mako\nStream.serialize() in Genshi\n\n", "It'd be more user-friendly (assuming they have javascript enabled) to build the table vi...
[ 5, 2, 2, 1, 0 ]
[]
[]
[ "python", "templates" ]
stackoverflow_0002832915_python_templates.txt
Q: Are there any guidelines available for beginning Python with Python 2.6 to write applications easily migratable to Python 3 in future? Possible Duplicate: Tips on upgrading to python 3.0? I am beginning Python and Python 3 is hardly a choice today. But I want the new code I write to have no problems running or b...
Are there any guidelines available for beginning Python with Python 2.6 to write applications easily migratable to Python 3 in future?
Possible Duplicate: Tips on upgrading to python 3.0? I am beginning Python and Python 3 is hardly a choice today. But I want the new code I write to have no problems running or being converted to Python 3. Are there any issues known that I should keep in mind for this?
[ "The full correct answer is in the comments, of course - but if you only do one thing to prepare for Python 3, make it learning to use parentheses with 'print'.\nPython 2.x:\nprint 'Hello, World!'\n\nPython 3.x:\nprint('Hello, World!')\n\nIt's the number one most common error in my code when I try to write Python 3...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0002896364_python_python_3.x.txt
Q: Crossfading audio with PyQT4 and Phonon I'm trying to get audio files to crossfade with phonon. I'm using PyQT4. I have tracks queuing properly, but I'm stuck with the fade effect. I think I need to be using the KVolumeFader effect. Here's my current code: def music_play(self): self.delayedInit() self....
Crossfading audio with PyQT4 and Phonon
I'm trying to get audio files to crossfade with phonon. I'm using PyQT4. I have tracks queuing properly, but I'm stuck with the fade effect. I think I need to be using the KVolumeFader effect. Here's my current code: def music_play(self): self.delayedInit() self.m_media.setCurrentSource(Phonon.MediaSource(s...
[ "Seems I found the solution I was looking for. Although it's not supported by every phonon backend, setting the MediaObject's transitionTime with a negative number will crossfade.\n" ]
[ 2 ]
[]
[]
[ "phonon", "pyqt4", "python" ]
stackoverflow_0002878521_phonon_pyqt4_python.txt
Q: file layout and setuptools configuration for the python bit of a multi-language library So we're writing a full-text search framework MongoDb. MongoDB is pretty much javascript-native, so we wrote the javascript library first, and it works. Now I'm trying to write a python framework for it, which will be partially...
file layout and setuptools configuration for the python bit of a multi-language library
So we're writing a full-text search framework MongoDb. MongoDB is pretty much javascript-native, so we wrote the javascript library first, and it works. Now I'm trying to write a python framework for it, which will be partially in python, but partially use those same stored javascript functions - the javascript functio...
[ "The short answer is that none of the Python distribution tools is going to do what you want, the exact way you want it. Even if you use distutils' data_files feature, you're still going to have to have your javascript files copied into your Python project directory (i.e., somewhere under the same directory as you...
[ 2 ]
[]
[]
[ "javascript", "project_structure", "python", "setuptools" ]
stackoverflow_0002891575_javascript_project_structure_python_setuptools.txt
Q: Getting Omni complete to work on vim 7.2 on windows I am trying to use the Omni complete feature with gVim 7.2 but on windows I keep getting an error that says Error: require vim compiled with +python E117: unknown function: pythoncomplete#complete seems like it might be because gvim 7.2 is compiled with 2.4 and ...
Getting Omni complete to work on vim 7.2 on windows
I am trying to use the Omni complete feature with gVim 7.2 but on windows I keep getting an error that says Error: require vim compiled with +python E117: unknown function: pythoncomplete#complete seems like it might be because gvim 7.2 is compiled with 2.4 and I have 2.5 installed. I have downloaded the 2.5 compiled ...
[ "The Cygwin Python won't work. Just install the Windows Python from http://python.org.\nI had the same problem, but with a plugin - pyflakes. I solved it by installing Python 2.6 FOR ALL USERS, and using a gvim.exe binary downloaded from here:\nhttp://www.gooli.org/blog/gvim-72-with-python-2526-support-windows-bina...
[ 1 ]
[]
[]
[ "python", "vim" ]
stackoverflow_0002897022_python_vim.txt
Q: How to include and use .eggs/pkg_resources within a project directory targeting python 2.5.1 I have python .egg files that are stored in a relative location to some .py code. The problem is, I am targeting python 2.5.1 computers which require my project be self contained in a folder (hundreds of thousands of OLPC...
How to include and use .eggs/pkg_resources within a project directory targeting python 2.5.1
I have python .egg files that are stored in a relative location to some .py code. The problem is, I am targeting python 2.5.1 computers which require my project be self contained in a folder (hundreds of thousands of OLPC XO 8.2.1 release laptops running Sugar). This means I cannot just ./ez_install to perform a syst...
[ "If you want to be able to use pkg_resources, just copy pkg_resources.py alongside your application's main script. It's designed to be able to be used this way as a standalone runtime.\n", "Include pkg_resources.py in the lib/ directory.\nAdd at the top of example.py...\n import sys\n sys.path.append(\"lib/\...
[ 1, 0 ]
[]
[]
[ "egg", "olpc", "python", "python_2.5" ]
stackoverflow_0001252910_egg_olpc_python_python_2.5.txt
Q: Compiling ODE on windows without Visual Studio (for PyODE) I'm new to compiling programs written by someone else, so I hope I'm not missing anything obvious. What I am really trying to do is install PyODE, and I think I managed that just fine, but when running the PyODE examples I get an error: Traceback (most rec...
Compiling ODE on windows without Visual Studio (for PyODE)
I'm new to compiling programs written by someone else, so I hope I'm not missing anything obvious. What I am really trying to do is install PyODE, and I think I managed that just fine, but when running the PyODE examples I get an error: Traceback (most recent call last): File "C:\Python26\pyode-examples\tutorial3.py"...
[ "My Problem was completley unrelated to whether or not you could compile ODE without visual studio.\nSimply copied ODE.dll which was in the python directory into the example's directory.\nThanks Thomas! :)\n" ]
[ 0 ]
[]
[]
[ "dll", "pyode", "python", "windows" ]
stackoverflow_0002897590_dll_pyode_python_windows.txt
Q: Problem trying to achieve a join using the `comments` contrib in Django I have this model, comments are managed with the django_comments contrib: class Fortune(models.Model): author = models.CharField(max_length=45, blank=False) title = models.CharField(max_length=200, blank=False) slug = models.SlugFi...
Problem trying to achieve a join using the `comments` contrib in Django
I have this model, comments are managed with the django_comments contrib: class Fortune(models.Model): author = models.CharField(max_length=45, blank=False) title = models.CharField(max_length=200, blank=False) slug = models.SlugField(_('slug'), db_index=True, max_length=255, unique_for_date='pub_date') ...
[ "http://charlesleifer.com/blog/generating-aggregate-data-across-generic-relations/\nhttp://djangosnippets.org/snippets/2034/\nUPDATE:\nhttp://github.com/coleifer/django-generic-aggregation/\n", "Why do you want to join the content type table? The original query is wrong, but not for that reason. The reference to ...
[ 3, 2, 2 ]
[]
[]
[ "django", "django_models", "orm", "python", "sql" ]
stackoverflow_0002754320_django_django_models_orm_python_sql.txt