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: help required using a class in extension dll through ctypes I have written the following code in visual studio to create an extension dll. class A { public: void someFunc() { } }; extern "C" __declspec(dllexport) A* A_new() { return new A(); } extern "C" __declspec(dllexpor...
help required using a class in extension dll through ctypes
I have written the following code in visual studio to create an extension dll. class A { public: void someFunc() { } }; extern "C" __declspec(dllexport) A* A_new() { return new A(); } extern "C" __declspec(dllexport) void A_someFunc(A* obj) { obj->someFunc(); } ex...
[ "Your exports use the cdecl calling convention, not stdcall, so you need to use CDLL instead of WinDLL. \ntest.cpp:\n#include <iostream>\n#include <string>\nusing namespace std;\n\nclass A {\n string name;\n public: \n A(const string& name) {\n this->name = name;\n cout << ...
[ 4, 0 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0007161349_ctypes_python.txt
Q: File naming problem with Python I am trying to iterate through a number .rtf files and for each file: read the file, perform some operations, and then write new files into a sub-directory as plain text files with the same name as the original file, but with .txt extensions. The problem I am having is with the file...
File naming problem with Python
I am trying to iterate through a number .rtf files and for each file: read the file, perform some operations, and then write new files into a sub-directory as plain text files with the same name as the original file, but with .txt extensions. The problem I am having is with the file naming. If a file is named foo.rtf, ...
[ "Instead of item.replace, check out some of the functions in the os.path module (http://docs.python.org/library/os.path.html). They're made for splitting up and recombining parts of filenames. For instance, os.path.splitext will split a filename into a file path and a file extension.\nLet's say you have a file /t...
[ 3, 2, 0 ]
[]
[]
[ "mkdir", "python" ]
stackoverflow_0007178125_mkdir_python.txt
Q: Using python datetime.datetime.strptime on windows with BST timezone I need to parse many different dates in many different formats. I am having trouble with the following and wondered if anyopne could explain why; The following works on a linux system: from datetime import datetime datetime.strptime('Tue 23 Aug 2...
Using python datetime.datetime.strptime on windows with BST timezone
I need to parse many different dates in many different formats. I am having trouble with the following and wondered if anyopne could explain why; The following works on a linux system: from datetime import datetime datetime.strptime('Tue 23 Aug 2011 09:00:07 PM BST','%a %d %b %Y %H:%M:%S %p %Z') But running under wind...
[ "In my opinion, parsing a three-letter time zone code like this is not a good practice (unless of course you have no choice). For example, \"EST\" is commonly used in the USA for UTC-4/5 and is also commonly used in Australia. So any support for \"EST\" must therefore be dependent on locale. It would not surpris...
[ 1 ]
[]
[]
[ "binary_search_tree", "python", "strptime", "timezone", "windows" ]
stackoverflow_0007177860_binary_search_tree_python_strptime_timezone_windows.txt
Q: python xml.dom parsing problems I am writing a program in which the first step takes an URL address and opens the page. Then it puts the content into the xml.dom.minidom parser: from xml.dom.minidom import parse page = urllib2.urlopen(page_url) parser = parse(page) The problem is that a lot of pages have mismatc...
python xml.dom parsing problems
I am writing a program in which the first step takes an URL address and opens the page. Then it puts the content into the xml.dom.minidom parser: from xml.dom.minidom import parse page = urllib2.urlopen(page_url) parser = parse(page) The problem is that a lot of pages have mismatched tags and special characters so th...
[ "I prefer lxml.html, it's very robust, and lxml in general is quite fast and has very nice capabilities, including XPath support.\nimport lxml.html\n\ndoc = lxml.html.parse('http://example.com')\n\n" ]
[ 2 ]
[]
[]
[ "html_parsing", "python", "xml" ]
stackoverflow_0007178341_html_parsing_python_xml.txt
Q: twisted manhole: how to access servers in application? I need to connect to my twisted application at runtime and I am trying to get twisted.manhole to work for me to that end. I am on Mac OSX 10.6 with twisted 8.2 as installed by default. The sample server using twistd works. There are DeprecationWarnings at star...
twisted manhole: how to access servers in application?
I need to connect to my twisted application at runtime and I am trying to get twisted.manhole to work for me to that end. I am on Mac OSX 10.6 with twisted 8.2 as installed by default. The sample server using twistd works. There are DeprecationWarnings at startup about md5, sha and twisted.protocols.telnet, but the man...
[ "Keep using twisted.conch and put something in the namespace dictionary.\nnamespace = {\"your_application_object\": some_object}\n\noptions = {\n # for some reason, these must\n # all exist, even if None\n 'namespace' : namespace,\n 'passwd' : 'users.txt',\n 'sshPort' : None,\n 'telnetPort...
[ 5 ]
[]
[]
[ "python", "telnet", "twisted" ]
stackoverflow_0007172508_python_telnet_twisted.txt
Q: Getting rid of JQuery DatePicker in a Selenium test I am writing a Selenium test to populate a date field on a webpage. The field is associated with a JQuery Date Picker. When I use the 'type' function to enter the date, the picker pops up. However, I cannot get it to go away, even if I shift focus, click on anoth...
Getting rid of JQuery DatePicker in a Selenium test
I am writing a Selenium test to populate a date field on a webpage. The field is associated with a JQuery Date Picker. When I use the 'type' function to enter the date, the picker pops up. However, I cannot get it to go away, even if I shift focus, click on another field etc. I've tried the following till now... # Pyth...
[ "i guess,\nyou don't need to use sle.focus() function as you are using sel.type() and it supplied with\nelement id.so it knows where to type the value. i think sel.focus() is causing the date field to pop-up the jquery date picker earlier.\nif this is not solved please post the HTML code to see where exactly that J...
[ 0, 0 ]
[]
[]
[ "jquery_ui", "python", "selenium", "selenium_rc", "testing" ]
stackoverflow_0007100068_jquery_ui_python_selenium_selenium_rc_testing.txt
Q: Django template blocks not showing? I'm having a problem with displaying the contents within the block tags of a child template. I have a base.html and a dash.html which extends the base. When I go to the dash.html page the base.html is extended but the contents set within the block tags of dash.html do not show u...
Django template blocks not showing?
I'm having a problem with displaying the contents within the block tags of a child template. I have a base.html and a dash.html which extends the base. When I go to the dash.html page the base.html is extended but the contents set within the block tags of dash.html do not show up. So I get the same thing when I go base...
[ "I just copied & pasted this code into a new project and it is working for me. What does your urls.py look like? Is it possible you are sending your dash url to the index view? Here is the quick urls.py that I wrote to get this up and running:\nfrom django.conf.urls.defaults import *\nimport views\n\nurlpatterns = ...
[ 2 ]
[]
[]
[ "django", "django_templates", "django_views", "html", "python" ]
stackoverflow_0007179137_django_django_templates_django_views_html_python.txt
Q: 0mq one-to-many connection What is the most correct way to establish a two-way communication between processes using 0mq? I need to create several background processes that will wait for commands from the main process, perform some calculations and return the result back to the main process. A: There are a fe...
0mq one-to-many connection
What is the most correct way to establish a two-way communication between processes using 0mq? I need to create several background processes that will wait for commands from the main process, perform some calculations and return the result back to the main process.
[ "There are a few ways to do this. The most straight forward approach might be to use REQ/REP sockets. Each background process/worker would have a REP socket, and you would use a REQ socket to communicate with them:\nimport zmq\n\ndef worker(addr):\n context = zmq.Context()\n socket = context.socket(zmq.REP)\n...
[ 7, 3 ]
[]
[]
[ "multithreading", "python", "zeromq" ]
stackoverflow_0007178384_multithreading_python_zeromq.txt
Q: Using Jenkins to run site up time and verification tests I'm wondering if Jenkins could (and should) be used to run various checks that I need to perform a few times a day. For example: sites accessible are dev sites password protected are checkout pages using SSL can an order be placed on each shop? are all p...
Using Jenkins to run site up time and verification tests
I'm wondering if Jenkins could (and should) be used to run various checks that I need to perform a few times a day. For example: sites accessible are dev sites password protected are checkout pages using SSL can an order be placed on each shop? are all pages accessible? e.g. no 404s are the correct databases being ...
[ "Jenkins is really just a job scheduler at its core, so there's no reason why you shouldn't use it for monitoring. However, you'd have to write your own scripts for most of the tasks you listed, whereas if you use a dedicated monitoring tool such as Nagios or Zabbix, you'll get all that functionality built in.\n",...
[ 3, 1 ]
[]
[]
[ "jenkins", "python", "selenium", "unit_testing" ]
stackoverflow_0007176727_jenkins_python_selenium_unit_testing.txt
Q: Starting a subprocess via python multiprocessing hangs I'm using pyAudio to listen to the audio device and do some "stuff" in the background while the main program continues to run. I started out with a second script, but would like to consolidate into a single script for supportability. When I moved the functions...
Starting a subprocess via python multiprocessing hangs
I'm using pyAudio to listen to the audio device and do some "stuff" in the background while the main program continues to run. I started out with a second script, but would like to consolidate into a single script for supportability. When I moved the functions in and use Process to start up the listener it simply hangs...
[ "The __init__ method for pyaudio.open() is:\n__init__(self, PA_manager, rate, channels, format, input=False, output=False, input_device_index=None, output_device_index=None, frames_per_buffer=1024, start=True, input_host_api_specific_stream_info=None, output_host_api_specific_stream_info=None) \n\nAccording to the ...
[ 1 ]
[]
[]
[ "debugging", "multiprocessing", "pyaudio", "python" ]
stackoverflow_0006203020_debugging_multiprocessing_pyaudio_python.txt
Q: How can I get a value in the scope of loop and use it outside the loop in Python Can someone assist me in thinking my way through this problem. In the code below, I'm taking a list and opening all of the .log and .txt files, as to search them for a particular string. In the inner most for loop there is an if and e...
How can I get a value in the scope of loop and use it outside the loop in Python
Can someone assist me in thinking my way through this problem. In the code below, I'm taking a list and opening all of the .log and .txt files, as to search them for a particular string. In the inner most for loop there is an if and else statement that determines if a string was found or not. I want to count the number...
[ "How about this:\ncount = 0\nfor afile in filelist:\n (head, filename) = os.path.split(afile)\n if afile.endswith(\".log\") or afile.endswith(\".txt\"):\n f=ftp.open(afile, 'r')\n for i, line in enumerate(f.readlines()):\n result = regex.search(line)\n if result:\n ...
[ 3 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0007180119_for_loop_python.txt
Q: How does one draw a tilted ellipse in ImageDraw? I am trying to draw a tilted ellipse in image draw. However, I am not sure how to define it, since while the scheme below would move the points, I think this would just squish the ellipse, not rotate it (also I think there is something slightly wrong with the transf...
How does one draw a tilted ellipse in ImageDraw?
I am trying to draw a tilted ellipse in image draw. However, I am not sure how to define it, since while the scheme below would move the points, I think this would just squish the ellipse, not rotate it (also I think there is something slightly wrong with the transformation in any case). I am feeding the output of this...
[ "It looks like the 'box' that is being used to draw the ellipse has no rotation associated with it. It is simply defined by the (left, top, right, bottom) extents.\nOne possible workaround (depending on what you need to do) is to draw the ellipse (sized correctly, but without the rotation) onto an intermediary ima...
[ 2 ]
[]
[]
[ "drawing", "image", "python", "python_imaging_library" ]
stackoverflow_0007178625_drawing_image_python_python_imaging_library.txt
Q: How to check if some process is running in task manager with python I have one function in python which should start running when some process (eg. proc.exe) showed up in tasks manager. How can I monitor processes running in tasks manager with python? A: here is something, I've adapted from microsoft import win...
How to check if some process is running in task manager with python
I have one function in python which should start running when some process (eg. proc.exe) showed up in tasks manager. How can I monitor processes running in tasks manager with python?
[ "here is something, I've adapted from microsoft\n\nimport win32com.client\nstrComputer = \".\"\nobjWMIService = win32com.client.Dispatch(\"WbemScripting.SWbemLocator\")\nobjSWbemServices = objWMIService.ConnectServer(strComputer,\"root\\cimv2\")\ncolItems = objSWbemServices.ExecQuery(\"Select * from Win32_Process\"...
[ 10, 0 ]
[]
[]
[ "process", "python" ]
stackoverflow_0001187264_process_python.txt
Q: How to upload multiple files to BlobStore? I'm trying to upload multiple files in a form to the BlobStore. Form: <form action="{{upload_url}}" method="POST" enctype="multipart/form-data"> <label>Key Name</label><input type="text" name="key_name" size="50"><br/> <label>name</label><input type="text" name="name"...
How to upload multiple files to BlobStore?
I'm trying to upload multiple files in a form to the BlobStore. Form: <form action="{{upload_url}}" method="POST" enctype="multipart/form-data"> <label>Key Name</label><input type="text" name="key_name" size="50"><br/> <label>name</label><input type="text" name="name" size="50"><br/> <label>image</label><input ty...
[ "Each file needs its own unique upload url, so my guess is something wacky is happening when all three files are posted to the same url.\nThe best solution for supporting multiple file uploads is described in Nick Johnson's blog post:\nhttp://blog.notdot.net/2010/04/Implementing-a-dropbox-service-with-the-Blobstore...
[ 5, 1, 0 ]
[]
[]
[ "blobstore", "forms", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0004762779_blobstore_forms_google_app_engine_google_cloud_datastore_python.txt
Q: File Write Attempt Silently Fails - Permissions Problem I am attempting to write a small portion of text to an (as yet) non-existing file to an directory owned by the root user and group. I have had a look at the Python docs regarding checking if a user is authorised to write files - the code below reflects the do...
File Write Attempt Silently Fails - Permissions Problem
I am attempting to write a small portion of text to an (as yet) non-existing file to an directory owned by the root user and group. I have had a look at the Python docs regarding checking if a user is authorised to write files - the code below reflects the doc example. Here's the offending bit of code: try: out = o...
[ "EACCESS should be EACCES (derived from the standard unix C libs.) That wouldn't cause you not to see an error however as IOERROR would get raised and you're re-raising even if the if block doesn't execute. This sounds like a linux specific issue. Probably SELinux.\nBTW a context manager would be useful to avoid th...
[ 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0007091100_file_python.txt
Q: Python: modify strings stored in various objects inplace in a loop I have strings stored in various objects, for example a, b, c[2:7] (ie 5 different strings c[2],...c[6]), d.s, e.s[:] (ie all strings stored in the e.s list). I need to loop over all these strings on various places in the code and modify these vari...
Python: modify strings stored in various objects inplace in a loop
I have strings stored in various objects, for example a, b, c[2:7] (ie 5 different strings c[2],...c[6]), d.s, e.s[:] (ie all strings stored in the e.s list). I need to loop over all these strings on various places in the code and modify these variables in the loops. (Assigning the modified strings to new variables wou...
[ "Your do_string_modifications functions need to be changed so that they return the new string value instead of attempting to modify it in place (since that is not possible). Use your new functions to modify the list, and reassign the original string references to the new values in the list after the modification (...
[ 1, 1, 0, 0 ]
[]
[]
[ "iteration", "mutable", "python", "reference", "string" ]
stackoverflow_0007178985_iteration_mutable_python_reference_string.txt
Q: python syntax error w3af I am getting a syntax error in a python file and I'm really new to python. if o in ('-r', '--revision'): doupdate = True a = a.upper() if a in ('HEAD', 'PREV'): rev = 0 if (a == 'HEAD') else -1 else: try: ...
python syntax error w3af
I am getting a syntax error in a python file and I'm really new to python. if o in ('-r', '--revision'): doupdate = True a = a.upper() if a in ('HEAD', 'PREV'): rev = 0 if (a == 'HEAD') else -1 else: try: rev = int(a) ...
[ "You must be using an old version of Python.\nThe if-expression was added in 2.5.\nYour code compiles fine for me.\n" ]
[ 1 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0007180288_python_syntax.txt
Q: Why can't generators be pickled? Python's pickle (I'm talking standard Python 2.5/2.6/2.7 here) cannot pickle locks, file objects etc. It also cannot pickle generators and lambda expressions (or any other anonymous code), because the pickle really only stores name references. In case of locks and OS-dependent fea...
Why can't generators be pickled?
Python's pickle (I'm talking standard Python 2.5/2.6/2.7 here) cannot pickle locks, file objects etc. It also cannot pickle generators and lambda expressions (or any other anonymous code), because the pickle really only stores name references. In case of locks and OS-dependent features, the reason why you cannot pickl...
[ "There is lots of information about this available. For the \"official word\" on the issue, read the (closed) Python bugtracker issue.\nThe core reasoning, by one of the people who made the decision, is detailed on this blog:\n\nSince a generator is essentially a souped-up function, we would need to save its byteco...
[ 56, 27 ]
[]
[]
[ "generator", "pickle", "python", "python_stackless" ]
stackoverflow_0007180212_generator_pickle_python_python_stackless.txt
Q: Extracting pair of values from matrix using python I have matrix as follows.. 31348 439352 6077 4619722 60825 31348 1 0.304 0.126 0.12 0.162 439352 0.304 1 0.101 0.095 0.316 6077 0.126 0.101 1 0.473 0.219 4619722 0.12 0.095...
Extracting pair of values from matrix using python
I have matrix as follows.. 31348 439352 6077 4619722 60825 31348 1 0.304 0.126 0.12 0.162 439352 0.304 1 0.101 0.095 0.316 6077 0.126 0.101 1 0.473 0.219 4619722 0.12 0.095 0.473 1 0.256 60825 0.162 0.316 ...
[ "mylist = []\n\nwith open('test.csv') as f:\n keys = f.readline()\n keys = keys.split()\n\n for line in f:\n a = line.split()\n mylist.append(a[1:])\n\nfor idx1, item in enumerate(mylist):\n for idx2, number in enumerate(item):\n if float(number) > 0.2:\n print \"%7s, %7s...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0007180023_python.txt
Q: AJAX between a static webpage and google app-engine server sharing same TLD I have the main website hosted by a reliable static web hosting service. Which only allow me to host static files like html, css, js etc. Now I have few requirements which would need user Login and data storage. I think I can handle this u...
AJAX between a static webpage and google app-engine server sharing same TLD
I have the main website hosted by a reliable static web hosting service. Which only allow me to host static files like html, css, js etc. Now I have few requirements which would need user Login and data storage. I think I can handle this using App Engine Python. My app is similar to a Voting module, So i will explain i...
[ "You need to use JSONP.\nSubdomains actually violate the same origin policy. This is because some hosted solutions provide subdomains for different users. This would allow users to attack each other's sites.\nSee: Same Origin Policy - AJAX & using Public APIs\n", "You can maintain login between the two sub-domain...
[ 3, 0 ]
[]
[]
[ "google_app_engine", "javascript", "python", "same_origin_policy" ]
stackoverflow_0007180386_google_app_engine_javascript_python_same_origin_policy.txt
Q: How to access Google App Engine's dev server data from the command line I regularly download my Google App Engine production data locally (using a custom script that basically calls appcfg.py download_data) and upload it to the development server so that the data in my development environment matches production. Y...
How to access Google App Engine's dev server data from the command line
I regularly download my Google App Engine production data locally (using a custom script that basically calls appcfg.py download_data) and upload it to the development server so that the data in my development environment matches production. You can find the scripts on Launchpad: Download script (called with ./extra/m...
[ "The trick is to add the --default_partition= argument to the ParseArguments() call in the script that accesses the GAE data:\nargs, option_dict = ParseArguments(['', colCasaBasePath, \"--default_partition=\"])\n\nNote that there is nothing after the =, that's what put me off. I first tried adding \"--default_parti...
[ 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0007166697_google_app_engine_google_cloud_datastore_python.txt
Q: Django: when I try to access localhost, it displays an empty object list Please help me. When I trying to access http://127.0.0.1:8000/myblog/ It display empty object list. Here is my template file. {% extends "base_entries.html" %} {% block title %}{{block.super}} | Latest entries{% endblock %} {% block content %...
Django: when I try to access localhost, it displays an empty object list
Please help me. When I trying to access http://127.0.0.1:8000/myblog/ It display empty object list. Here is my template file. {% extends "base_entries.html" %} {% block title %}{{block.super}} | Latest entries{% endblock %} {% block content %} {% for entry in object_list %} <h2>{{entry.title}}</h2> <p>Published on {{en...
[ "In archive_index generic view, the default name of the template variable is latest, not object_list.\narchive_index documentation\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007174379_django_python.txt
Q: Software install automation I work at a computer software installation center - our users run Windows. Some of the software is difficult to install for new employees. I would like to automate the setup of software using either Python or Java. How should I fill in the information in the setup dialogs and moving th...
Software install automation
I work at a computer software installation center - our users run Windows. Some of the software is difficult to install for new employees. I would like to automate the setup of software using either Python or Java. How should I fill in the information in the setup dialogs and moving through the setup process automatic...
[ "I used pywinauto to automate GUIs, which should also work well for installation forms.\n", "---- Edited as the solution is obviously talking about Windows / MSI ----\nMSI supports the passing of configuration parameters on the command line. Look into it. Unless they are doing something truly exotic, or they pa...
[ 1, 1, 0 ]
[]
[]
[ "deployment", "installation", "java", "python", "windows" ]
stackoverflow_0007178290_deployment_installation_java_python_windows.txt
Q: Using os.system asynchronous, independ from the python process? When using os.system to open a file, eg: os.system(r'C:/foo.txt'), the current Python process, of course, waits until the system-call returns. (ie.: the text-editor closes). Do I have to use a Thread to make this asynchronous ? Imagine the following s...
Using os.system asynchronous, independ from the python process?
When using os.system to open a file, eg: os.system(r'C:/foo.txt'), the current Python process, of course, waits until the system-call returns. (ie.: the text-editor closes). Do I have to use a Thread to make this asynchronous ? Imagine the following situation: I'm writing a File-manager for Windows using Python. The us...
[ "If you want to open a file on windows with the default program, there's a special function that opens it asynchronously and independently of your own program: os.startfile. This should do what you want.\nMore generally, for running programs asynchronously, os.system can't do it. However, the subprocess module can....
[ 5 ]
[]
[]
[ "asynchronous", "process", "python", "system" ]
stackoverflow_0007180857_asynchronous_process_python_system.txt
Q: Python lxml changes tag hierarchy? I'm having a small issue with lxml. I'm converting an XML doc into an HTML doc. The original XML looks like this (it looks like HTML, but it's in the XML doc): <p>Localization - Eiffel tower? Paris or Vegas <p>Bayes theorem p(A|B)</p></p> When I do this (item is the string above...
Python lxml changes tag hierarchy?
I'm having a small issue with lxml. I'm converting an XML doc into an HTML doc. The original XML looks like this (it looks like HTML, but it's in the XML doc): <p>Localization - Eiffel tower? Paris or Vegas <p>Bayes theorem p(A|B)</p></p> When I do this (item is the string above) lxml.html.tostring(lxml.html.fromstrin...
[ "lxml is doing this because it doesn't store invalid HTML, and <p> elements can't be nested in HTML:\n\nThe P element represents a paragraph. It cannot contain block-level elements (including P itself).\n\n", "You're using lxml's HTML parser, not an XML parser. Try this instead:\n>>> from lxml import etree\n>>> ...
[ 12, 1 ]
[]
[]
[ "html", "lxml", "python", "xml" ]
stackoverflow_0007180919_html_lxml_python_xml.txt
Q: How to identify if the current selected row is the last on a gtk.TreeView? I am sorry if this looks a trivial question but I am still new to the complexity of the View/model/store scheme require to use the GTK Treeview. How to identify if the current selected item is the last item on a gtk.TreeView ? I don't have ...
How to identify if the current selected row is the last on a gtk.TreeView?
I am sorry if this looks a trivial question but I am still new to the complexity of the View/model/store scheme require to use the GTK Treeview. How to identify if the current selected item is the last item on a gtk.TreeView ? I don't have children so right now each node is just a row.
[ "To do that, you have to ask the view what row is selected, then ask the model whether that row is the last one. Like so:\nselection = view.get_selection()\nmodel, iter = selection.get_selected()\nif iter is None:\n print \"Nothing selected\"\nelse:\n if model.iter_next(iter) is not None:\n print \"Sel...
[ 3 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0007179558_gtk_pygtk_python.txt
Q: kinit using Python subprocess I'm trying to connect to a remote server via subprocess + ssh to list the files in a directory and print the content of a file in that directory. To do that I need to run kinit as a Python subprocess.Any idea on how to do that? assume the user logged on using their kerberos id and pas...
kinit using Python subprocess
I'm trying to connect to a remote server via subprocess + ssh to list the files in a directory and print the content of a file in that directory. To do that I need to run kinit as a Python subprocess.Any idea on how to do that? assume the user logged on using their kerberos id and password.. Thank you.
[ "If you want to run kinit to make the user get a Kerberos ticket, you can just prompt for their password (e.g. using the getpass module) and then pass that input to the subprocess.\nThis looks something like this:\nfrom subprocess import Popen, PIPE\n\nkinit = '/usr/bin/kinit'\nkinit_args = [ kinit, '%s@%s' % (user...
[ 7 ]
[]
[]
[ "python", "ssh", "subprocess" ]
stackoverflow_0007181263_python_ssh_subprocess.txt
Q: Send an authenticated POST request to tastypie I am trying to send an ApiKey-autheticated POST request to a tastypie API my Model: class Thing(models.Model): name = models.TextField() def __unicode__(self): return u'%s'%self.name my ModelResource class ThingResource(ModelResource): class Meta...
Send an authenticated POST request to tastypie
I am trying to send an ApiKey-autheticated POST request to a tastypie API my Model: class Thing(models.Model): name = models.TextField() def __unicode__(self): return u'%s'%self.name my ModelResource class ThingResource(ModelResource): class Meta: queryset = Thing.objects.all() res...
[ "Using the -d and --data with curl is mangling the POSTed data. \nIncluding the username and api_key params in the GET should solve this, like so:\n curl --dump-header - -H \"Accept: application/json\"\\\n -H \"Content-Type: application/json\" -X POST\\\n --data \"{\\\"name\\\":\\\"arrrg\\\"}\"\\\n \"h...
[ 9, 6 ]
[]
[]
[ "curl", "django", "python", "tastypie" ]
stackoverflow_0007149866_curl_django_python_tastypie.txt
Q: To compare two lists and find the similarities I have a list like this one: C E I want to find these in the following tables (table 1) and write them into the second table (table 2) Does anyone have a python or perl script to do this? Table 1: A MU_ADO_2 1099 MU_ADO_2.1099 o o o o o o o ...
To compare two lists and find the similarities
I have a list like this one: C E I want to find these in the following tables (table 1) and write them into the second table (table 2) Does anyone have a python or perl script to do this? Table 1: A MU_ADO_2 1099 MU_ADO_2.1099 o o o o o o o o o o 7.82436 s_3_merged Suseptible A AG ...
[ "Since you included the awk tag I'm assuming you are open to other *nix utilities, here is a sed solution:\nsed '/^[^CE]/d' table1.txt > table2.txt\n\nThis will remove all lines from table1.txt that do not start with C or E.\n", "How about grep\ngrep -e '^[CE]' source.file\n\nand you can redirect that into a new ...
[ 3, 3, 1, 1, 0 ]
[]
[]
[ "awk", "perl", "python" ]
stackoverflow_0007180873_awk_perl_python.txt
Q: Explain me this python expression in C# What is the C# equivalent of this python expression? file_no = int (last_file.Name.Replace(last_file.Extension,"")[-3:]); I understand what [-3:] does but not the (int) cast. A: It replaces the extension of a filename with the empty string, takes the last three characters...
Explain me this python expression in C#
What is the C# equivalent of this python expression? file_no = int (last_file.Name.Replace(last_file.Extension,"")[-3:]); I understand what [-3:] does but not the (int) cast.
[ "It replaces the extension of a filename with the empty string, takes the last three characters as a string and tries to convert to an int.\nSo if last_file is jamesbond007.secretagent and last_file.Extension is .secretagent then file_no becomes 7 because .secretagent is replaced by the empty string, and the last t...
[ 5, 4, 2, 1, 0 ]
[]
[]
[ "c#", "ironpython", "python" ]
stackoverflow_0007181897_c#_ironpython_python.txt
Q: Python CSV Module read and write simultaneously I have two .csv files I am looking up data in one (file a) and matching it to the other (file b) once I find the appropriate row in b I want to write to a specific cell in the appropriate row. Additionally I need to iterate over this so I will likely be writing to e...
Python CSV Module read and write simultaneously
I have two .csv files I am looking up data in one (file a) and matching it to the other (file b) once I find the appropriate row in b I want to write to a specific cell in the appropriate row. Additionally I need to iterate over this so I will likely be writing to each row in file b potentially several times. can I w...
[ "If file b is not extremely large I would suggest using readlines() to get a list of all lines and then iterate over the list and change lines as needed. This will be quite a bit easier than seeking to different positions in the file and replacing lines.\nAlso, you can significantly reduce the code in the body of ...
[ 2, 1, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0007181977_csv_python.txt
Q: Django manage.py question Why is it that I have to run python manage.py somecommand and others simply run manage.py somecommand? I'm on OSX 10.6. Is this because there is a pre-set way to enable .py files to automatically run as Python scripts, and I've somehow disabled the functionality, or is that something that...
Django manage.py question
Why is it that I have to run python manage.py somecommand and others simply run manage.py somecommand? I'm on OSX 10.6. Is this because there is a pre-set way to enable .py files to automatically run as Python scripts, and I've somehow disabled the functionality, or is that something that you explicitly enable?
[ "If you are using a recent version of Django, the manage.py file should be an \"executable\" file by default.\nPlease note, you cannot just type manage.py somecommand into the terminal as manage.py is not on the PATH, you will have to type ./ before it to run it from the current directory, i.e. ./manage.py somecomm...
[ 6, 1, 1 ]
[]
[]
[ "command_line", "django", "python" ]
stackoverflow_0007182165_command_line_django_python.txt
Q: Python: multiple packages with multiple setup.py files I'm having a hard time constructing my Python setup.py files to do what I want. I have one pacakge set up like this: somestuff_root/ setup.py myutils/ __init__.py a/ __init__.py somestuff.py I have another packa...
Python: multiple packages with multiple setup.py files
I'm having a hard time constructing my Python setup.py files to do what I want. I have one pacakge set up like this: somestuff_root/ setup.py myutils/ __init__.py a/ __init__.py somestuff.py I have another package setup like this: otherstuff_root/ setup.py myutil...
[ "If I'm understanding this correctly, what you are trying to set up is a namespace package (an empty package that contains other, separately installed packages), which is a feature of setuptools.\nCall setuptools.setup() with a list of packages that are namespaces for the namespace_packages argument.\nsetup(..., na...
[ 9 ]
[]
[]
[ "namespace_package", "package", "python", "setup.py" ]
stackoverflow_0007182117_namespace_package_package_python_setup.py.txt
Q: Is my HelloWorld queue working? I'm about to put this design into use in an application, but I'm fairly new to threading and Queue stuff in python. Obviously the actual application is not for saying hello, but the design is the same - i.e. there is a process which takes some time to set-up and tear down, but I ca...
Is my HelloWorld queue working?
I'm about to put this design into use in an application, but I'm fairly new to threading and Queue stuff in python. Obviously the actual application is not for saying hello, but the design is the same - i.e. there is a process which takes some time to set-up and tear down, but I can do multiple tasks in one hit. Task...
[ "\nThe thread safety is handled by Queue implementation (also you must handle in your _say_hello implementation if it is required).\nBurst handler problem: A burst should be handled by a single thread only.(ex: let's say your process setup/teardown takes 10 seconds; at second 1 all threads will be busy with burst f...
[ 0 ]
[]
[]
[ "multithreading", "python", "queue" ]
stackoverflow_0007169797_multithreading_python_queue.txt
Q: How to avoid using readlines()? I need to deal with super large txt input files, and I usually use .readlines() to first read the whole file, and turn it into a list. I know it's really memory-cost and can be quite slow, but I also need to make use of LIST characteristics to manipulate the specific lines, like bel...
How to avoid using readlines()?
I need to deal with super large txt input files, and I usually use .readlines() to first read the whole file, and turn it into a list. I know it's really memory-cost and can be quite slow, but I also need to make use of LIST characteristics to manipulate the specific lines, like below: #!/usr/bin/python import os,sys ...
[ "If you can refactor your code to read through the file linearly, then you can just say for line in file to iterate through each line of the file without reading it all into memory at once. But, since your file access looks more complicated, you could use a generator to replace readlines(). One way to do this wou...
[ 6, 2, 1, 1, 0, 0 ]
[]
[]
[ "list", "python", "readlines" ]
stackoverflow_0007178404_list_python_readlines.txt
Q: Problem passing XML to HTTP Post api using urllib in Python I am trying to access a REST api and need to call it with a line of XML for a filter condition. My apologies for providing code that others cannot access. When I execute this code, I get the error message listed below. import urllib2 import urllib import ...
Problem passing XML to HTTP Post api using urllib in Python
I am trying to access a REST api and need to call it with a line of XML for a filter condition. My apologies for providing code that others cannot access. When I execute this code, I get the error message listed below. import urllib2 import urllib import hashlib import hmac import time import random import base64 def ...
[ "So the problem was with the formatting of the form variable and the encoding I was trying to do. Revising the following lines gets the call to work. I did not need to specify the headers.\n xml_string = \"<list><FilterItems><FilterItem attribute='pageNumber' value='1'/></FilterItems></list>\"\n data = (xml_string)...
[ 4 ]
[]
[]
[ "python", "urllib2", "xml" ]
stackoverflow_0007030436_python_urllib2_xml.txt
Q: What are the proper security measures involved with opening a port with Python? Consider a very basic python socket which opens up a port to the internet on the host computer and listens for incoming messages, which are displayed in a terminal. Keeping a port wide open like this is considered fairly vulnerable, co...
What are the proper security measures involved with opening a port with Python?
Consider a very basic python socket which opens up a port to the internet on the host computer and listens for incoming messages, which are displayed in a terminal. Keeping a port wide open like this is considered fairly vulnerable, correct? What security features should I implement? Should incoming data be sanitized? ...
[ "Why would this be vulnerable? Your program accepts connections from arbitrary people (potentially on the whole Internet), and lets them display arbitrary bytes to your terminal. There is only one attack vector here: your terminal itself. If your terminal has a bug that (for example) executes bytes instead of print...
[ 6, 1 ]
[]
[]
[ "ports", "python", "security", "sockets" ]
stackoverflow_0007180811_ports_python_security_sockets.txt
Q: How to calculate cumulative moving average in Python/SQLAlchemy/Flask I'll give some context so it makes sense. I'm capturing Customer Ratings for Products in a table (Rating) and want to be able to return a Cumulative Moving Average of the ratings based on time. A basic example follows taking a rating per day: 02...
How to calculate cumulative moving average in Python/SQLAlchemy/Flask
I'll give some context so it makes sense. I'm capturing Customer Ratings for Products in a table (Rating) and want to be able to return a Cumulative Moving Average of the ratings based on time. A basic example follows taking a rating per day: 02 FEB - Rating: 5 - Cum Avg: 5 03 FEB - Rating: 4 - Cum Avg: (5+4)/2 = 4.5 0...
[ "I don't know about SQLAlchemy, but I might use an approach like this:\n\nStore the cumulative average and rating count separately from individual ratings.\nEvery time you get a new rating, update the cumulative average and rating count:\n\nnew_count = old_count + 1\nnew_average = ((old_average * old_count) + new_r...
[ 5 ]
[]
[]
[ "flask", "flask_sqlalchemy", "python", "sqlalchemy" ]
stackoverflow_0007157768_flask_flask_sqlalchemy_python_sqlalchemy.txt
Q: Why do I get a ASCII encoding error with Unicode data in Python 2.4 but not in 2.7? I have a program that, when run in Python 2.7, produces proper Unicode output to the standard output. When run in Python 2.4, I get UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-4: ordinal not in range(128...
Why do I get a ASCII encoding error with Unicode data in Python 2.4 but not in 2.7?
I have a program that, when run in Python 2.7, produces proper Unicode output to the standard output. When run in Python 2.4, I get UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-4: ordinal not in range(128). What changed between version 2.4 and 2.7 that this works now?
[ "Although I could not find any mention of it elswhere, it appears that Python 2.7 is automatically converting text to the terminal encoding, instead of throwing an error as expected.\nPython 2.7:\n> echo $LANG\nen_US.UTF-8\n> python -c 'import sys; print sys.getdefaultencoding()'\nascii\n\n> python -c 'import sys; ...
[ 7 ]
[]
[]
[ "encoding", "exception", "python", "unicode" ]
stackoverflow_0007182384_encoding_exception_python_unicode.txt
Q: How do I get the 'Resolution' from Jira with python and XML-RPC I'm using python to fetch issues from Jira with xml-rpc. It works well except it is missing the 'Resolution' field in the returned dictionary. For example 'Fixed', or 'WontFix' etc. This is how I get the issue from Jira: import xmlrpclib s = xmlrpcli...
How do I get the 'Resolution' from Jira with python and XML-RPC
I'm using python to fetch issues from Jira with xml-rpc. It works well except it is missing the 'Resolution' field in the returned dictionary. For example 'Fixed', or 'WontFix' etc. This is how I get the issue from Jira: import xmlrpclib s = xmlrpclib.ServerProxy('http://myjira.com/rpc/xmlrpc') auth = s.jira1.login('u...
[ "The answer is that the getIssue method in JiraXmlRpcService.java calls makeIssueStruct with a RemoteIssue object. The RemoteIssue object contains the Resolution field, but makeIssueStruct copies only values that are set. So if Resolution is not set, it won't appear in the Hashtable there.\n" ]
[ 2 ]
[]
[]
[ "jira", "python", "xml_rpc" ]
stackoverflow_0007159303_jira_python_xml_rpc.txt
Q: Python Socket and Thread pooling, how to get more performance? I am trying to implement a basic lib to issue HTTP GET requests. My target is to receive data through socket connections - minimalistic design to improve performance - usage with threads, thread pool(s). I have a bunch of links which I group by their h...
Python Socket and Thread pooling, how to get more performance?
I am trying to implement a basic lib to issue HTTP GET requests. My target is to receive data through socket connections - minimalistic design to improve performance - usage with threads, thread pool(s). I have a bunch of links which I group by their hostnames, so here's a simple demonstration of input URLs: hostname1....
[ "Do this. \nUse multiprocessing. http://docs.python.org/library/multiprocessing.html.\n\nWrite a worker Process which puts all of the URL's into a Queue.\nWrite a worker Process which gets a URL from a Queue and does a GET, saving a file and putting the File information into another Queue. You'll probably want m...
[ 3, 2 ]
[]
[]
[ "http_get", "multithreading", "python", "sockets", "threadpool" ]
stackoverflow_0006610769_http_get_multithreading_python_sockets_threadpool.txt
Q: Parsing Large XML file with Python lxml and Iterparse I'm attempting to write a parser using lxml and the iterparse method to step through a very large xml file containing many items. My file is of the format: <item> <title>Item 1</title> <desc>Description 1</desc> <url> <item>http://www.url1.com</item...
Parsing Large XML file with Python lxml and Iterparse
I'm attempting to write a parser using lxml and the iterparse method to step through a very large xml file containing many items. My file is of the format: <item> <title>Item 1</title> <desc>Description 1</desc> <url> <item>http://www.url1.com</item> </url> </item> <item> <title>Item 2</title> <desc>D...
[ "The entire xml is parsed anyway by the core implementation. The etree.iterparse is just a view in generator style, that provides a simple filtering by tag name (see docstring http://lxml.de/api/lxml.etree.iterparse-class.html).\nIf you want a complex filtering you should do by it's own.\nA solution: registering fo...
[ 4 ]
[]
[]
[ "iterparse", "large_files", "lxml", "python", "xml" ]
stackoverflow_0007182234_iterparse_large_files_lxml_python_xml.txt
Q: Python Tkinter Listbox: fire off a function on change? My problem is: when I click an option in a Listbox, I want a third party Text [area] to be updated with information based on the Listboxs selection. As far as I can tell though I can't see a way to harvest that event. I come from java and am used to registerin...
Python Tkinter Listbox: fire off a function on change?
My problem is: when I click an option in a Listbox, I want a third party Text [area] to be updated with information based on the Listboxs selection. As far as I can tell though I can't see a way to harvest that event. I come from java and am used to registering listeners and the like, is there a way to do something sim...
[ "use <<ListboxSelect>>:\nhttp://farmdev.com/src/secrets/decorator/tkinter/step3.html\n" ]
[ 5 ]
[]
[]
[ "events", "listbox", "listener", "python", "tkinter" ]
stackoverflow_0007182722_events_listbox_listener_python_tkinter.txt
Q: regex in python :groups and | I can't find how to proceed for a regular expression, here is an example: string = "red\\/banana 36 monkey\\/apple 14 red\\/apple 23 red\\/horse 56 bull\\/red 67 monkey\\/red 45 bull\\/shark 89" I want to do a single regex with re.match.group() which will take into account...
regex in python :groups and |
I can't find how to proceed for a regular expression, here is an example: string = "red\\/banana 36 monkey\\/apple 14 red\\/apple 23 red\\/horse 56 bull\\/red 67 monkey\\/red 45 bull\\/shark 89" I want to do a single regex with re.match.group() which will take into account only the ones like red/xxxx and th...
[ "i don't completely follow, but it sounds like you want non-capturing groups around your alternatives:\n(?:foo|bar|baz)\n\nthat lets you use | without creating a \"real\" group.\n\nupdate why doesn't this help? is this not right?\n>>> s=\"red\\\\/banana 36 monkey\\\\/apple 14 red\\\\/apple 23 red\\\\/horse 56...
[ 3, 1 ]
[]
[]
[ "python", "regex", "regex_group" ]
stackoverflow_0007182516_python_regex_regex_group.txt
Q: Why is Python throwing an 'OverFlow' exception on float calculation? I'm just starting to get into learning Python (Sorry, don't claim homework on this one, because it's not). Just to give myself some meaningful exercises to do to get better with the syntax and features, I've been following this URL: http://www.c...
Why is Python throwing an 'OverFlow' exception on float calculation?
I'm just starting to get into learning Python (Sorry, don't claim homework on this one, because it's not). Just to give myself some meaningful exercises to do to get better with the syntax and features, I've been following this URL: http://www.cs.washington.edu/homes/stepp/bridge/2007/exercises.html This particular 'O...
[ "input() only gives you a float if it actually sees something that looks like a float; if it looks like an integer then you will get an integer. Use float(raw_input()) instead.\nNow, as to the overflow.\nOlder versions of Python did not promote int to long automatically, meaning that the maximum integer you can hav...
[ 2 ]
[]
[]
[ "floating_point", "overflow", "python" ]
stackoverflow_0007183889_floating_point_overflow_python.txt
Q: GAE: Unit testing DeadlineExceededError I've been using testbed, webtest, and nose to test my Python GAE app, and it is a great setup. I'm now implementing something similar to Nick's great example of using the deferred library, but I can't figure out a good way to test the parts of the code triggered by Deadline...
GAE: Unit testing DeadlineExceededError
I've been using testbed, webtest, and nose to test my Python GAE app, and it is a great setup. I'm now implementing something similar to Nick's great example of using the deferred library, but I can't figure out a good way to test the parts of the code triggered by DeadlineExceededError. Since this is in the context...
[ "Abstract the \"GAE context\" for your code. in production provide real \"GAE implementation\" for testing provide a mock own that will raise the DeadlineExceededError. The test should not depend on any timeout, should be fast.\nSample abstraction (just glue):\nclass AbstractGAETaskContext(object):\n def task_spir...
[ 1 ]
[]
[]
[ "google_app_engine", "python", "unit_testing" ]
stackoverflow_0007182984_google_app_engine_python_unit_testing.txt
Q: Run Python unittest so that nothing is printed if successful, only AssertionError() if fails I have a test module in the standard unittest format class my_test(unittest.TestCase): def test_1(self): [tests] def test_2(self): [tests] etc.... My company has a proprietary test harness that...
Run Python unittest so that nothing is printed if successful, only AssertionError() if fails
I have a test module in the standard unittest format class my_test(unittest.TestCase): def test_1(self): [tests] def test_2(self): [tests] etc.... My company has a proprietary test harness that will execute my module as a command line script, and which will catch any errors raised by my mod...
[ "I came up with this. If you are able to change the command line you might remove the internal io redirection.\nimport sys, inspect, traceback\n\n# redirect stdout,\n# can be replaced by testharness.py > /dev/null at console\nclass devnull():\n def write(self, data):\n pass\n\nf = devnull()\norig_stdout ...
[ 3 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0007181134_python_unit_testing.txt
Q: python regex for string replacement I want to replace parts of a string that contains the following words "$%word$%" I want to replace it with the value of a dictionary with the corresponding key equal to word. In other words if I have a string: "blahblahblah $%word$% blablablabla $%car$%" and a dictionary {word:'...
python regex for string replacement
I want to replace parts of a string that contains the following words "$%word$%" I want to replace it with the value of a dictionary with the corresponding key equal to word. In other words if I have a string: "blahblahblah $%word$% blablablabla $%car$%" and a dictionary {word:'wassup', car:'toyota'} The string would b...
[ "Use re.sub with a function as the repl parameter:\nimport re\n\ntext = \"blahblahblah $%word$% blablablabla $%car$%\"\nwords = dict(word=\"wassup\", car=\"toyota\")\n\ndef replacement(match):\n try:\n return words[match.group(1)] # Lookup replacement string\n except KeyError:\n return match.g...
[ 8, 1, 0 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0007182469_python_regex_string.txt
Q: How to write a unittest with setUpClass & tearDownClass in Python 2.3 I am trying to write unittests in python 2.3. I've got everything working accept the class level setUp and tearDown function. I've tried to look online but am not able to find a way to define these in a python 2.3 unittest case. Hence, is it pos...
How to write a unittest with setUpClass & tearDownClass in Python 2.3
I am trying to write unittests in python 2.3. I've got everything working accept the class level setUp and tearDown function. I've tried to look online but am not able to find a way to define these in a python 2.3 unittest case. Hence, is it possible to have setUpClass() & tearDownClass() in a python 2.3 testcase? If y...
[ "According to the Python 2.3 standard library documentation, unittest.TestCase subclassing should work in the same way it works in more recent versions of the language.\nimport unittest\n\nclass MyTest(unittest.TestCase):\n\n def setUp(self):\n 'Do stuff to set up before each test'\n\n def tearDown(sel...
[ 0, 0 ]
[]
[]
[ "python", "python_2.3", "unit_testing" ]
stackoverflow_0007179108_python_python_2.3_unit_testing.txt
Q: Text file parsing question in Python I am new to python and I am trying to delete lines in a text file if I find the word "Lett." in the line. Here is a sample of the text file I am trying to parse: <A>Lamb</A> <W>Let. Moxon</W> <A>Lamb</A> <W>Danger Confound. Mor. w. Personal Deformity</W> <A>Lamb</A> <W>Gentle G...
Text file parsing question in Python
I am new to python and I am trying to delete lines in a text file if I find the word "Lett." in the line. Here is a sample of the text file I am trying to parse: <A>Lamb</A> <W>Let. Moxon</W> <A>Lamb</A> <W>Danger Confound. Mor. w. Personal Deformity</W> <A>Lamb</A> <W>Gentle Giantess</W> <A>Lamb</A> <W>Lett., to Words...
[ "f = open(\"myfile.txt\", \"r\")\nfor line in f:\n if not \"Lett.\" in line: print line,\n\nf.close()\n\nor if you want to write the result to a file:\nf = open(\"myfile.txt\", \"r\")\nlines = f.readlines()\nf.close()\nf = open(\"myfile.txt\", \"w\")\nfor line in lines:\n if not \"Lett.\" in line: f.write(line)\n...
[ 4, 1, 1, 0, 0 ]
[]
[]
[ "parsing", "python", "text_files" ]
stackoverflow_0007169669_parsing_python_text_files.txt
Q: Python: Check if any list element is a key in a dictionary Given the following code all_options = { "1": "/test/1", "2": "/test/2", "3": "/test/3" } selected_options = [ "1", "3" ] How do I get the entries from all_options where the key matches an entry in selected_options? I started down the path of using a List...
Python: Check if any list element is a key in a dictionary
Given the following code all_options = { "1": "/test/1", "2": "/test/2", "3": "/test/3" } selected_options = [ "1", "3" ] How do I get the entries from all_options where the key matches an entry in selected_options? I started down the path of using a List Comprehension, but I'm stuck on the last clause: final = () [ f...
[ "Just like this?\n>>> dict((option, all_options[option]) for option in selected_options if option in all_options)\n{'1': '/test/1', '3': '/test/3'}\n\nFrom Python 2.7 and 3 onwards, you can use the dict comprehension syntax:\n{option : all_options[option] for option in selected_options if option in all_options}\n\n...
[ 6, 1, 1, 1, 0 ]
[]
[]
[ "dictionary", "list", "python", "search" ]
stackoverflow_0007183869_dictionary_list_python_search.txt
Q: How can I keep track of specific values rolled in a dice-rolling script? I'm still considering myself a programming newbie (my reputation is largely because of gamedev.SE), and as such I've run into a problem I can't solve on my own. I have a function that takes a specified number of dice and rolls them, and retur...
How can I keep track of specific values rolled in a dice-rolling script?
I'm still considering myself a programming newbie (my reputation is largely because of gamedev.SE), and as such I've run into a problem I can't solve on my own. I have a function that takes a specified number of dice and rolls them, and returns the result. However, if it happens to roll the highest value available, eg ...
[ "have a second array maybe original = [] and in the roll == sides part of the if append a sides in the else append roll. you could then return [sum(results), original]. in your if roll == sides: you would then have to do something like results.append(roll_die(2,sides)[0])\nin answer to your list question you could ...
[ 2, 2 ]
[]
[]
[ "list", "python", "random" ]
stackoverflow_0007183200_list_python_random.txt
Q: Twisted plugin logging I am creating a twisted plugin. There is documentation here about how to control logging for twisted apps in .tac files. However there is no similar documentation for controlling logging for plugins. Since plugins do not create Application() objects, how can we control/customize the logging ...
Twisted plugin logging
I am creating a twisted plugin. There is documentation here about how to control logging for twisted apps in .tac files. However there is no similar documentation for controlling logging for plugins. Since plugins do not create Application() objects, how can we control/customize the logging that occurs? (a near-identic...
[ "Plugins should not configure logging. logging is normally configured directly by twistd from the command line option --logfile. Feel free to emit log messages in your plugin in the usual way as twisted.python.log.msg()\nRemember that twistd is a convenience, it's not intended to be the beginning and ending of al...
[ 1 ]
[]
[]
[ "logging", "python", "twistd", "twisted" ]
stackoverflow_0007184545_logging_python_twistd_twisted.txt
Q: Conditional Relative Imports in Python ... to do or not to do? Given the following package: testpackage __init__.py testmod.py testmod2.py Contents of __init__.py from . import testmod from . import testmod2 Contents of testmod.py # relative import without conditional logic, breaks when run directly ...
Conditional Relative Imports in Python ... to do or not to do?
Given the following package: testpackage __init__.py testmod.py testmod2.py Contents of __init__.py from . import testmod from . import testmod2 Contents of testmod.py # relative import without conditional logic, breaks when run directly from . import testmod2 ... if __name__ == '__main__': # do my mo...
[ "That will definitely become a maintenance headache in the future. Not just the conditional imports... more the reason why you're having to do conditional imports, namely that running testpackage/testmod2.py as the main script is causing the first entry of sys.path to be ./testpackage instead of ., which makes the ...
[ 1 ]
[]
[]
[ "conditional_statements", "import", "python", "python_packaging", "relative_path" ]
stackoverflow_0007184663_conditional_statements_import_python_python_packaging_relative_path.txt
Q: Collections and Stream classes equivalences between Smalltalk, Perl, Python and Ruby I have few experience with languages like Python, Perl and Ruby, but I have developed in Smalltalk from some time. There are some pretty basic Smalltalk classes which are very popular and cross-Smalltalk implementation: FileStream...
Collections and Stream classes equivalences between Smalltalk, Perl, Python and Ruby
I have few experience with languages like Python, Perl and Ruby, but I have developed in Smalltalk from some time. There are some pretty basic Smalltalk classes which are very popular and cross-Smalltalk implementation: FileStream ReadWriteStream Set Dictionary OrderedCollection SortedCollection Bag Interval Array Whi...
[ "Perl\nI'll answer for Perl, since I'm fluent in both Perl and Smalltalk.\nSmalltalk's Dictionary is fairly close to Perl's hash type. A Dictionary uses object equivalence for the keys. Perl uses simple strings for keys, so the flexibility is somewhat limited.\nSmalltalk's OrderedCollection is fairly close to Perl'...
[ 7, 4, 2 ]
[]
[]
[ "perl", "programming_languages", "python", "ruby", "smalltalk" ]
stackoverflow_0007184240_perl_programming_languages_python_ruby_smalltalk.txt
Q: web2py linking to CSS I'm learning web2py 1.98.2, so the question is very basic. In static/css folder I created basic.css file with the following content: .auth_navbar { top: 0px; float: right; padding: 3px 10px 3px 10px; } In layout.html I have: <head> ... {{response.files.append(URL('static','css/bas...
web2py linking to CSS
I'm learning web2py 1.98.2, so the question is very basic. In static/css folder I created basic.css file with the following content: .auth_navbar { top: 0px; float: right; padding: 3px 10px 3px 10px; } In layout.html I have: <head> ... {{response.files.append(URL('static','css/base.css'))}} ... </head> <b...
[ "{{response.files.append(URL('static','css/base.css'))}}\n\nThe above line simply adds base.css to the response.files list. The <link> tag is generated by the web2py_ajax.html template, which is included in the default layout.html. So, you need to make sure that web2py_ajax.html is also included in your layout.html...
[ 3, 1 ]
[]
[]
[ "python", "web2py" ]
stackoverflow_0007184489_python_web2py.txt
Q: jquery.ajax post request to get data from app engine server Apologies up front for the noob question... Hello, how do I get data from the Python end of an appengine server using jQuery.ajax? I know how to send data to the server using ajax and an appropriate handler, but I was wondering if someone could tell me wh...
jquery.ajax post request to get data from app engine server
Apologies up front for the noob question... Hello, how do I get data from the Python end of an appengine server using jQuery.ajax? I know how to send data to the server using ajax and an appropriate handler, but I was wondering if someone could tell me what the ajax request for getting values from the server looks like...
[ "The mechanism is exactly the same either way the data is flowing. Use the success parameter on the ajax call to operate on the data after the request successfully finishes. This is generally called a callback. Other callbacks exist. See http://api.jquery.com/jQuery.ajax/ for the complete information.\n$.ajax({\n ...
[ 9 ]
[]
[]
[ "ajax", "google_app_engine", "jquery", "python" ]
stackoverflow_0007184450_ajax_google_app_engine_jquery_python.txt
Q: how to manage pylons/paster config file in a cluster? I have 4 nodes running paster app, once I change the config, I need to change config files on the 4 nodes. It will be a headache if the nodes number growing. I believe it should be a common problem for people who running paster on more than one machines, is the...
how to manage pylons/paster config file in a cluster?
I have 4 nodes running paster app, once I change the config, I need to change config files on the 4 nodes. It will be a headache if the nodes number growing. I believe it should be a common problem for people who running paster on more than one machines, is there any solution for this? or did I use it the wrong way? t...
[ "Look at http://docs.fabfile.org/en/1.2.1/index.html\nThis common solution for managing and deploying apps on several instances by ssh/sftp\n" ]
[ 1 ]
[]
[]
[ "config", "deployment", "paster", "pylons", "python" ]
stackoverflow_0007159423_config_deployment_paster_pylons_python.txt
Q: Scrapy problem with international text I did scraping text from webpage using scrapy. In spider, I have code like: title = hxs.select("//h1/text()").extract() #1 final_text = title[0].encode('utf-8') #2 Here problem is line #1 gives [u'Puerto Ban\xfas'] line #2 gives Puerto Ban\xc3\xbas But original text was P...
Scrapy problem with international text
I did scraping text from webpage using scrapy. In spider, I have code like: title = hxs.select("//h1/text()").extract() #1 final_text = title[0].encode('utf-8') #2 Here problem is line #1 gives [u'Puerto Ban\xfas'] line #2 gives Puerto Ban\xc3\xbas But original text was Puerto Banús. How can I get this original sav...
[ ">>> print u'Puerto Ban\\xfas'\nPuerto Banús\n>>> print 'Puerto Ban\\xc3\\xbas'\nPuerto Banús\n\nI don't see a problem here.\n" ]
[ 1 ]
[]
[]
[ "python", "scrapy" ]
stackoverflow_0007185755_python_scrapy.txt
Q: how to get console output from a remote computer (ssh + python) I have googled "python ssh". There is a wonderful module pexpect, which can access a remote computer using ssh (with password). After the remote computer is connected, I can execute other commands. However I cannot get the result in python again. p ...
how to get console output from a remote computer (ssh + python)
I have googled "python ssh". There is a wonderful module pexpect, which can access a remote computer using ssh (with password). After the remote computer is connected, I can execute other commands. However I cannot get the result in python again. p = pexpect.spawn("ssh user@remote_computer") print "connecting..." p.w...
[ "Have you tried an even simpler approach?\n>>> from subprocess import Popen, PIPE\n>>> stdout, stderr = Popen(['ssh', 'user@remote_computer', 'ps -ef'],\n... stdout=PIPE).communicate()\n>>> print(stdout)\n\nGranted, this only works because I have ssh-agent running preloaded with a private key...
[ 11, 3, 1, 1 ]
[]
[]
[ "authentication", "linux", "pexpect", "python", "ssh" ]
stackoverflow_0001311697_authentication_linux_pexpect_python_ssh.txt
Q: Why doesn't this Haskell I translated to Python work properly? Haskell: average x y = (x + y) / 2 sqrt' :: (Ord a, Fractional a) => a -> Int -> a sqrt' 0 _ = 0.0 sqrt' 1 _ = 1.0 sqrt' s approximations = (infsqr' s) !! approximations infsqr' n = unfoldr acc 1 where acc guess | guess < 0 = Nothing ...
Why doesn't this Haskell I translated to Python work properly?
Haskell: average x y = (x + y) / 2 sqrt' :: (Ord a, Fractional a) => a -> Int -> a sqrt' 0 _ = 0.0 sqrt' 1 _ = 1.0 sqrt' s approximations = (infsqr' s) !! approximations infsqr' n = unfoldr acc 1 where acc guess | guess < 0 = Nothing | otherwise = Just (newguess', newguess') where ne...
[ "If you called unfold again, your generator will regenerate again, so you need to assign it to variable.\n>>> res = unfold(acc, 1)\n>>> print res.next()\n5.0\n>>> print res.next()\n3.4\n>>>\n\n" ]
[ 11 ]
[]
[]
[ "haskell", "math", "python" ]
stackoverflow_0007186081_haskell_math_python.txt
Q: Unbounded range() Is there an unbounded version of range (or xrange for Python 2), or is it necessary to define it manually? For example squares = (x*x for x in range(n)) can only give me a generator for the squares up to (n-1)**2, and I can't see any obvious way to call range(infinity) so that it just keeps on ...
Unbounded range()
Is there an unbounded version of range (or xrange for Python 2), or is it necessary to define it manually? For example squares = (x*x for x in range(n)) can only give me a generator for the squares up to (n-1)**2, and I can't see any obvious way to call range(infinity) so that it just keeps on truckin'.
[ "You're describing the basic use of itertools.count:\nimport itertools\nsquares = (x*x for x in itertools.count())\n\n" ]
[ 68 ]
[]
[]
[ "generator", "python", "range" ]
stackoverflow_0007186336_generator_python_range.txt
Q: Python validating web forms data I am able to extract the form field data, but I am NOT able to Put a check / validate the information to see if The field is not empty. I am writing it in Apache+mod_wsgi, browser FF, Python 2.6, Ubuntu 10.04 64bit The Following is the sample code where web form field data is read....
Python validating web forms data
I am able to extract the form field data, but I am NOT able to Put a check / validate the information to see if The field is not empty. I am writing it in Apache+mod_wsgi, browser FF, Python 2.6, Ubuntu 10.04 64bit The Following is the sample code where web form field data is read.This is where i need to put a check, w...
[ "This is the part of the code I am using.\n\n class Handler:<br>\n def do(self, environ, start_response):<br>\n html = \"\"\"\n <html><head><title>C Informatics</title>\n <meta charset=utf-8>\n <form method=\"post\" action=\"newreg.py\"><br>\n <table border=...
[ 1, 0 ]
[]
[]
[ "forms", "mod_wsgi", "python", "validating", "web" ]
stackoverflow_0007177770_forms_mod_wsgi_python_validating_web.txt
Q: how to compare values in an existing dictionary and update the dictionary back to a file? I am making an utility of sorts with dictionary. What I am trying to achieve is this: for each XML file that I parse, the existing dictionary is loaded from a file (output.dict) and compared/updated for the current key and st...
how to compare values in an existing dictionary and update the dictionary back to a file?
I am making an utility of sorts with dictionary. What I am trying to achieve is this: for each XML file that I parse, the existing dictionary is loaded from a file (output.dict) and compared/updated for the current key and stored back along with existing values. I tried with has_key() and attributerror, it does not wor...
[ "def createUpdateDictionary(servicename, xmlfile):\n dictionary = {}\n if path.isfile == 'output.dict':\n dictionary.update (eval(open('output.dict'),'r'))\n\nThere is a typo, as the 'r' argument belongs to open(), not eval(). Furthermore, you cannot evaluate a file object as returned by open(), you have...
[ 1 ]
[]
[]
[ "conditional_statements", "dictionary", "python" ]
stackoverflow_0007186134_conditional_statements_dictionary_python.txt
Q: how to send a "Ctrl+Break" to a subprocess via pid or handler import subprocess proc = subprocess.Popen(['c:\windows\system32\ping.exe','127.0.0.1', '-t'],stdout=subprocess.PIPE) while True: line = proc.stdout.readline() print "ping result:", line.rstrip() #sendkey("Ctrl+Break", proc) # i nee...
how to send a "Ctrl+Break" to a subprocess via pid or handler
import subprocess proc = subprocess.Popen(['c:\windows\system32\ping.exe','127.0.0.1', '-t'],stdout=subprocess.PIPE) while True: line = proc.stdout.readline() print "ping result:", line.rstrip() #sendkey("Ctrl+Break", proc) # i need this here, this is not for terminate the process but to print a s...
[ "The Ctrl+Break keys is a SIGBREAK signal.\nUnder linux, you can send this signal with kill command, on Windows, this is slightly different. You can use the SendSignal tool.\n", "Windows? Try this:\nimport signal\nproc.send_signal(signal.SIGBREAK)\n\nIf you meant a signal interrupt (kill -2)\nimport signal\nproc....
[ 2, 2 ]
[]
[]
[ "controls", "python", "sendkeys" ]
stackoverflow_0007186543_controls_python_sendkeys.txt
Q: Python - Function attributes or mutable default values Say you have a function that needs to maintain some sort of state and behave differently depending on that state. I am aware of two ways to implement this where the state is stored entirely by the function: Using a function attribute Using a mutable default ...
Python - Function attributes or mutable default values
Say you have a function that needs to maintain some sort of state and behave differently depending on that state. I am aware of two ways to implement this where the state is stored entirely by the function: Using a function attribute Using a mutable default value Using a slightly modified version of Felix Klings ans...
[ "I use closure instead, no side effects.\nHere is the example (I've just modified the original example of Felix Klings answer):\ndef replaceNthWith(n, replacement):\n c = [0]\n def replace(match):\n c[0] += 1\n return replacement if c[0] == n else match.group(0)\n return replace\n\nAnd the us...
[ 5, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007183349_python.txt
Q: How to install PySide v0.3.1 on Mac OS X? I'm trying to install PySide v0.3.1 in Mac OS X, for Qt development in python. As a pre-requisite, I have installed CMake and the Qt SDK. I have gone through the documentation and come up with the following installation script: export PYSIDE_BASE_DIR="<my_dir>" export API...
How to install PySide v0.3.1 on Mac OS X?
I'm trying to install PySide v0.3.1 in Mac OS X, for Qt development in python. As a pre-requisite, I have installed CMake and the Qt SDK. I have gone through the documentation and come up with the following installation script: export PYSIDE_BASE_DIR="<my_dir>" export APIEXTRACTOR_DIR="$PYSIDE_BASE_DIR/apiextractor-0....
[ "I don't have any MacOS experience but assuming it's similar to any *nix, let's go:\nAbout the script: Isn't it missing some \"make, make install\" commands? The version you posted just run cmake to configure the build. Also for testing, I set -DCMAKE_INSTALL_PREFIX= for all modules. That way everything is installe...
[ 2, 1, 1 ]
[]
[]
[ "macos", "pyside", "python", "qt" ]
stackoverflow_0002880434_macos_pyside_python_qt.txt
Q: psycopg2.ProgrammingError, running script to serialize data of django app from postgres I have a djano web app which stores the data about some entries to postgres db.To copy the data in db to json files ,I generally use the python manage.py shell and use the serialization api as mentioned i django tutorial. >>>py...
psycopg2.ProgrammingError, running script to serialize data of django app from postgres
I have a djano web app which stores the data about some entries to postgres db.To copy the data in db to json files ,I generally use the python manage.py shell and use the serialization api as mentioned i django tutorial. >>>python manage.py shell ... In[8]:from myapp.models import MyFirstModel In[9]:data = serializers...
[ "Have you looked in to using ./manage.py dumpdata ? You can specify the serialization format.\nFor your script to work have you set DJANGO_SETTINGS to the correct settings.py ?\nSecondly is there a reason that you are doing your imports inside the function, probably better to move them to the head of the file:\nfro...
[ 1 ]
[]
[]
[ "django", "python", "serialization" ]
stackoverflow_0007185670_django_python_serialization.txt
Q: Python and ShutdownBlockReasonCreate, ShutdownBlockReasonDestroy, and ShutdownBlockReasonQuery Is it possible to call the ShutdownBlockReasonCreate, ShutdownBlockReasonDestroy, and ShutdownBlockReasonQuery win32 APIs from within Python? I can't find them anywhere in the pywin32 library. Thanks! A: Use ctypes fro...
Python and ShutdownBlockReasonCreate, ShutdownBlockReasonDestroy, and ShutdownBlockReasonQuery
Is it possible to call the ShutdownBlockReasonCreate, ShutdownBlockReasonDestroy, and ShutdownBlockReasonQuery win32 APIs from within Python? I can't find them anywhere in the pywin32 library. Thanks!
[ "Use ctypes\nfrom ctypes import *\nretval = windll.user32.ShutdownBlockReasonCreate(\n handle,\n c_wchar_p(\"the reason\")\n)\nif retval != 0:\n ... Error checking\n\nAnd similarly with ShutdownBlockReasonDestroy.\n", "You could try asking or making an enhancement request on the pywin32 mailing list:\n\n...
[ 5, 0 ]
[]
[]
[ "python", "winapi" ]
stackoverflow_0007182243_python_winapi.txt
Q: Why does Python say file does not exist? I am writing a small script which will print if a file exists or not. But it always says that the file does not exist, even though the file actually exists. Code: file = exists(macinput+".py") print file if file == "True": print macinput+" command not found" elif file ==...
Why does Python say file does not exist?
I am writing a small script which will print if a file exists or not. But it always says that the file does not exist, even though the file actually exists. Code: file = exists(macinput+".py") print file if file == "True": print macinput+" command not found" elif file == "True": print os.getcwd() os.system("py...
[ "You should not compare with \"True\", but with True.\nAlso, you compare both in the if and the elif with \"True\".\ninstead of \nif file == \"True\":\n print macinput + \" command not found\"\n\ntry this:\nfile = exists(macinput+\".py\")\nprint \"file truth value: \", file\n\nif file:\n print macinput + \" c...
[ 2, 2, 2 ]
[]
[]
[ "operating_system", "python", "system", "windows_xp" ]
stackoverflow_0007186928_operating_system_python_system_windows_xp.txt
Q: Python - calculating trendlines with errors So I've got some data stored as two lists, and plotted them using plot(datasetx, datasety) Then I set a trendline trend = polyfit(datasetx, datasety) trendx = [] trendy = [] for a in range(datasetx[0], (datasetx[-1]+1)): trendx.append(a) trendy.append(trend[0]*...
Python - calculating trendlines with errors
So I've got some data stored as two lists, and plotted them using plot(datasetx, datasety) Then I set a trendline trend = polyfit(datasetx, datasety) trendx = [] trendy = [] for a in range(datasetx[0], (datasetx[-1]+1)): trendx.append(a) trendy.append(trend[0]*a**2 + trend[1]*a + trend[2]) plot(trendx, trend...
[ "I think you can use the function curve_fit of scipy.optimize (documentation). A basic example of the usage:\nimport numpy as np\nfrom scipy.optimize import curve_fit\n\ndef func(x, a, b, c):\n return a*x**2 + b*x + c\n\nx = np.linspace(0,4,50)\ny = func(x, 5, 3, 4)\nyn = y + 0.2*np.random.normal(size=len(x))\n\...
[ 14, 1 ]
[]
[]
[ "numpy", "python", "trendline" ]
stackoverflow_0007171356_numpy_python_trendline.txt
Q: Persisting test data across apps My Django site has two apps — Authors and Books. My Books app has a model which has a foreign key to a model in Authors. I have some tests for the Authors app which tests all my models and managers and this works fine. However, my app Books require some data from the Authors app in...
Persisting test data across apps
My Django site has two apps — Authors and Books. My Books app has a model which has a foreign key to a model in Authors. I have some tests for the Authors app which tests all my models and managers and this works fine. However, my app Books require some data from the Authors app in order to function. Can I specify the ...
[ "Create a fixture containing the test data you need. You can then load the same data for both your Authors and Books tests.\nFor details, see docs on Testcase.fixures and Introduction to Python/Django tests: Fixtures.\n" ]
[ 0 ]
[]
[]
[ "django", "integration_testing", "python", "testing", "unit_testing" ]
stackoverflow_0007187493_django_integration_testing_python_testing_unit_testing.txt
Q: Paramiko SFTP - Avoid having to specify full local filename? I have some Python code that uses Paramiko to grab build files from a remote server: def setup_sftp_session(self, host='server.com', port=22, username='puppy'): self.transport = paramiko.Transport((host, port)) privatekeyfile = os.path.expanduser...
Paramiko SFTP - Avoid having to specify full local filename?
I have some Python code that uses Paramiko to grab build files from a remote server: def setup_sftp_session(self, host='server.com', port=22, username='puppy'): self.transport = paramiko.Transport((host, port)) privatekeyfile = os.path.expanduser('~/.ssh/id_dsa') try: ssh_key = paramiko.DSSKey.from_...
[ "you have to insert \nos.path.join(os.getcwd(), remote_filename)\n\nCalling exit() in a function is not a good idea. Maybe you want to reuse the code and take some action in case of an exception. If you keep the exit() call you are lost.\nI suggest to modify this function such that a True is returned in case of suc...
[ 1 ]
[]
[]
[ "paramiko", "python", "sftp" ]
stackoverflow_0007187913_paramiko_python_sftp.txt
Q: BeautifulSoup parser appends semicolons to naked ampersands, mangling URLs? I am trying to parse some site in python that has links in it to other sites, but in plain text, not in "a" tag. Using BeautifulSoup I get the wrong answer. Consider this code: import BeautifulSoup html = """<html> <head> ...
BeautifulSoup parser appends semicolons to naked ampersands, mangling URLs?
I am trying to parse some site in python that has links in it to other sites, but in plain text, not in "a" tag. Using BeautifulSoup I get the wrong answer. Consider this code: import BeautifulSoup html = """<html> <head> <title>Test html</title> </head> <body> ...
[ "Apparently BS has an underdocumented issue parsing ampersands inside URL, I just searched their discussion forum for 'semicolon'. According to that discussion from 2009, naked & is strictly not valid and must be replaced by &amp; although browsers accept this so it seems waay pedantic.\nI agree this parsing behavi...
[ 7 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0007187744_beautifulsoup_python.txt
Q: Using scrapy to get links in Python? Sorry if this is a dumb question, but I have absolutely no idea how to use Scrapy. I don't want to create a Scrapy crawler (or w/e), I want to incorporate it into my existing code. I've looked at the docs, but I found them a bit confusing. What I need to do is, get links from a...
Using scrapy to get links in Python?
Sorry if this is a dumb question, but I have absolutely no idea how to use Scrapy. I don't want to create a Scrapy crawler (or w/e), I want to incorporate it into my existing code. I've looked at the docs, but I found them a bit confusing. What I need to do is, get links from a list on the site. I just need an example ...
[ "maybe you don't need scrappy if it's that simple.\ncat local.html\n\n<html><body>\n<ul> \n<li>example</li> \n<li>example2</li>\n</ul>\n<div><a href=\"test\">test</a><div><a href=\"hi\">hi</a></div></div>\n</body></html>\n\nthen...\nimport urllib2\nfrom lxml import html\n\npage =urllib2.urlopen(\"file:///root/loc...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007187406_python.txt
Q: Django-profile and django-registration get started I've installed Django-registration succesfully (form this tutorial). So now I have a Django project "loginSystem", with in this map urls.py, settings.py, manage.py and _init_.py, so there is no app created but it works. The registration-folder is installed in my p...
Django-profile and django-registration get started
I've installed Django-registration succesfully (form this tutorial). So now I have a Django project "loginSystem", with in this map urls.py, settings.py, manage.py and _init_.py, so there is no app created but it works. The registration-folder is installed in my python-packages folder. No I want to give to each users a...
[ "I don't see there they are talking about a /profiles/edit/ folder. The only thing you have to do is creating a /profiles/ folder in your TEMPLATE_DIR and put an edit_profile.html template there. Then you still need to hock up the url configuration to serve the edit view of the profiles app (they suggest a url some...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007188190_django_python.txt
Q: time complexity to get auto incremented row id in mysql I am a newbie at mysql and databases. I have a simple question. I have created a table that has an integer type id column that is auto incremented. After each insert I get the last row inserted id (in python using cursor.lastrowid, or connection.insert_id())....
time complexity to get auto incremented row id in mysql
I am a newbie at mysql and databases. I have a simple question. I have created a table that has an integer type id column that is auto incremented. After each insert I get the last row inserted id (in python using cursor.lastrowid, or connection.insert_id()). I wanted to know what is the time complexity in mysql to get...
[ "cursor.lastrowid will return the value from the single insert \nsee: http://www.python.org/dev/peps/pep-0249/\nconnection.insert_id() will have to make a seperate call to get the last_insert_id, and would slightly slower\n" ]
[ 2 ]
[]
[]
[ "mysql", "python", "python_db_api" ]
stackoverflow_0007187992_mysql_python_python_db_api.txt
Q: unable to Post data to a login form using urllib python v3.2.1 import urllib.parse import urllib.request import time def __init__(self, parent= None): QtGui.QWidget.__init__(self,parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) username = 'name' password = 'pass' wh...
unable to Post data to a login form using urllib python v3.2.1
import urllib.parse import urllib.request import time def __init__(self, parent= None): QtGui.QWidget.__init__(self,parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) username = 'name' password = 'pass' while True: try: page=urllib.request.urlop...
[ "import urllib.parse\nimport urllib.request\nimport time\n\nusername = 'name'\npassword = 'pass'\n\ntm = 60\n\nwhile True:\n url = \"http://10.100.56.55:8090/httpclient.html\"\n values = {'username': username, 'password': password, 'btnSubmit':'Login'}\n data = urllib.parse.urlencode(values)\n binary_da...
[ 3 ]
[]
[]
[ "python", "python_3.x", "urllib" ]
stackoverflow_0007188561_python_python_3.x_urllib.txt
Q: Split text into sentences I wish to split text into sentences. Can anyone help me? I also need to handle abbreviations. However my plan is to replace these at an earlier stage. Mr. -> Mister import re import unittest class Sentences: def __init__(self,text): self.sentences = tuple(re.split("[...
Split text into sentences
I wish to split text into sentences. Can anyone help me? I also need to handle abbreviations. However my plan is to replace these at an earlier stage. Mr. -> Mister import re import unittest class Sentences: def __init__(self,text): self.sentences = tuple(re.split("[.!?]\s", text)) class TestSent...
[ "Sentence Segmentation can be a very difficult task, especially when the text contains dotted abbreviations. it may require a use of lists of known abbreviations, or training classifier to recognize them.\nI suggest you to use NLTK - it a suite of open source Python modules, designed for natural language processing...
[ 5 ]
[]
[]
[ "python", "python_3.x", "regex", "text_segmentation" ]
stackoverflow_0007188665_python_python_3.x_regex_text_segmentation.txt
Q: ExtJS 3 and Highcharts, JsonStore problem while loading data i'm trying to chart some data using Highcharts in a EXTJS 3 window. With a fixed array of data everything works but i need to chart data taken from a python cgi which returns a json. This is how the python cgi creates my data (a slice of, i skipped the c...
ExtJS 3 and Highcharts, JsonStore problem while loading data
i'm trying to chart some data using Highcharts in a EXTJS 3 window. With a fixed array of data everything works but i need to chart data taken from a python cgi which returns a json. This is how the python cgi creates my data (a slice of, i skipped the connection to the db and so on): query = "select timestamp, val...
[ "dict.__str__ will in most cases not produce correct json. Use the json module.\nExample:\nimport json\n...\nreq.write(json.dumps(json_root)\n\nAnd remember to set the Content-Type header to application/json (some javascript frameworks use the header value to determine the correct action to take with the data).\n" ...
[ 0 ]
[]
[]
[ "extjs", "highcharts", "json", "python" ]
stackoverflow_0007188694_extjs_highcharts_json_python.txt
Q: Debug Python using PDB on Windows Anyone know how to debug Python using PDB in Windows XP? My system has some deadlock. I want to use PDB to track my system. My Config: VC 2005, Python2.7 A: I would recommend using the Winpdb GUI debugger, which works great on Windows (and other OSes too--the name is misleading)...
Debug Python using PDB on Windows
Anyone know how to debug Python using PDB in Windows XP? My system has some deadlock. I want to use PDB to track my system. My Config: VC 2005, Python2.7
[ "I would recommend using the Winpdb GUI debugger, which works great on Windows (and other OSes too--the name is misleading) and can attach to processes after launch. There's a great tutorial that gets you all the basics, which has been enough for me every time I've needed it, at least. Good luck!\n" ]
[ 0 ]
[ "I think the following page will help you. It's pydev with Eclipse.\nhttp://pydev.org/manual_adv_remote_debugger.html\n" ]
[ -2 ]
[ "debugging", "python" ]
stackoverflow_0003234927_debugging_python.txt
Q: Xpath python find node after specific text Here is the HTML code: <div id="someid"> <h2>Specific text 1</h2> <a class="hyperlinks" href="link"> link1 inside specific text 1</a> <a class="hyperlinks" href="link"> link2 inside specific text 1</a> <a class="hyperlinks" href="link"> link3 inside specif...
Xpath python find node after specific text
Here is the HTML code: <div id="someid"> <h2>Specific text 1</h2> <a class="hyperlinks" href="link"> link1 inside specific text 1</a> <a class="hyperlinks" href="link"> link2 inside specific text 1</a> <a class="hyperlinks" href="link"> link3 inside specific text 1</a> <h2>Specific text 2</h2> ...
[ "I think you will need one XPath expression for each h2 specific text.\nGiven an h2 specific text, you can get its following adjacent a siblings by:\n //div[@id='someid']/h2[.='Specific text 1']\n /following-sibling::a[\n count( . | following-sibling::h2[1]/preceding-sibling::*)\n = count(following...
[ 1, 0 ]
[]
[]
[ "html", "parsing", "python", "xpath" ]
stackoverflow_0007188964_html_parsing_python_xpath.txt
Q: Time Zone Synchronization I have a server which runs on Java and client which runs on python. When I connect the client and server I have to sync the time from server to client. I was successful in connecting and sending streams from server to client. I wanted to know what is the usual way to send time and timezon...
Time Zone Synchronization
I have a server which runs on Java and client which runs on python. When I connect the client and server I have to sync the time from server to client. I was successful in connecting and sending streams from server to client. I wanted to know what is the usual way to send time and timezone. How can i do it? For now i a...
[ "Do you know NTP, the Network Time Protocol?\n", "You should transmit and process the time in UTC and not mess with timezones at all. In Java, this is exactly what System.currentTimeMillis() returns.\nEdit: The correct format to transfer timezone information is to use a continent/city ID as in the tz database, e....
[ 3, 3 ]
[]
[]
[ "java", "python", "synchronization", "timezone" ]
stackoverflow_0007189439_java_python_synchronization_timezone.txt
Q: Python help can't figure out why unit test is failing Hi I am new to python and I am having an issue figuring out what's wrong with my code and why the unit test is failing? Below is the code, unit test and error message when running the test: legs = [] stomach = [] class Centipede(object): def __init__(self)...
Python help can't figure out why unit test is failing
Hi I am new to python and I am having an issue figuring out what's wrong with my code and why the unit test is failing? Below is the code, unit test and error message when running the test: legs = [] stomach = [] class Centipede(object): def __init__(self): def __str__(self): return ','.join(se...
[ "Move the legs and stomach into the Centipede.\n(I have always wanted to say that :))\nclass Centipede(object): \n def init(self):\n self.stomach=[]\n self.legs=[]\n\n", "self.legs is never set before you use it. Are you sure you don't mean just \"legs\" without the \"self\" part since you have a...
[ 5, 1, 1 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0007189585_python_unit_testing.txt
Q: writing output to a file with subprocess in python I have a code which spawns at the max 4 processes at a go. It looks for any news jobs submitted and if it exists it runs the python code for index,row in enumerate(rows): if index < 4: dirs=row[0] dirName=os.path.join(homeFolder,dirs) ...
writing output to a file with subprocess in python
I have a code which spawns at the max 4 processes at a go. It looks for any news jobs submitted and if it exists it runs the python code for index,row in enumerate(rows): if index < 4: dirs=row[0] dirName=os.path.join(homeFolder,dirs) logFile=os.path.join(dirName,(dirs+".log")) proc...
[ "For 2. you can take a look at http://docs.python.org/library/multiprocessing.html\n", "Concerning point 1, try to adjust the buffering used for the log file:\nopen(logFile,'w', 1) # line-buffered (writes to the file after each logged line)\nopen(logFile,'w', 0) # unbuffered (should immediately write to the file)...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007188965_python.txt
Q: subtract two columns in a tab'ed file (python) I have been tinkering with some coordinates which I want to check against eachother. I have a tab'ed filed, which consist of 6 columns. These are the last 4 columns I want to subtract, and get the result in two columns after the last coordinate column. Also tab'ed. I ...
subtract two columns in a tab'ed file (python)
I have been tinkering with some coordinates which I want to check against eachother. I have a tab'ed filed, which consist of 6 columns. These are the last 4 columns I want to subtract, and get the result in two columns after the last coordinate column. Also tab'ed. I want to do this for quite large files, is this possi...
[ "Something like this?\n#!/usr/bin/env python\n\nwith open('input') as fd:\n for line in fd:\n columns=line.split()\n columns=map(float,columns)\n print \"%s | \\t %s \\t %s\" % (line.strip(), columns[0] - columns[2],\n columns[1] - columns[3])\n\nOutputs\n3...
[ 3 ]
[]
[]
[ "python", "tabs" ]
stackoverflow_0007189682_python_tabs.txt
Q: Retrieving last 100 rows from a mysql database I have a table created with an auto-increment id as a column which is also the primary key. I want to know the most efficient way to retrieve the last 100 tuples from the table (preferably O(1) time as my table is going to be huge). Also, since id is my primary key he...
Retrieving last 100 rows from a mysql database
I have a table created with an auto-increment id as a column which is also the primary key. I want to know the most efficient way to retrieve the last 100 tuples from the table (preferably O(1) time as my table is going to be huge). Also, since id is my primary key here, will it automatically indexed? And does id being...
[ "SELECT ... FROM t ORDER BY id DESC LIMIT 100;\n\nUPDATE\nYes, your primary key will be indexed which speeds up queries using it.\n" ]
[ 7 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0007189940_mysql_python.txt
Q: Two related windows not displaying properly Running this code on my linux mint 11 with Python 2.6 would normally lead to creating 2 windows, each of them having a frame with a Button: from Tkinter import * root = Tk() boot = Toplevel() frame = Frame(root).pack() button = Button(frame,text="button1").pack() fr = ...
Two related windows not displaying properly
Running this code on my linux mint 11 with Python 2.6 would normally lead to creating 2 windows, each of them having a frame with a Button: from Tkinter import * root = Tk() boot = Toplevel() frame = Frame(root).pack() button = Button(frame,text="button1").pack() fr = Frame(boot).pack() but = Button(fr,text="button2"...
[ "Instead of \nfr = Frame(boot).pack()\nbut=Button(boot, text=...\n\ntry\nfr = Frame(boot)\nfr.pack()\nbut=Button(boot, text= ...)\n\n" ]
[ 3 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0007189537_python_tkinter.txt
Q: Django url reverse and regular expression I got this in my urlpatterns url(r'^(page/(?P<page>\d+)/)?$', 'index', name = 'index_path') and here is my views.py file def index(request, page=1): posts = Post.objects.filter(published = True) paginated_posts = Paginator(posts, 20) try: target_page ...
Django url reverse and regular expression
I got this in my urlpatterns url(r'^(page/(?P<page>\d+)/)?$', 'index', name = 'index_path') and here is my views.py file def index(request, page=1): posts = Post.objects.filter(published = True) paginated_posts = Paginator(posts, 20) try: target_page = paginated_posts.page(page) except EmptyPa...
[ "I think in order to make this work properly you'll have to have two urls:\nurl(r'^page/(?P<page>\\d+)$', 'index', name = 'index_path_page'),\nurl(r'^$', 'index', name = 'index_path'),\n\nThen when you reverse, you have two options:\nreverse('index_path_page', args=[1])\n# or\nreverse('index', args=[1]) # pulls by ...
[ 3, 1 ]
[]
[]
[ "django", "python", "reverse" ]
stackoverflow_0007190069_django_python_reverse.txt
Q: Django Admin :: HTML Input In Django's admin panel: how do I add a form field that users can add unescaped HTML into? A: Use a standard TextField, the data gets saved unescaped. However, by default any data that is outputted in a template is automatically escaped. You can circumvent this by either disable autoes...
Django Admin :: HTML Input
In Django's admin panel: how do I add a form field that users can add unescaped HTML into?
[ "Use a standard TextField, the data gets saved unescaped. However, by default any data that is outputted in a template is automatically escaped. You can circumvent this by either disable autoescaping (bad idea!) by using the safe filter.\n" ]
[ 1 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0007190356_django_django_admin_python.txt
Q: Extracting href with Beautiful Soup I use this code to get acces to my link : links = soup.find("span", { "class" : "hsmall" }) links.findNextSiblings('a') for link in links: print link['href'] print link.string Link have no ID or class or whatever, it's just a classic link with a href attribute. The response...
Extracting href with Beautiful Soup
I use this code to get acces to my link : links = soup.find("span", { "class" : "hsmall" }) links.findNextSiblings('a') for link in links: print link['href'] print link.string Link have no ID or class or whatever, it's just a classic link with a href attribute. The response of my script is : print link['href'] Typ...
[ "Links is still referring to your soup.find. So you could do something like:\nlinks = soup.find(\"span\", { \"class\" : \"hsmall\" }).findNextSiblings('a')\nfor link in links:\n print link['href']\n print link.string\n\n", "Okay, it works now with following code : \nlinkSpan = soup.find(\"span\", { \"class\...
[ 9, 4 ]
[]
[]
[ "beautifulsoup", "href", "python" ]
stackoverflow_0007183922_beautifulsoup_href_python.txt
Q: Basic Python StringIO -- Why is GetValue() Returning Nothing? I'm having basic python issues.. In the following example no errors are returned but displaying the contents of all variables using pprint shows that contents is = '' -- why would this possibly be the case? import sys, os, re, StringIO, pprint, time fro...
Basic Python StringIO -- Why is GetValue() Returning Nothing?
I'm having basic python issues.. In the following example no errors are returned but displaying the contents of all variables using pprint shows that contents is = '' -- why would this possibly be the case? import sys, os, re, StringIO, pprint, time from BeautifulSoup import BeautifulSoup, BeautifulStoneSoup import pyc...
[ "Look at the lines that involve StringIO.\nstrio = StringIO.StringIO()\ncontents = strio.getvalue()\nstrio.close()\n\nNone of these statements draw content from curlobj. So strio is empty.\n\nEdit (thanks to @Alexander Cameron and @agf): \nPerhaps you meant\ncurlobj.setopt(pycurl.WRITEFUNCTION, strio.write) \n\n...
[ 5, 2 ]
[]
[]
[ "python", "stringio" ]
stackoverflow_0007190593_python_stringio.txt
Q: Selenium: Problem with deleting cookies We are using selenium 2.4 with a python client, and running the scripts on Firefox. When doing delete_all_visible_cookies we are getting the exception: ERROR: Command execution failure. Please search the user group at https://groups.google.com/forum/#!forum/selenium-users f...
Selenium: Problem with deleting cookies
We are using selenium 2.4 with a python client, and running the scripts on Firefox. When doing delete_all_visible_cookies we are getting the exception: ERROR: Command execution failure. Please search the user group at https://groups.google.com/forum/#!forum/selenium-users for error details from the log window. The err...
[ "ok, we found the 2 problems we have here:\n\nThe cookie value is problematic, therefore we got the 'malformed URI sequence' error. To solve this problem I set the cookie value to 0 using create_cookie(), before deleting the cookies. \nThere are 2 cookie with the same name and value, but with different domains: one...
[ 3 ]
[]
[]
[ "cookies", "python", "selenium", "selenium_rc", "selenium_webdriver" ]
stackoverflow_0007144941_cookies_python_selenium_selenium_rc_selenium_webdriver.txt
Q: Attribute error in smtp I want to make use of SMTP. I have written a simple code that will send mail from one mail address to another. import smtplib msg = "smtp_mail" server = smtplib.SMTP('MailServerAddress') server = smtplib.SMTP(server) server.set_debuglevel(1) server.sendmail(fromaddr, toaddrs, msg) serve...
Attribute error in smtp
I want to make use of SMTP. I have written a simple code that will send mail from one mail address to another. import smtplib msg = "smtp_mail" server = smtplib.SMTP('MailServerAddress') server = smtplib.SMTP(server) server.set_debuglevel(1) server.sendmail(fromaddr, toaddrs, msg) server.quit() here I am getting ...
[ "Your program crashes on line : server = smtplib.SMTP(server)\nJust remove this line, it's twice !\n" ]
[ 3 ]
[]
[]
[ "python", "smtp", "smtpclient", "smtplib" ]
stackoverflow_0007188658_python_smtp_smtpclient_smtplib.txt
Q: pip install from a github repo - how to build C-extensions with Cython during egg install I can successfully install the DMSL package using the following commands git clone git://github.com/dasacc22/dmsl.git cd dmsl sudo python setup.py install but when I try installing with pip pip install -e git+git://github.co...
pip install from a github repo - how to build C-extensions with Cython during egg install
I can successfully install the DMSL package using the following commands git clone git://github.com/dasacc22/dmsl.git cd dmsl sudo python setup.py install but when I try installing with pip pip install -e git+git://github.com/dasacc22/dmsl.git#egg=dmsl I get an error Obtaining dmsl from git+git://github.com/dasacc22/...
[ "After installing Pyrex the installation worked for me. You might want to add Cython and Pyrex to the installed_requires parameter of the setup() call.\n" ]
[ 3 ]
[]
[]
[ "cython", "egg", "git", "pip", "python" ]
stackoverflow_0007189336_cython_egg_git_pip_python.txt
Q: Python, checking if a proxy is alive? The code: for item in pxfile.readlines(): if is_OK(item): sys.stdout.write(item + "is not OK.") item = make(item) item = "#" + item resfile.write(item) else: sys.stdout.write(item) sys.stdout.write("is OK.") ...
Python, checking if a proxy is alive?
The code: for item in pxfile.readlines(): if is_OK(item): sys.stdout.write(item + "is not OK.") item = make(item) item = "#" + item resfile.write(item) else: sys.stdout.write(item) sys.stdout.write("is OK.") line = make(item) resfile.wri...
[ "You should use threads to make the code run quicker :\nimport urllib2, threading\n\ndef is_OK(ip):\n print 'Trying %s ...' % ip\n try:\n proxy_handler = urllib2.ProxyHandler({'http': ip})\n opener = urllib2.build_opener(proxy_handler)\n opener.addheaders = [('User-agent', 'Mozilla/5.0')]...
[ 2, 1, 1 ]
[]
[]
[ "proxy", "python", "urllib2" ]
stackoverflow_0007188168_proxy_python_urllib2.txt
Q: How to display rich text in a gtk.MenuItem label? I would like to display rich text in a gtk.MenuItem(), e.g. displaying bold text. So far I have only found that one could pass in a string. Is it possible to display rich text in such a label? If so, how? If not, how appalling that would be! :) Thanks. A: You can...
How to display rich text in a gtk.MenuItem label?
I would like to display rich text in a gtk.MenuItem(), e.g. displaying bold text. So far I have only found that one could pass in a string. Is it possible to display rich text in such a label? If so, how? If not, how appalling that would be! :) Thanks.
[ "You cannot set the menu bold, but you may set the label on it as bold by calling the child :\n label = menuItem.get_children()[0]\n label.set_markup(\"<b>Hi Pete!</b>\")\n\n" ]
[ 4 ]
[]
[]
[ "menuitem", "pygtk", "python", "rtf", "string" ]
stackoverflow_0007189338_menuitem_pygtk_python_rtf_string.txt
Q: Directory sizes and extensions I'd like to create python command line code that is able to print directory tree with sizes of all subdirectories (from certain directory) and most frequent extensions... I will show the example output. root_dir (5 GB, jpg (65 %): avi ( 30 %) : pdf (5 %)) -- aa (3 GB, jpg (100 %) )...
Directory sizes and extensions
I'd like to create python command line code that is able to print directory tree with sizes of all subdirectories (from certain directory) and most frequent extensions... I will show the example output. root_dir (5 GB, jpg (65 %): avi ( 30 %) : pdf (5 %)) -- aa (3 GB, jpg (100 %) ) -- bb (2 GB, avi (20 %) : pdf (2 %...
[ "Calculating directory sizes really isn't python's strong suit, as explained in this post: very quickly getting total size of folder. If you have access to du and find, by all means use that. You can easily display the size of each directory with the following line: \nfind . -type d -exec du -hs \"{}\" \\;\n\nIf yo...
[ 4, 2, 0 ]
[ "That's the module you need. And also this.\n" ]
[ -2 ]
[ "directory", "file_extension", "python" ]
stackoverflow_0007138379_directory_file_extension_python.txt
Q: How do I upload a document from a web form to google docs? I'm writing a web aplication for users to upload documents on their computer to google docs, and download them. It seems that google docs python API requires that the files for upload be stored locally on the server running the aplication. How do I allow u...
How do I upload a document from a web form to google docs?
I'm writing a web aplication for users to upload documents on their computer to google docs, and download them. It seems that google docs python API requires that the files for upload be stored locally on the server running the aplication. How do I allow users to upload documents using a web form?
[ "Google Documents List Data API is a REST API, so you can use it in any language. You can use urllib2 or culrlib to make your HTTP requests, or use http://code.google.com/intl/pl-PL/apis/documents/docs/3.0/developers_guide_python.html#GettingStarted\n" ]
[ 0 ]
[]
[]
[ "google_docs_api", "python" ]
stackoverflow_0007185484_google_docs_api_python.txt
Q: How to set up a table with a recursive foreign key and a relationship declaratively in SQLAlchemy? Suppose I have a table "nodes" where I store a tree. Each node has a primary key id and a column parent_id. Of course, I want to access a parent attribute of each node instance, that is, a relation. One might try: im...
How to set up a table with a recursive foreign key and a relationship declaratively in SQLAlchemy?
Suppose I have a table "nodes" where I store a tree. Each node has a primary key id and a column parent_id. Of course, I want to access a parent attribute of each node instance, that is, a relation. One might try: import sqlalchemy, sqlalchemy.orm, sqlalchemy.ext.declarative engine = sqlalchemy.create_engine('sqlite://...
[ "For some reason, you already have a class registered for that table, or you have defined the table (possibly indirectly) twice. This happens to me most frequently when I'm experimenting on the python command line; sqlalchemy remembers the table definitions and class mappings longer than is immediately obvious (fr...
[ 5 ]
[]
[]
[ "foreign_key_relationship", "foreign_keys", "python", "sqlalchemy" ]
stackoverflow_0007191758_foreign_key_relationship_foreign_keys_python_sqlalchemy.txt