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: How can I provide safety template for user to modify with python? I am building a multi-user web application. Each user can have their own site under my application. I am considering how to allow user to modify template without security problem? I have evaluated some python template engine. For example, genshi, it...
How can I provide safety template for user to modify with python?
I am building a multi-user web application. Each user can have their own site under my application. I am considering how to allow user to modify template without security problem? I have evaluated some python template engine. For example, genshi, it is a pretty wonderful template engine, but however it might be dangero...
[ "Jinja2 is a Django-ish templating system that has a sandboxing feature. I've never attempted to use the sandboxing, but I quite like Jinja2 as an alternative to Django's templates. It still promotes separation of template from business logic, but has more Pythonic calling conventions, namespacing, etc. \nJinja2 S...
[ 5, 1, 0 ]
[ "The short answer is probably \"you can't\".\nThe best you can probably do is to trap the individual users in virtual machines or sandboxes.\n" ]
[ -1 ]
[ "python", "templates", "web" ]
stackoverflow_0000550337_python_templates_web.txt
Q: python, dictionary and int error I have a very frustrating python problem. In this code fixedKeyStringInAVar = "SomeKey" def myFunc(a, b): global sleepTime global fixedKeyStringInAVar varMe=int("15") sleepTime[fixedKeyStringInAVar] = varMe*60*1000 #more code Now this works. BUT sometimes when...
python, dictionary and int error
I have a very frustrating python problem. In this code fixedKeyStringInAVar = "SomeKey" def myFunc(a, b): global sleepTime global fixedKeyStringInAVar varMe=int("15") sleepTime[fixedKeyStringInAVar] = varMe*60*1000 #more code Now this works. BUT sometimes when I run this function I get TypeError: ...
[ "\nDon't use global keyword in a function unless you'd like to change binding of a global name.\nSearch for 'sleepTime =' in your code. You are binding an int object to the sleepTime name at some point in your program.\n\n", "Your sleepTime is a global variable. It could be changed to be an int at some point in y...
[ 5, 1 ]
[]
[]
[ "dictionary", "global", "python" ]
stackoverflow_0000550673_dictionary_global_python.txt
Q: Java Servlet Filter Equivalent in Ruby [on Rails] and PHP? Not sure if the terminology is correct, but are there rough equivalents to Java Servlet Filters in Ruby and PHP ? Are they actual concrete classes ? I assume there is also a number of common web app libraries/frameworks in Python. Is there an equivalent th...
Java Servlet Filter Equivalent in Ruby [on Rails] and PHP?
Not sure if the terminology is correct, but are there rough equivalents to Java Servlet Filters in Ruby and PHP ? Are they actual concrete classes ? I assume there is also a number of common web app libraries/frameworks in Python. Is there an equivalent there ? Thanks. === ADDENDUM === On the good advice of Kevin Davis...
[ "\nI assume there is also a number of\n common web app libraries/frameworks in\n Python. Is there an equivalent there ?\n\nDjango provides a framework of middleware hooks that can be used to alter input/output in request/response processing. See the Middleware documentation page for more details.\n", "In a typi...
[ 2, 0, 0, 0 ]
[]
[]
[ "java", "php", "python", "ruby_on_rails", "servlets" ]
stackoverflow_0000417158_java_php_python_ruby_on_rails_servlets.txt
Q: "Private" (implementation) class in Python I am coding a small Python module composed of two parts: some functions defining a public interface, an implementation class used by the above functions, but which is not meaningful outside the module. At first, I decided to "hide" this implementation class by defining ...
"Private" (implementation) class in Python
I am coding a small Python module composed of two parts: some functions defining a public interface, an implementation class used by the above functions, but which is not meaningful outside the module. At first, I decided to "hide" this implementation class by defining it inside the function using it, but this hamper...
[ "Use a single underscore prefix:\nclass _Internal:\n ...\n\nThis is the official Python convention for 'internal' symbols; \"from module import *\" does not import underscore-prefixed objects.\nReference to the single underscore convention.\n", "In short:\n\nYou cannot enforce privacy. There are no private cla...
[ 235, 97, 46, 19, 13, 7, 6 ]
[]
[]
[ "access_modifiers", "python" ]
stackoverflow_0000551038_access_modifiers_python.txt
Q: python runtime error, can dump a file? I am using libcurl to DL a webpage, then i am scanning it for data and doing something with one of the links. However, once in a while the page is different then i except thus i extract bad data and pycurl throws an exception. I tried finding the exception name for pycurl but...
python runtime error, can dump a file?
I am using libcurl to DL a webpage, then i am scanning it for data and doing something with one of the links. However, once in a while the page is different then i except thus i extract bad data and pycurl throws an exception. I tried finding the exception name for pycurl but had no luck. Is there a way i can get the t...
[ "sys.excepthook may help you here, where you can set a global exception handler. I am not sure how pycurl exceptions are handled, it being a binding library, but it will probably work to reassign it to a generic function. Something like:\n>>> import sys\n>>> \n>>> def my_global_exception_handler(type, value, traceb...
[ 3, 3, 2 ]
[]
[]
[ "error_handling", "pycurl", "python" ]
stackoverflow_0000550804_error_handling_pycurl_python.txt
Q: Deploying application with Python or another embedded scripting language I'm thinking about using Python as an embedded scripting language in a hobby project written in C++. I would not like to depend on separately installed Python distribution. Python documentation seems to be quite clear about general usage, but...
Deploying application with Python or another embedded scripting language
I'm thinking about using Python as an embedded scripting language in a hobby project written in C++. I would not like to depend on separately installed Python distribution. Python documentation seems to be quite clear about general usage, but I couldn't find a clear answer to this. Is it feasible to deploy a Python int...
[ "Link your application to the python library (pythonXX.lib on Windows) and add the following to your main() function.\nPy_NoSiteFlag = 1; // Disable importing site.py\nPy_Initialize(); // Create a python interpreter\n\nPut the python standard library bits you need into a zip file (called pythonXX.zip) and place...
[ 18, 8, 5, 0 ]
[]
[]
[ "c++", "deployment", "embedded_language", "python", "scripting_language" ]
stackoverflow_0000551227_c++_deployment_embedded_language_python_scripting_language.txt
Q: What's the best way to make a time from "Today" or "Yesterday" and a time in Python? Python has pretty good date parsing but is the only way to recognize a datetime such as "Today 3:20 PM" or "Yesterday 11:06 AM" by creating a new date today and doing subtractions? A: A library that I like a lot, and I'm seeing ...
What's the best way to make a time from "Today" or "Yesterday" and a time in Python?
Python has pretty good date parsing but is the only way to recognize a datetime such as "Today 3:20 PM" or "Yesterday 11:06 AM" by creating a new date today and doing subtractions?
[ "A library that I like a lot, and I'm seeing more and more people use, is python-dateutil but unfortunately neither it nor the other traditional big datetime parser, mxDateTime from Egenix can parse the word \"tomorrow\" in spite of both libraries having very strong \"fuzzy\" parsers.\nThe only library I've seen th...
[ 19 ]
[ "I am not yet completely up to speed on Python yet, but your question interested me, so I dug around a bit.\nDate subtraction using timedelta is by far the most common solution I found.\nSince your question asks if that's the only way to do it, I checked out the strftime format codes to see if you could define your...
[ -3 ]
[ "datetime", "parsing", "python" ]
stackoverflow_0000552073_datetime_parsing_python.txt
Q: Missing first line when downloading .rar file using urllib2.urlopen() Okey this is really strange. I have this script which basically downloads bunch of achieve files and extracts them. Usually those files are .zip files. Today I sat down and decided to make it work with rar files and I got stuck. At first I thoug...
Missing first line when downloading .rar file using urllib2.urlopen()
Okey this is really strange. I have this script which basically downloads bunch of achieve files and extracts them. Usually those files are .zip files. Today I sat down and decided to make it work with rar files and I got stuck. At first I thought that the problem is in my unrar code, but it wasn't there. So I did: f =...
[ "When trying to determine the content of binary data string, use repr() or hex(). For example,\n>>> print repr(data)\n'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t'\n>>> print [hex(ord(c)) for c in data]\n['0x0', '0x1', '0x2', '0x3', '0x4', '0x5', '0x6', '0x7', '0x8', '0x9']\n>>>\n\n", "Does the data maybe co...
[ 3, 2 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0000552328_python_urllib2.txt
Q: How do python classes work? I have a code file from the boto framework pasted below, all of the print statements are mine, and the one commented out line is also mine, all else belongs to the attributed author. My question is what is the order in which instantiations and allocations occur in python when instantiat...
How do python classes work?
I have a code file from the boto framework pasted below, all of the print statements are mine, and the one commented out line is also mine, all else belongs to the attributed author. My question is what is the order in which instantiations and allocations occur in python when instantiating a class? The author's code b...
[ "A few python notes\nWhen python executes the class block, it creates all of the \"attributes\" of that class as it encounters them. They are usually class variables as well as functions (methods), and the like.\nSo the value for \"Manager.DefaultDomainName\" is set when it is encountered in the class definition. ...
[ 9, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000552329_python.txt
Q: python ide vs cmd line detection? When programming in the two IDEs i used, bad things happen when i use raw_input. However on the command line it works EXACTLY how i expect it to. Typically this app is ran in cmd line but i like to edit and debug it in an IDE. Is there a way to detect if i executed the app in an I...
python ide vs cmd line detection?
When programming in the two IDEs i used, bad things happen when i use raw_input. However on the command line it works EXACTLY how i expect it to. Typically this app is ran in cmd line but i like to edit and debug it in an IDE. Is there a way to detect if i executed the app in an IDE or not?
[ "if sys.stdin.isatty():\n # command line (not a pipe, no stdin redirection)\nelse:\n # something else, could be IDE\n\n", "I would strongly advise (and you have been previously advised on this) to use a good IDE, and a good debugger instead of hacking around your code to fix something that shouldn't be broken...
[ 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000552627_python.txt
Q: Windows Server 2008 or Vista? What is an easy (to implement) way to check whether I am on Windows Vista or Windows Server 2008 from a Python script? platform.uname() gives the same result for both versions. A: As mentioned in the other question the foolproof (I think) way is to use win32api.GetVersionEx(1). The ...
Windows Server 2008 or Vista?
What is an easy (to implement) way to check whether I am on Windows Vista or Windows Server 2008 from a Python script? platform.uname() gives the same result for both versions.
[ "As mentioned in the other question the foolproof (I think) way is to use win32api.GetVersionEx(1). The combination of the version number and the product type will give you the current windows platform you're running on. Eg. the combination of version number \"6.*\" and product type VER_NT_SERVER is Windows Server ...
[ 2 ]
[]
[]
[ "python", "windows_server_2008", "windows_vista", "windowsversion" ]
stackoverflow_0000553372_python_windows_server_2008_windows_vista_windowsversion.txt
Q: python exit a blocking thread? In my code I loop though raw_input() to see if the user has requested to quit. My app can quit before the user quits, but my problem is the app is still alive until I enter a key to return from the blocking function raw_input(). Can I do to force raw_input() to return by maybe sendin...
python exit a blocking thread?
In my code I loop though raw_input() to see if the user has requested to quit. My app can quit before the user quits, but my problem is the app is still alive until I enter a key to return from the blocking function raw_input(). Can I do to force raw_input() to return by maybe sending it a fake input? Could I terminate...
[ "Why don't you just mark the thread as daemonic?\nFrom the docs:\n\nA thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon a...
[ 6, 2, 2, 1 ]
[]
[]
[ "multithreading", "python", "raw_input" ]
stackoverflow_0000552996_multithreading_python_raw_input.txt
Q: Python super class reflection If I have Python code class A(): pass class B(): pass class C(A, B): pass and I have class C, is there a way to iterate through it's super classed (A and B)? Something like pseudocode: >>> magicGetSuperClasses(C) (<type 'A'>, <type 'B'>) One solution seems to be inspect ...
Python super class reflection
If I have Python code class A(): pass class B(): pass class C(A, B): pass and I have class C, is there a way to iterate through it's super classed (A and B)? Something like pseudocode: >>> magicGetSuperClasses(C) (<type 'A'>, <type 'B'>) One solution seems to be inspect module and getclasstree function. d...
[ "C.__bases__ is an array of the super classes, so you could implement your hypothetical function like so:\ndef magicGetSuperClasses(cls):\n return cls.__bases__\n\nBut I imagine it would be easier to just reference cls.__bases__ directly in most cases.\n", "@John: Your snippet doesn't work -- you are returning t...
[ 37, 11, 4, 2 ]
[]
[]
[ "python", "reflection" ]
stackoverflow_0000025807_python_reflection.txt
Q: Can anyone provide a more pythonic way of generating the morris sequence? I'm trying to generate the morris sequence in python. My current solution is below, but I feel like I just wrote c in python. Can anyone provide a more pythonic solution? def morris(x): a = ['1', '11'] yield a[0] yield a[1] w...
Can anyone provide a more pythonic way of generating the morris sequence?
I'm trying to generate the morris sequence in python. My current solution is below, but I feel like I just wrote c in python. Can anyone provide a more pythonic solution? def morris(x): a = ['1', '11'] yield a[0] yield a[1] while len(a) <= x: s = '' count = 1 al = a[-1] f...
[ "itertools.groupby seems to fit perfectly! Just define a next_morris function as follows:\ndef next_morris(number):\n return ''.join('%s%s' % (len(list(group)), digit)\n for digit, group in itertools.groupby(str(number)))\n\nThat's all!!! Look:\nprint next_morris(1)\n11\nprint next_morris(11122...
[ 24, 6 ]
[]
[]
[ "python", "python_itertools", "sequences" ]
stackoverflow_0000553871_python_python_itertools_sequences.txt
Q: What's a way to create flash animations with Python? I'm having a set of Python scripts that process the photos. What I would like is to be able to create some kind of flash-presentation out of those images. Is there any package or 'framework' that would help to do this? A: I don't know of any Python-specific so...
What's a way to create flash animations with Python?
I'm having a set of Python scripts that process the photos. What I would like is to be able to create some kind of flash-presentation out of those images. Is there any package or 'framework' that would help to do this?
[ "I don't know of any Python-specific solutions but there are multiple tools to handle this:\nYou can create a flash file with dummy pictures which you then replace using mtasc, swfmill, SWF Tools or similar. This way means lots of trouble but allows you to create a dynamic flash file.\nIf you don't need dynamic con...
[ 3, 2, 1, 1 ]
[]
[]
[ "flash", "python" ]
stackoverflow_0000531377_flash_python.txt
Q: Creating an inheritable Python type with PyCxx A friend and I have been toying around with various Python C++ wrappers lately, trying to find one that meets the needs of both some professional and hobby projects. We've both honed in on PyCxx as a good balance between being lightweight and easy to interface with wh...
Creating an inheritable Python type with PyCxx
A friend and I have been toying around with various Python C++ wrappers lately, trying to find one that meets the needs of both some professional and hobby projects. We've both honed in on PyCxx as a good balance between being lightweight and easy to interface with while hiding away some of the ugliest bits of the Pyth...
[ "You must declare kitty as class new_style_class: public Py::PythonClass< new_style_class >. See simple.cxx and the Python test case at http://cxx.svn.sourceforge.net/viewvc/cxx/trunk/CXX/Demo/Python3/.\nPython 2.2 introduced new-style classes which among other things allow the user to subclass built-in types (like...
[ 3, 1 ]
[]
[]
[ "pycxx", "python", "python_c_api" ]
stackoverflow_0000548442_pycxx_python_python_c_api.txt
Q: Stackless python network performance degrading over time? So i'm toying around with stackless python, writing a very simple webserver to teach myself programming with microthreads/tasklets. But now to my problem, when I run something like ab -n 100000 -c 50 http://192.168.0.192/ (100k requests, 50 concurrency) in ...
Stackless python network performance degrading over time?
So i'm toying around with stackless python, writing a very simple webserver to teach myself programming with microthreads/tasklets. But now to my problem, when I run something like ab -n 100000 -c 50 http://192.168.0.192/ (100k requests, 50 concurrency) in apache bench I get something like 6k req/s, the second time I r...
[ "Two things.\nFirst, please make Class Name start with an Upper Case Letter. It's more conventional and easier to read.\nMore importantly, in the stackless_accept function you accumulate a list of Sock objects, named sockets. This list appears to grow endlessly. Yes, you have a remove, but it isn't always invoke...
[ 14 ]
[]
[]
[ "io", "networking", "performance", "python", "python_stackless" ]
stackoverflow_0000554805_io_networking_performance_python_python_stackless.txt
Q: Parameterised regular expression in Python In Python, is there a better way to parameterise strings into regular expressions than doing it manually like this: test = 'flobalob' names = ['a', 'b', 'c'] for name in names: regexp = "%s" % (name) print regexp, re.search(regexp, test) This noddy example tries ...
Parameterised regular expression in Python
In Python, is there a better way to parameterise strings into regular expressions than doing it manually like this: test = 'flobalob' names = ['a', 'b', 'c'] for name in names: regexp = "%s" % (name) print regexp, re.search(regexp, test) This noddy example tries to match each name in turn. I know there's bette...
[ "Well, as you build a regexp from a string, I see no other way. But you could parameterise the string itself with a dictionary:\nd = {'bar': 'a', 'foo': 'b'}\nregexp = '%(foo)s|%(bar)s' % d\n\nOr, depending on the problem, you could use list comprehensions:\nvlist = ['a', 'b', 'c']\nregexp = '|'.join([s for s in v...
[ 6, 2, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000554957_python_regex.txt
Q: Python or Ruby for a .NET developer? I'm a C# .NET developer and I work on mostly ASP.NET projects. I want to learn a new programming language, to improve my programming skills by experiencing a new language, to see something different then microsoft environment, and maybe to think in a different way. I focus o...
Python or Ruby for a .NET developer?
I'm a C# .NET developer and I work on mostly ASP.NET projects. I want to learn a new programming language, to improve my programming skills by experiencing a new language, to see something different then microsoft environment, and maybe to think in a different way. I focus on two languages for my goal. Python and Ru...
[ "Both languages are powerful and fun. Either would be a useful addition to your tool box.\nPython has a larger community and probably more mature documentation and libraries. Its object-orientation is a little inconsistent and feels (to me, IMHO) like something that was bolted on to the language. You can alter clas...
[ 16, 6, 3, 2, 2, 2, 1, 0 ]
[]
[]
[ "comparison", "python", "ruby", "ruby_on_rails" ]
stackoverflow_0000551465_comparison_python_ruby_ruby_on_rails.txt
Q: Multiple output files edit: Initially I was trying to be general but it came out vague. I've included more detail below. I'm writing a script that pulls in data from two large CSV files, one of people's schedules and the other of information about their schedules. The data is mined and combined to eventually crea...
Multiple output files
edit: Initially I was trying to be general but it came out vague. I've included more detail below. I'm writing a script that pulls in data from two large CSV files, one of people's schedules and the other of information about their schedules. The data is mined and combined to eventually create pajek format graphs for ...
[ "I would open seven file streams as accumulating them might be quite memory extensive if it's a lot of data. Of course that is only an option if you can sort them live and don't first need all data read to do the sorting.\n", "\"...pulls in data from two large CSV files, one of people's schedules and the other of...
[ 2, 2 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0000555146_file_io_python.txt
Q: Match series of (non-nested) balanced parentheses at end of string How can I match one or more parenthetical expressions appearing at the end of string? Input: 'hello (i) (m:foo)' Desired output: ['i', 'm:foo'] Intended for a python script. Paren marks cannot appear inside of each other (no nesting), and the par...
Match series of (non-nested) balanced parentheses at end of string
How can I match one or more parenthetical expressions appearing at the end of string? Input: 'hello (i) (m:foo)' Desired output: ['i', 'm:foo'] Intended for a python script. Paren marks cannot appear inside of each other (no nesting), and the parenthetical expressions may be separated by whitespace. It's harder than ...
[ "paren_pattern = re.compile(r\"\\(([^()]*)\\)(?=(?:\\s*\\([^()]*\\))*\\s*$)\")\n\ndef getParens(s):\n return paren_pattern.findall(s)\n\nor even shorter:\ngetParens = re.compile(r\"\\(([^()]*)\\)(?=(?:\\s*\\([^()]*\\))*\\s*$)\").findall\n\nexplaination:\n\\( # opening paren\n([^()]*) ...
[ 6, 5 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000555344_python_regex.txt
Q: SQLAlchemy/Elixir validation rules? I just found out how to validate my database input before saving it, but I'm kinda bummed to find there are no premade rules (like validate email, length, etc) that are found in some web based frameworks. Are there any validation libraries laying around anywhere or somewhere tha...
SQLAlchemy/Elixir validation rules?
I just found out how to validate my database input before saving it, but I'm kinda bummed to find there are no premade rules (like validate email, length, etc) that are found in some web based frameworks. Are there any validation libraries laying around anywhere or somewhere that some premade validation lists are hidin...
[ "Yes. There are. But keep your validation separate from your data layer. (As all the web frameworks do.)\nNow the libraries you can use for validation are the exact form libraries from the web frameworks. Start with:\n\nFormencode\n\nAnd a lot of others have sprung up recently, but most of them also deal with some ...
[ 3 ]
[]
[]
[ "python", "python_elixir", "sqlalchemy", "validation" ]
stackoverflow_0000555578_python_python_elixir_sqlalchemy_validation.txt
Q: Getting a list of all modules in the current package Here's what I want to do: I want to build a test suite that's organized into packages like tests.ui, tests.text, tests.fileio, etc. In each __init__.py in these packages, I want to make a test suite consisting of all the tests in all the modules in that packag...
Getting a list of all modules in the current package
Here's what I want to do: I want to build a test suite that's organized into packages like tests.ui, tests.text, tests.fileio, etc. In each __init__.py in these packages, I want to make a test suite consisting of all the tests in all the modules in that package. Of course, getting all the tests can be done with unit...
[ "Solution to exactly this problem from our django project:\n\"\"\"Test loader for all module tests\n\"\"\"\nimport unittest\nimport re, os, imp, sys\n\ndef find_modules(package):\n files = [re.sub('\\.py$', '', f) for f in os.listdir(os.path.dirname(package.__file__))\n if f.endswith(\".py\")]\n r...
[ 2, 2, 1 ]
[]
[]
[ "module", "package", "python", "python_2.5", "unit_testing" ]
stackoverflow_0000555571_module_package_python_python_2.5_unit_testing.txt
Q: Python code to find if x is following y on twitter. More Pythonic way please I wrote a twitter application in Python. Following is the code I used for a module where I find if x is following y. This code can be obviously improved upon. A pythonic way to do that? import urllib2 import sys import re import base64 fr...
Python code to find if x is following y on twitter. More Pythonic way please
I wrote a twitter application in Python. Following is the code I used for a module where I find if x is following y. This code can be obviously improved upon. A pythonic way to do that? import urllib2 import sys import re import base64 from urlparse import urlparse import simplejson def is_follows(follower, following)...
[ "Three things:\n\nFix the indentation (but then I guess this was not done on purpose).\nUse formatting instead of concatenation in constructing theurl.\nRemove the fol variable. Rather, do the following:\n\n\ntry:\n return simplejson.load(urllib2.urlopen(handle))\nexcept IOError, e:\n # here we shouldn't fail...
[ 2, 2, 2, 0 ]
[]
[]
[ "authentication", "python", "twitter" ]
stackoverflow_0000556342_authentication_python_twitter.txt
Q: WingIDE no autocompletion for my modules If anyone using WingIDE for their python dev needs: For some reason I get auto-completion on all the standard python libraries (like datetime....) but not on my own modules. So if I create my own class and then import it from another class, I get no auto-completion on it. D...
WingIDE no autocompletion for my modules
If anyone using WingIDE for their python dev needs: For some reason I get auto-completion on all the standard python libraries (like datetime....) but not on my own modules. So if I create my own class and then import it from another class, I get no auto-completion on it. Does anyone know why this is?
[ "Just found an answer, it has to do with pythonpath:\nhttp://www.wingware.com/doc/edit/how-analysis-works\n" ]
[ 0 ]
[]
[]
[ "ide", "python" ]
stackoverflow_0000556785_ide_python.txt
Q: How to use storeHtmlSource in python code (Selenium RC) I found storeHtmlSource method description in Selenium reference, but can't figure out how to use it in python code I generated by exporting recording of my actions from the Selenium IDE. I need to pass the html source code of the current page into a function...
How to use storeHtmlSource in python code (Selenium RC)
I found storeHtmlSource method description in Selenium reference, but can't figure out how to use it in python code I generated by exporting recording of my actions from the Selenium IDE. I need to pass the html source code of the current page into a function for processing. How to do that? Can anyone show example of c...
[ "I can't speak for Python, but check out the getHtmlSource method for the Java API of the Selenium interface. It explains what it does pretty clearly.\n" ]
[ 1 ]
[]
[]
[ "html", "python", "selenium" ]
stackoverflow_0000522229_html_python_selenium.txt
Q: Which Version of TurboGears should I use for a new project? I'm planing a new project and I want to use TurboGears. The problem is: I'm not sure which version to choose. There are three choices: Turbogears 1.0.8 (stable) Turbogears 1.1 (beta 3) Turbogears 2.0 (beta 4) As this is a new project I dont want to choose...
Which Version of TurboGears should I use for a new project?
I'm planing a new project and I want to use TurboGears. The problem is: I'm not sure which version to choose. There are three choices: Turbogears 1.0.8 (stable) Turbogears 1.1 (beta 3) Turbogears 2.0 (beta 4) As this is a new project I dont want to choose the wrong framework. So where are the differeneces, how "beta" i...
[ "I personally would go with TG2 (but would also look at other frameworks such as Pylons or repoze.bfg) esp. if it's a new project. Remember that you might need to upgrade at some point (or want to at least). TG2 also is offers full WSGI support which gains more and more traction and is IMHO also something you reall...
[ 5, 1 ]
[]
[]
[ "project", "python", "turbogears" ]
stackoverflow_0000557101_project_python_turbogears.txt
Q: Django - having middleware communicate with views/templates Alright, this is probably a really silly question but I am new to Python/Django so I can't really wrap my head around its scoping concepts just yet. Right now I am writing a middleware class to handle some stuff, and I want to set 'global' variables that ...
Django - having middleware communicate with views/templates
Alright, this is probably a really silly question but I am new to Python/Django so I can't really wrap my head around its scoping concepts just yet. Right now I am writing a middleware class to handle some stuff, and I want to set 'global' variables that my views and templates can access. What is the "right" way of doi...
[ "\nIt's not the best way. You could set my_var on the request rather than on the settings. Settings are global and apply to the whole site. You don't want to modify it for every request. There could be concurrency issues with multiple request updating/reading the variable at the same time.\nTo access request.my_var...
[ 19, 12, 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000557460_django_python.txt
Q: Python for Autohotkey style key-combination sniffing, automation? I want to automate several tasks (eg. simulate eclipse style ctrl-shift-R open dialog for other editors). The general pattern is: the user will press some key combination, my program will detect it and potentially pop up a dialog to get user input, ...
Python for Autohotkey style key-combination sniffing, automation?
I want to automate several tasks (eg. simulate eclipse style ctrl-shift-R open dialog for other editors). The general pattern is: the user will press some key combination, my program will detect it and potentially pop up a dialog to get user input, and then run a corresponding command, typically by running an executabl...
[ "You may want to look at AutoIt. It does everything that AutoHotKey can do, but the language syntax doesn't make you want to pull your hair out. Additonally, it has COM bindings so you can use most of it's abilities easily in python if you so desired. I've posted about how to do it here before.\n", "Found the ...
[ 7, 5 ]
[]
[]
[ "autohotkey", "python" ]
stackoverflow_0000294285_autohotkey_python.txt
Q: How to lookup custom ip address field stored as integer in Django-admin? In my Django model I've created custom MyIPAddressField which is stored as integer in mysql backend. To do that I've implemented to_python, get_db_prep_value, get_iternal_type (returns PositiveIntegerField) and formfield methods (uses stock I...
How to lookup custom ip address field stored as integer in Django-admin?
In my Django model I've created custom MyIPAddressField which is stored as integer in mysql backend. To do that I've implemented to_python, get_db_prep_value, get_iternal_type (returns PositiveIntegerField) and formfield methods (uses stock IPAddressField as form_class). The only problem is field lookup in cases like b...
[ "You could instruct the ORM to add an extra field to your SQL queries, like so:\nIPAddressModel.objects.extra(select={'ip': \"inet_ntoa(ip_address)\"})\n\nThis adds SELECT inet_ntoa(ip_address) as ip to the query and a field ip to your objects. You can use the new synthesized field in your WHERE clause.\nAre you su...
[ 2 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0000541115_django_mysql_python.txt
Q: Converting a database-driven (non-OO) python script into a non-database driven, OO-script I have some software that is heavily dependent on MySQL, and is written in python without any class definitions. For performance reasons, and because the database is really just being used to store and retrieve large amounts ...
Converting a database-driven (non-OO) python script into a non-database driven, OO-script
I have some software that is heavily dependent on MySQL, and is written in python without any class definitions. For performance reasons, and because the database is really just being used to store and retrieve large amounts of data, I'd like to convert this to an object-oriented python script that does not use the dat...
[ "If the data is a natural fit for database tables (\"rectangular data\"), why not convert it to sqlite? It's portable -- just one file to move the db around, and sqlite is available anywhere you have python (2.5 and above anyway).\n", "Generally you want your Objects to absolutely match your \"real world entitie...
[ 5, 2, 1, 1, 1, 1, 1, 1 ]
[]
[]
[ "object", "python" ]
stackoverflow_0000557199_object_python.txt
Q: What is wrong with my nested loops in Python? How do I make nested loops in Python (version 3.0)? I am trying to get the following loops to show me the products of two numbers: def PrintProductsBelowNumber(number): number1 = 1 number2 = 1 while number1 <= number: while number2 <= number: ...
What is wrong with my nested loops in Python?
How do I make nested loops in Python (version 3.0)? I am trying to get the following loops to show me the products of two numbers: def PrintProductsBelowNumber(number): number1 = 1 number2 = 1 while number1 <= number: while number2 <= number: print(number1, "*", number2, "=", number1 * n...
[ "number2 only gets initialized once, you need to re-initialize it for each iteration of the inner loop. However, this code is very C-like and not very Pythonic. The better way to do it would be to use the for number in range(n) construct:\ndef PrintProductsBelowNumber(number):\n for number1 in range(1, number+...
[ 14, 8, 0 ]
[]
[]
[ "loops", "nested", "python" ]
stackoverflow_0000558539_loops_nested_python.txt
Q: Make pyunit show output for every assertion How can I make python's unittest module show output for every assertion, rather than failing at the first one per test case? It would be much easier to debug if I could see the complete pattern of failures rather than just the first one. In my case the assertions are bas...
Make pyunit show output for every assertion
How can I make python's unittest module show output for every assertion, rather than failing at the first one per test case? It would be much easier to debug if I could see the complete pattern of failures rather than just the first one. In my case the assertions are based on a couple loops over an array containing an ...
[ "import unittest\nimport get_nodes\n\nclass TestSuper(unittest.TestCase):\n def setUp( self ):\n self.root = get_nodes.mmnode_plus.factory('mytree.xml')\n def condition( self, aNode, skip_traversal, skip_as_child, skip_as_parent, is_leaf ):\n self.assertEquals( skip_traversal, aNode.skip_travers...
[ 2, 1 ]
[]
[]
[ "python", "python_unittest", "unit_testing" ]
stackoverflow_0000557213_python_python_unittest_unit_testing.txt
Q: DOM Aware Browser Python GUI Widget I'm looking for a python browser widget (along the lines of pyQT4's QTextBrowser class or wxpython's HTML module) that has events for interaction with the DOM. For example, if I highlight an h1 node, the widget class should have a method that notifies me something was highlighte...
DOM Aware Browser Python GUI Widget
I'm looking for a python browser widget (along the lines of pyQT4's QTextBrowser class or wxpython's HTML module) that has events for interaction with the DOM. For example, if I highlight an h1 node, the widget class should have a method that notifies me something was highlighted and what dom properties that node had (...
[ "It may not be ideal for your purposes, but you might want to take a look at the Python bindings to KHTML that are part of PyKDE. One place to start looking is the KHTMLPart class:\nhttp://api.kde.org/pykde-4.2-api/khtml/KHTMLPart.html\nSince the API for this class is based on the signals and slots paradigm used in...
[ 2, 1, 1 ]
[]
[]
[ "browser", "python", "widget" ]
stackoverflow_0000531487_browser_python_widget.txt
Q: Shared folder sessions in Python I'm trying to get a list of currently-open sessions in Python via WMI. What I'm after is the exact information displayed in the Computer Management thingy, when you go to System Tools -> Shared Folders -> Sessions (ie username, computer name, connected time, that sort of thing). I ...
Shared folder sessions in Python
I'm trying to get a list of currently-open sessions in Python via WMI. What I'm after is the exact information displayed in the Computer Management thingy, when you go to System Tools -> Shared Folders -> Sessions (ie username, computer name, connected time, that sort of thing). I know (or at least believe) it has some...
[ "Never mind -- I found it:\n>>> import wmi\n>>> c = wmi.WMI()\n>>> for x in c.Win32_ConnectionShare():\n print \"%s: %s\" % (x.Dependent.Username, x.Dependent.ComputerName)\n\n" ]
[ 1 ]
[]
[]
[ "python", "shared_directory", "winapi", "wmi" ]
stackoverflow_0000559662_python_shared_directory_winapi_wmi.txt
Q: Django - queries made repeat/inefficient Alright, I have a Django view, like this: @render_to('home/main.html') def login(request): # also tried Client.objects.select_related().all() clients = Client.objects.all() return {'clients':clients} And I have a template, main.html, like this: <ul> {% for clie...
Django - queries made repeat/inefficient
Alright, I have a Django view, like this: @render_to('home/main.html') def login(request): # also tried Client.objects.select_related().all() clients = Client.objects.all() return {'clients':clients} And I have a template, main.html, like this: <ul> {% for client in clients %} <li>{{ client.full_name }}</l...
[ "Django uses a cache. The RDBMS uses a cache. Don't prematurely optimize the queries. \nYou can play with bulk queries in your view function instead of one-at-a-time queries in your template. \n@render_to('home/main.html')\ndef login(request):\n # Query all clients \n clients = Client.objects.all()\n #...
[ 7, 4, 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000559701_django_python.txt
Q: Debugging web apps I've gotten pretty used to step-through debuggers over the years, both in builder, and using the pydev debugger in Eclipse. Currently, I'm making something in Python and running it on Google App Engine, and I should add that I'm pretty new to developing any real web app; I've never really done ...
Debugging web apps
I've gotten pretty used to step-through debuggers over the years, both in builder, and using the pydev debugger in Eclipse. Currently, I'm making something in Python and running it on Google App Engine, and I should add that I'm pretty new to developing any real web app; I've never really done much beyond editing HTML...
[ "The dev_appserver is just a python script, you can simply use the pydev debugger on that script with the proper arguments as far as I know.\nHere is a very detailed guide on how to do that:\nhttp://www.ibm.com/developerworks/opensource/library/os-eclipse-mashup-google-pt1/index.html\n", "I would suggest to use l...
[ 7, 4, 2, 2 ]
[]
[]
[ "debugging", "eclipse", "google_app_engine", "python" ]
stackoverflow_0000557927_debugging_eclipse_google_app_engine_python.txt
Q: Issue with PyAMF, Django, and Python's "property" feature So far, I've had great success using PyAMF to communicate between my Flex front-end and my Django back-end. However, I believe I've encountered a bug. The following example (emphasis on the word "example") demonstrates the (potential) bug: My Flex app con...
Issue with PyAMF, Django, and Python's "property" feature
So far, I've had great success using PyAMF to communicate between my Flex front-end and my Django back-end. However, I believe I've encountered a bug. The following example (emphasis on the word "example") demonstrates the (potential) bug: My Flex app contains the following VO: package myproject.model.vo { [Binda...
[ "I just received the following response from PyAMF's lead developer. It's definitely a bug:\n\nThis is a bug in the way the Django\n adapter handles non models.fields.*\n properties.\nIf I do:\n\nimport pyamf\n\nclass Book(object): \ndef _get_number_of_odd_pages(self):\n return 52\n\nnumberOfOddPages = prope...
[ 1 ]
[ "Not at all.\nDo you think the error is from Django or from Flex? You could first of all trace the AMF Object in Flex. If the value there is allready 0 then have a good look what PyAMF does.\n" ]
[ -1 ]
[ "apache_flex", "django", "flex3", "pyamf", "python" ]
stackoverflow_0000558926_apache_flex_django_flex3_pyamf_python.txt
Q: How do i extract my required data from HTML file? This is the HTML I have: p_tags = '''<p class="foo-body"> <font class="test-proof">Full name</font> Foobar<br /> <font class="test-proof">Born</font> July 7, 1923, foo, bar<br /> <font class="test-proof">Current age</font> 27 years 226 days<br /> <font clas...
How do i extract my required data from HTML file?
This is the HTML I have: p_tags = '''<p class="foo-body"> <font class="test-proof">Full name</font> Foobar<br /> <font class="test-proof">Born</font> July 7, 1923, foo, bar<br /> <font class="test-proof">Current age</font> 27 years 226 days<br /> <font class="test-proof">Major teams</font> <span style="white-sp...
[ "The issue is that your HTML is not very well thought out -- you have a \"mixed content model\" where your labels and your data are interleaved. Your labels are wrapped in <font> Tags, but your data is in NavigableString nodes.\nYou need to iterate over the contents of p_tag. There will be two kinds of nodes: Tag...
[ 4, 4, 2, 0 ]
[]
[]
[ "beautifulsoup", "python", "screen_scraping" ]
stackoverflow_0000560936_beautifulsoup_python_screen_scraping.txt
Q: Want procmail to run a custom python script, everytime a new mail shows up I have a pretty usual requirement with procmail but I am unable to get the results somehow. I have procmailrc file with this content: :0 * ^To.*@myhost | /usr/bin/python /work/scripts/privilege_emails_forward.py Wherein my custom python sc...
Want procmail to run a custom python script, everytime a new mail shows up
I have a pretty usual requirement with procmail but I am unable to get the results somehow. I have procmailrc file with this content: :0 * ^To.*@myhost | /usr/bin/python /work/scripts/privilege_emails_forward.py Wherein my custom python script(privilege_emails_forward.py) will be scanning through the email currently r...
[ "That is just fine, just put fw after :0 (:0 fw). Your python program will receive the mail on stdin. You have to 'echo' the possibly transformed mail on stdout.\nfw means:\n\nf Consider the pipe as a filter.\nw Wait for the filter or program to finish and check its exitcode (normally ignored); if the filter is uns...
[ 11, 5 ]
[]
[]
[ "email", "procmail", "python" ]
stackoverflow_0000557906_email_procmail_python.txt
Q: python MySQL module class file name I am confused how directory name, file name and class name all work together. This is what I have at the moment app.py database/ client.py staff.py order.py Inside client.py I have a single class called client, which acts as the database model (MVC). The same...
python MySQL module class file name
I am confused how directory name, file name and class name all work together. This is what I have at the moment app.py database/ client.py staff.py order.py Inside client.py I have a single class called client, which acts as the database model (MVC). The same with my other files: staff.py has a clas...
[ "Python has two basic ways of importing content. Modules and Packages.\n\nA module is simply a python file on the include path: order.py\nIf order.py defines a class named foo, then access to that class could be had by:\nimport order\no = order.foo()\n\nIn order to use the syntax from the orignial question, you wo...
[ 4 ]
[]
[]
[ "class", "directory", "file", "module", "python" ]
stackoverflow_0000561791_class_directory_file_module_python.txt
Q: Where should I post my python code? Today I needed to parse some data out from an xlsx file (Office open XML Spreadsheet). I could have just opened the files in openoffice and exported to csv. However I will need to reimport data from this spreadsheet later, and I wanted to eliminate the manual operation. I search...
Where should I post my python code?
Today I needed to parse some data out from an xlsx file (Office open XML Spreadsheet). I could have just opened the files in openoffice and exported to csv. However I will need to reimport data from this spreadsheet later, and I wanted to eliminate the manual operation. I searched on the net for xlsx parser, and all I ...
[ "GitHub would also be a great place to post this. Especially as that would allow others to quickly fork their own copies and make any improvements or modifications they need. These changes would then also be available to anyone else who wants them.\n", "You should post it here. There are plenty of recipes here an...
[ 6, 5, 2, 1, 1, 0, 0 ]
[]
[]
[ "excel_2007", "python" ]
stackoverflow_0000556967_excel_2007_python.txt
Q: I want to load all of the unit-tests in a tree, can it be done? I have a heirarchical folder full of Python unit-tests. They are all importable ".py" files which define TestCase objects. This folder contains thousands of files in many nested subdirectories and was written by somebody else. I do not have permission...
I want to load all of the unit-tests in a tree, can it be done?
I have a heirarchical folder full of Python unit-tests. They are all importable ".py" files which define TestCase objects. This folder contains thousands of files in many nested subdirectories and was written by somebody else. I do not have permission to change it, I just have to run it. I want to generate a single Tes...
[ "The nose application may be useful for you, either directly, or to show how to implement this.\nhttp://code.google.com/p/python-nose/ seems to be the home page.\nBasically, what you want to do is walk the source tree (os.walk), use imp.load_module\nto load the module, use unittest.defaultTestLoader to load the tes...
[ 4, 2, 1 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0000562349_python_unit_testing.txt
Q: Python Imaging Library save function syntax Simple one I think but essentially I need to know what the syntax is for the save function on the PIL. The help is really vague and I can't find anything online. Any help'd be great, thanks :). A: From the PIL Handbook: im.save(outfile, options...) im.save(outfile, fo...
Python Imaging Library save function syntax
Simple one I think but essentially I need to know what the syntax is for the save function on the PIL. The help is really vague and I can't find anything online. Any help'd be great, thanks :).
[ "From the PIL Handbook:\nim.save(outfile, options...)\n\nim.save(outfile, format, options...)\n\nSimplest case:\nim.save('my_image.png')\n\nor whatever. In this case, the type of the image will be determined from the extension. Is there a particular problem you're having? Or specific saving option that you'd like t...
[ 18, 1 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0000562519_python_python_imaging_library.txt
Q: python upload - where are tmp/FILES? I'm running python 2.4 from cgi and I'm trying to upload to a cloud service using a python api. In php, the $_FILE array contains a "tmp" element which is where the file lives until you place it where you want it. What's the equivalent in python? if I do this fileitem = fo...
python upload - where are tmp/FILES?
I'm running python 2.4 from cgi and I'm trying to upload to a cloud service using a python api. In php, the $_FILE array contains a "tmp" element which is where the file lives until you place it where you want it. What's the equivalent in python? if I do this fileitem = form['file'] fileitem.filename is the name ...
[ "The file is a real file, but the cgi.FieldStorage unlinked it as soon as it was created so that it would exist only as long as you keep it open, and no longer has a real path on the file system.\nYou can, however, change this...\nYou can extend the cgi.FieldStorage and replace the make_file method to place the fil...
[ 2, 1 ]
[]
[]
[ "cgi", "mosso", "python", "upload" ]
stackoverflow_0000562278_cgi_mosso_python_upload.txt
Q: Context processor using Werkzeug and Jinja2 My application is running on App Engine and is implemented using Werkzeug and Jinja2. I'd like to have something functionally equivalent of Django's own context processor: a callable that takes a request and adds something to the template context. I already have a "conte...
Context processor using Werkzeug and Jinja2
My application is running on App Engine and is implemented using Werkzeug and Jinja2. I'd like to have something functionally equivalent of Django's own context processor: a callable that takes a request and adds something to the template context. I already have a "context processors" that add something to the template...
[ "One way of achieving this is through late-bound template globals using the thread-local proxy in Werkzeug.\nA simple example that puts the request into the the template globals:\nfrom werkzeug import Local, LocalManager\nlocal = Local()\nlocal_manager = LocalManager([local])\n\nfrom jinja2 import Environment, File...
[ 4, 3 ]
[]
[]
[ "django", "google_app_engine", "jinja2", "python", "werkzeug" ]
stackoverflow_0000539116_django_google_app_engine_jinja2_python_werkzeug.txt
Q: Can you recommend a Python SOAP client that can accept WS-Attachments? I've read mixed reviews of both Suds and ZSI -- two Python SOAP libraries. However, I'm unclear whether either of them can support WS-Attachments. I'd prefer to use Suds (appears to be more straightforward), but I'll defer to whichever librar...
Can you recommend a Python SOAP client that can accept WS-Attachments?
I've read mixed reviews of both Suds and ZSI -- two Python SOAP libraries. However, I'm unclear whether either of them can support WS-Attachments. I'd prefer to use Suds (appears to be more straightforward), but I'll defer to whichever library suits my needs.
[ "For your requirements I'd have to recommend ZSI. From its documentation,\n\nIt can also be used to build applications using SOAP Messages with Attachments.\n\nTheir website is not as pretty as Suds but the package includes promising documentation.\nSOAPpy has support for attachments on its TODO list. Suds does not...
[ 1, 1, 0 ]
[]
[]
[ "python", "soap" ]
stackoverflow_0000491404_python_soap.txt
Q: String separation in required format, Pythonic way? (with or w/o Regex) I have a string in the format: t='@abc @def Hello this part is text' I want to get this: l=["abc", "def"] s='Hello this part is text' I did this: a=t[t.find(' ',t.rfind('@')):].strip() s=t[:t.find(' ',t.rfind('@'))].strip() b=a.split('@') l...
String separation in required format, Pythonic way? (with or w/o Regex)
I have a string in the format: t='@abc @def Hello this part is text' I want to get this: l=["abc", "def"] s='Hello this part is text' I did this: a=t[t.find(' ',t.rfind('@')):].strip() s=t[:t.find(' ',t.rfind('@'))].strip() b=a.split('@') l=[i.strip() for i in b][1:] It works for the most part, but it fails when th...
[ "Building unashamedly on MrTopf's effort:\nimport re\nrx = re.compile(\"((?:@\\w+ +)+)(.*)\")\nt='@abc @def @xyz Hello this part is text and my email is foo@ba.r'\na,s = rx.match(t).groups()\nl = re.split('[@ ]+',a)[1:-1]\nprint l\nprint s\n\nprints:\n\n['abc', 'def', 'xyz']\n Hello this part is text and my ema...
[ 13, 7, 5, 3, 3, 3, 1 ]
[]
[]
[ "format", "python", "regex", "string" ]
stackoverflow_0000558105_format_python_regex_string.txt
Q: Import python functions into a .NET language? I am a C# .NET programmer and am learning Python. I have downloaded IronPython, and know that it can call into .NET libraries. I'm wondering whether there is a way to do the reverse, that is to call into some existing "classic" Python libraries in my C# code, maybe ...
Import python functions into a .NET language?
I am a C# .NET programmer and am learning Python. I have downloaded IronPython, and know that it can call into .NET libraries. I'm wondering whether there is a way to do the reverse, that is to call into some existing "classic" Python libraries in my C# code, maybe using .NET Interop. I'd like to be able to access f...
[ "Ironpython 2.0 is CPython 2.5 compatible, so pure Python that uses <=2.5 APIs should work fine under Ironpython. I believe Ironpython code can then be compiled into a DLL.\nFor C-extensions like Pygame, you might want to take a look at Ironclad. It's a project to allow for C-extensions to be used within Ironpython...
[ 5, 3 ]
[]
[]
[ "c#", "ironpython", "python" ]
stackoverflow_0000561626_c#_ironpython_python.txt
Q: Implementing chat in an application? I'm making a game and I am using Python for the server side. It would be fairly trivial to implement chat myself using Python - that's not my question. My question is I was just wondering if there were any pre-made chat servers or some kind of service that I would be able to ...
Implementing chat in an application?
I'm making a game and I am using Python for the server side. It would be fairly trivial to implement chat myself using Python - that's not my question. My question is I was just wondering if there were any pre-made chat servers or some kind of service that I would be able to implement inside of my game instead of rol...
[ "I recommend using XMPP/Jabber. There are a lot of libraries for clients and servers in different languages. It's free/open source.\nhttp://en.wikipedia.org/wiki/XMPP\n", "Maybe you could use IRC as a chat service, I know of irclib for python, its more of a client but in theory, you could use it to proxy another ...
[ 10, 1, 1 ]
[]
[]
[ "chat", "python" ]
stackoverflow_0000561301_chat_python.txt
Q: Anybody tried mosso CloudFiles with Google AppEngine? I'm wondering if anybody tried to integrate mosso CloudFiles with an application running on Google AppEngine (mosso does not provide testing sandbox so I cann't check for myself without registering)? Looking at the code it seems that this will not work due to h...
Anybody tried mosso CloudFiles with Google AppEngine?
I'm wondering if anybody tried to integrate mosso CloudFiles with an application running on Google AppEngine (mosso does not provide testing sandbox so I cann't check for myself without registering)? Looking at the code it seems that this will not work due to httplib and urllib limitations in AppEngine environment, but...
[ "It appears to implement a simple RESTful API, so there's no reason you couldn't use it from App Engine. Previously, you'd have had to write your own library to do so, using App Engine's urlfetch API, but with the release of SDK 1.1.9, you can now use urllib and httplib instead.\n" ]
[ 1 ]
[]
[]
[ "cloud", "google_app_engine", "mosso", "python", "storage" ]
stackoverflow_0000564460_cloud_google_app_engine_mosso_python_storage.txt
Q: can my programs access more than 4GB of memory? if I run python on a 64bit machine with a 64bit operating system, will my programs be able to access the full range of memory? I.e. Could I build a list with 10billion entries, assuming I had enough RAM? If not, are there other programming languages that would allow ...
can my programs access more than 4GB of memory?
if I run python on a 64bit machine with a 64bit operating system, will my programs be able to access the full range of memory? I.e. Could I build a list with 10billion entries, assuming I had enough RAM? If not, are there other programming languages that would allow this?
[ "You'll need to be sure that Python has been built as a 64 bit application. For example, on Win64 you'll be able to run the 32bit build of Python.exe but it won't get the benefits of the 64 bit environment as Windows will run it in a 32bit sandbox.\n", "The language python itself has no such restrictions, but per...
[ 7, 3 ]
[]
[]
[ "64_bit", "python" ]
stackoverflow_0000565030_64_bit_python.txt
Q: Using jep.invoke() method I need to call a function from a python script and pass in parameters into it. I have a test python script which I can call and run from java using Jepp - this then adds the person. Eg Test.py import Finding from Finding import * f = Finding() f.addFinding("John", "Doe", 27) Within my ...
Using jep.invoke() method
I need to call a function from a python script and pass in parameters into it. I have a test python script which I can call and run from java using Jepp - this then adds the person. Eg Test.py import Finding from Finding import * f = Finding() f.addFinding("John", "Doe", 27) Within my Finding class I have addFinding...
[ "Easier way to run python code in java is to use jython.\nEDIT: Found an article with examples in the jython website.\n" ]
[ 0 ]
[]
[]
[ "java", "python" ]
stackoverflow_0000565060_java_python.txt
Q: Pydev and Pylons inside virtual environment, auto completion won’t work I have Pydev installed and running without problem with Python 2.6. I installed Pylons 0.9.7 RC 4 into virtual environment, then configured new interpreter to pint into virtual environment and this one is used for pylons project. My problem is...
Pydev and Pylons inside virtual environment, auto completion won’t work
I have Pydev installed and running without problem with Python 2.6. I installed Pylons 0.9.7 RC 4 into virtual environment, then configured new interpreter to pint into virtual environment and this one is used for pylons project. My problem is that code auto completion does not work for a classes from base library (one...
[ "perhaps this or this would help\nBTW: I guess that this is the correct behavior, this interpreter uses only the packages that are installed withing the virtualenv (this is the whole intent and purpose of the virtualenv isn't it?)\n" ]
[ 4 ]
[]
[]
[ "pydev", "pylons", "python", "virtualenv" ]
stackoverflow_0000540538_pydev_pylons_python_virtualenv.txt
Q: Setting values to the output of a formset in Django This question is somewhat linked to a question I asked previously: Generating and submitting a dynamic number of objects in a form with Django I'm wondering, if I've got separate default values for each form within a formset, am I able to pre-populate the fields?...
Setting values to the output of a formset in Django
This question is somewhat linked to a question I asked previously: Generating and submitting a dynamic number of objects in a form with Django I'm wondering, if I've got separate default values for each form within a formset, am I able to pre-populate the fields? For instance, a form requiring extra customer informatio...
[ "Pass in a list of dicts which contain the default values you want to set for each form:\nhttp://docs.djangoproject.com/en/dev/topics/forms/formsets/#using-initial-data-with-a-formset\n" ]
[ 1 ]
[]
[]
[ "django", "django_forms", "formset", "python" ]
stackoverflow_0000565034_django_django_forms_formset_python.txt
Q: python code for django view MODEL: class Pathology(models.Model): pathology = models.CharField(max_length=100) class Publication(models.Model): pubtitle = models.TextField() class Pathpubcombo(models.Model): pathology = models.ForeignKey(Pathology) publication = models.ForeignKey(Publication) L...
python code for django view
MODEL: class Pathology(models.Model): pathology = models.CharField(max_length=100) class Publication(models.Model): pubtitle = models.TextField() class Pathpubcombo(models.Model): pathology = models.ForeignKey(Pathology) publication = models.ForeignKey(Publication) List of pathology sent to HTML te...
[ "you should be using many-to-many relations as described here:\nhttp://www.djangoproject.com/documentation/models/many_to_many/\nLike:\nclass Pathology(models.Model):\n pathology = models.CharField(max_length=100)\n publications = models.ManyToManyField(Publication)\n\nclass Publication(models.Model):\n pu...
[ 5 ]
[]
[]
[ "django", "many_to_many", "python", "syntax" ]
stackoverflow_0000566083_django_many_to_many_python_syntax.txt
Q: How can I make this one-liner work in DOS? python -c "for x in range(1,10) print x" I enjoy python one liners with -c, but it is limited when indentation is needed. Any ideas? A: python -c "for x in range(1,10): print x" Just add the colon. To address the question in the comments: How can I make this work tho...
How can I make this one-liner work in DOS?
python -c "for x in range(1,10) print x" I enjoy python one liners with -c, but it is limited when indentation is needed. Any ideas?
[ "python -c \"for x in range(1,10): print x\"\n\nJust add the colon.\nTo address the question in the comments:\n\nHow can I make this work though? python -c \"import calendar;print calendar.prcal(2009);for x in range(1,10): print x\"\n\npython -c \"for x in range(1,10): x==1 and __import__('calendar').prcal(2009); p...
[ 12, 3, 3, 1, 1, 0 ]
[]
[]
[ "command_line", "python" ]
stackoverflow_0000566559_command_line_python.txt
Q: Building a "complete" number range w/out overlaps I need to build a full "number range" set given a series of numbers. I start with a list such as : ID START * 0 a 4 b 70 c 700 d 701 e 85 where "def" is the default range & should "fill-in" the gaps "overlaps" are value (70, 70...
Building a "complete" number range w/out overlaps
I need to build a full "number range" set given a series of numbers. I start with a list such as : ID START * 0 a 4 b 70 c 700 d 701 e 85 where "def" is the default range & should "fill-in" the gaps "overlaps" are value (70, 700, 701) in starting data And need the following resul...
[ "import operator\n\nranges = {\n '4' : 'a',\n '70' : 'b',\n '700': 'c',\n '701': 'd',\n '85' : 'e',\n '87' : 'a',\n}\n\ndef id_for_value(value):\n possible = '*'\n for idvalue, id in sorted(ranges.iteritems()):\n if value.startswith(idvalue):\n possible = id\n elif ...
[ 0 ]
[]
[]
[ "numbers", "overlap", "python", "range" ]
stackoverflow_0000566574_numbers_overlap_python_range.txt
Q: How can I anonymise XML data for selected tags? My question is as follows: I have to read a big XML file, 50 MB; and anonymise some tags/fields that relate to private issues, like name surname address, email, phone number, etc... I know exactly which tags in XML are to be anonymised. s|<a>alpha</a>|MD5ed(alpha)|e...
How can I anonymise XML data for selected tags?
My question is as follows: I have to read a big XML file, 50 MB; and anonymise some tags/fields that relate to private issues, like name surname address, email, phone number, etc... I know exactly which tags in XML are to be anonymised. s|<a>alpha</a>|MD5ed(alpha)|e; s|<h>beta</h>|MD5ed(beta)|e; where alpha and beta...
[ "You have to do something like the following in Python.\nimport xml.etree.ElementTree as xml # or lxml or whatever\nimport hashlib\ntheDoc= xml.parse( \"sample.xml\" )\nfor alphaTag in theDoc.findall( \"xpath/to/tag\" ):\n print alphaTag, alphaTag.text\n alphaTag.text = hashlib.md5(alphaTag.text).hexdigest()\...
[ 6, 4, 4, 3 ]
[]
[]
[ "anonymize", "perl", "python", "xml" ]
stackoverflow_0000565823_anonymize_perl_python_xml.txt
Q: How to stop Tkinter Frame from shrinking to fit its contents? This is the code that's giving me trouble. f = Frame(root, width=1000, bg="blue") f.pack(fill=X, expand=True) l = Label(f, text="hi", width=10, bg="red", fg="white") l.pack() If I comment out the lines with the Label, the Frame displays with the righ...
How to stop Tkinter Frame from shrinking to fit its contents?
This is the code that's giving me trouble. f = Frame(root, width=1000, bg="blue") f.pack(fill=X, expand=True) l = Label(f, text="hi", width=10, bg="red", fg="white") l.pack() If I comment out the lines with the Label, the Frame displays with the right width. However, adding the Label seems to shrink the Frame down ...
[ "By default, both pack and grid shrink or grow a widget to fit its contents, which is what you want 99.9% of the time. The term that describes this feature is geometry propagation. There is a command to turn geometry propagation on or off when using pack (pack_propagate) and grid (grid_propagate).\nSince you are us...
[ 76 ]
[]
[]
[ "frame", "label", "python", "tkinter" ]
stackoverflow_0000563827_frame_label_python_tkinter.txt
Q: PyDev debugger different from command line django runserver command I am trying to debug a problem with a django view. When I run it on the command line. I don't get any of these messages. However when I run the it in the PyDev debugger i get these error messages. I am running with the --noreload option. What do t...
PyDev debugger different from command line django runserver command
I am trying to debug a problem with a django view. When I run it on the command line. I don't get any of these messages. However when I run the it in the PyDev debugger i get these error messages. I am running with the --noreload option. What do these error messages mean? Why do I not get them when I run it on the comm...
[ "I seem to recall having similar issues debugging in PyDev related to the auto-reload mechanism of Django's test server. You can turn reloading off by passing --noreload to your runserver command. From there you just have to train yourself to restart your test server after making a code change while debugging.\nE...
[ 1 ]
[]
[]
[ "django", "eclipse", "pydev", "python" ]
stackoverflow_0000566819_django_eclipse_pydev_python.txt
Q: How can I process command line arguments in Python? What would be an easy expression to process command line arguments if I'm expecting anything like 001 or 999 (let's limit expectations to 001...999 range for this time), and few other arguments passed, and would like to ignore any unexpected? I understand if for ...
How can I process command line arguments in Python?
What would be an easy expression to process command line arguments if I'm expecting anything like 001 or 999 (let's limit expectations to 001...999 range for this time), and few other arguments passed, and would like to ignore any unexpected? I understand if for example I need to find out if "debug" was passed among pa...
[ "As others answered, optparse is the best option, but if you just want quick code try something like this:\nimport sys, re\n\nfirst_re = re.compile(r'^\\d{3}$')\n\nif len(sys.argv) > 1:\n\n if first_re.match(sys.argv[1]):\n print \"Primary argument is : \", sys.argv[1]\n else:\n raise ValueError...
[ 32, 16, 2, 2, 0 ]
[]
[]
[ "command_line", "command_line_arguments", "python" ]
stackoverflow_0000567879_command_line_command_line_arguments_python.txt
Q: How to programmatically insert comments into a Microsoft Word document? Looking for a way to programmatically insert comments (using the comments feature in Word) into a specific location in a MS Word document. I would prefer an approach that is usable across recent versions of MS Word standard formats and impleme...
How to programmatically insert comments into a Microsoft Word document?
Looking for a way to programmatically insert comments (using the comments feature in Word) into a specific location in a MS Word document. I would prefer an approach that is usable across recent versions of MS Word standard formats and implementable in a non-Windows environment (ideally using Python and/or Common Lisp)...
[ "Here is what I did:\n\nCreate a simple document with word (i.e. a very small one)\nAdd a comment in Word\nSave as docx.\nUse the zip module of python to access the archive (docx files are ZIP archives).\nDump the content of the entry \"word/document.xml\" in the archive. This is the XML of the document itself.\n\n...
[ 7, 2 ]
[]
[]
[ "common_lisp", "ms_word", "openxml", "python" ]
stackoverflow_0000568972_common_lisp_ms_word_openxml_python.txt
Q: How to extract frequency information from an input audio stream (using PortAudio)? I want to record sound (voice) using PortAudio (PyAudio) and output the corresponding sound wave on the screen. Hopeless as I am, I am unable to extract the frequency information from the audio stream so that I can draw it in Hz/tim...
How to extract frequency information from an input audio stream (using PortAudio)?
I want to record sound (voice) using PortAudio (PyAudio) and output the corresponding sound wave on the screen. Hopeless as I am, I am unable to extract the frequency information from the audio stream so that I can draw it in Hz/time form. Here's an example code snippet that records and plays recorded audio for five s...
[ "What you want is probably the Fourier transform of the audio data. There is several packages that can calculate that for you. scipy and numpy is two of them. It is often named \"Fast Fourier Transform\" (FFT), but that is just the name of the algorithm.\nHere is an example of it's usage: https://svn.enthought.com/...
[ 4, 1 ]
[]
[]
[ "frequency", "portaudio", "python", "voice" ]
stackoverflow_0000259451_frequency_portaudio_python_voice.txt
Q: Logging output of external program with (wx)python I'm writing a GUI for using the oracle exp/imp commands and starting sql-scripts through sqlplus. The subprocess class makes it easy to launch the commands, but I need some additional functionality. I want to get rid of the command prompt when using my wxPython GU...
Logging output of external program with (wx)python
I'm writing a GUI for using the oracle exp/imp commands and starting sql-scripts through sqlplus. The subprocess class makes it easy to launch the commands, but I need some additional functionality. I want to get rid of the command prompt when using my wxPython GUI, but I still need a way to show the output of the exp/...
[ "The solution is to use a list for your command\ncommand = [\"exp\", \"userid=user/pwd@nsn\", \"file=dump.dmp\"]\nprocess = subprocess.Popen(command, stdout=subprocess.PIPE)\n\nthen you read process.stdout in a line-by-line basis:\nline = process.stdout.readline()\n\nthat way you can update the GUI without waiting....
[ 1, 1, 0 ]
[ "Try this:\nimport subprocess\n\ncommand = \"ping google.com\"\n\nprocess = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)\noutput = process.stdout\nwhile 1:\n print output.readline(),\n\n" ]
[ -1 ]
[ "oracle", "python", "sqlplus", "wxpython" ]
stackoverflow_0000531708_oracle_python_sqlplus_wxpython.txt
Q: Getting Forms on Page in Python I'm working on a web vulnerability scanner. I have completed 30% of the program, in that it can scan only HTTP GET methods. But I've hit a snag now: I have no idea how I shall make the program pentest the POST method. I had the idea to make it extract the form data/names from all th...
Getting Forms on Page in Python
I'm working on a web vulnerability scanner. I have completed 30% of the program, in that it can scan only HTTP GET methods. But I've hit a snag now: I have no idea how I shall make the program pentest the POST method. I had the idea to make it extract the form data/names from all the pages on the website, but I have no...
[ "Use BeautifulSoup for screen scraping.\nFor heavier scripting, use twill :\n\ntwill is a simple language that allows users to browse the Web from a command-line interface. With twill, you can navigate through Web sites that use forms, cookies, and most standard Web features.\n\nWith twill, you can easily fill form...
[ 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000569477_python.txt
Q: Statistics with numpy I am working at some plots and statistics for work and I am not sure how I can do some statistics using numpy: I have a list of prices and another one of basePrices. And I want to know how many prices are with X percent above basePrice, how many are with Y percent above basePrice. Is there a ...
Statistics with numpy
I am working at some plots and statistics for work and I am not sure how I can do some statistics using numpy: I have a list of prices and another one of basePrices. And I want to know how many prices are with X percent above basePrice, how many are with Y percent above basePrice. Is there a simple way to do that using...
[ "Say you have\n>>> prices = array([100, 200, 150, 145, 300])\n>>> base_prices = array([90, 220, 100, 350, 350])\n\nThen the number of prices that are more than 10% above the base price are\n>>> sum(prices > 1.10 * base_prices)\n2\n\n", "Just for amusement, here's a slightly different take on dF's answer:\n>>> pri...
[ 8, 2, 1, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0000570137_numpy_python.txt
Q: With Twisted, how can 'connectionMade' fire a specific Deferred? This is part of a larger program; I'll explain only the relevant parts. Basically, my code wants to create a new connection to a remote host. This should return a Deferred, which fires once the connection is established, so I can send something on ...
With Twisted, how can 'connectionMade' fire a specific Deferred?
This is part of a larger program; I'll explain only the relevant parts. Basically, my code wants to create a new connection to a remote host. This should return a Deferred, which fires once the connection is established, so I can send something on it. I'm creating the connection with twisted.internet.interfaces.IReac...
[ "Looking at this some more, I think I've come up with a solution, although hopefully there is a better way; this seems kind of weird.\nTwisted has a class, ClientCreator that is used for producing simple single-use connections. It in theory does what I want; connects and returns a Deferred that fires when the conn...
[ 0 ]
[]
[]
[ "connection", "python", "reactor", "twisted" ]
stackoverflow_0000570397_connection_python_reactor_twisted.txt
Q: Detect when a Python module unloads I have a module that uses ctypes to wrap some functionality from a static library into a class. When the module loads, it calls an initialize function in the static library. When the module is unloaded (presumably when the interpreter exits), there's an unload function in the li...
Detect when a Python module unloads
I have a module that uses ctypes to wrap some functionality from a static library into a class. When the module loads, it calls an initialize function in the static library. When the module is unloaded (presumably when the interpreter exits), there's an unload function in the library that I'd like to be called. How can...
[ "Use the atexit module:\nimport mymodule\nimport atexit\n\n# call mymodule.unload('param1', 'param2') when the interpreter exits:\natexit.register(mymodule.unload, 'param1', 'param2')\n\nAnother simple example from the docs, using register as a decorator:\nimport atexit\n\n@atexit.register\ndef goodbye():\n prin...
[ 16 ]
[]
[]
[ "python" ]
stackoverflow_0000570636_python.txt
Q: Python c-api and unicode strings I need to convert between python objects and c strings of various encodings. Going from a c string to a unicode object was fairly simple using PyUnicode_Decode, however Im not sure how to go the other way //char* can be a wchar_t or any other element size, just make sure it is corr...
Python c-api and unicode strings
I need to convert between python objects and c strings of various encodings. Going from a c string to a unicode object was fairly simple using PyUnicode_Decode, however Im not sure how to go the other way //char* can be a wchar_t or any other element size, just make sure it is correctly terminated for its encoding Unic...
[ "\nI suspect it has somthing to do with PyUnicode_AsEncodedString however that returns a PyObject so I'm not sure how to put that into my buffer...\n\nThe PyObject returned is a PyStringObject, so you just need to use PyString_Size and PyString_AsString to get a pointer to the string's buffer and memcpy it to your ...
[ 3 ]
[]
[]
[ "c", "python", "python_c_api" ]
stackoverflow_0000570781_c_python_python_c_api.txt
Q: Django "SuspiciousOperation" Error While Deleting Uploaded File I'm developing in Django on Windows XP using the manage.py runserver command to serve files. Apache isn't involved. When I login to the administration and try to delete a file I get a "SuspiciousOperation" error. Here's the traceback: http://dpaste.co...
Django "SuspiciousOperation" Error While Deleting Uploaded File
I'm developing in Django on Windows XP using the manage.py runserver command to serve files. Apache isn't involved. When I login to the administration and try to delete a file I get a "SuspiciousOperation" error. Here's the traceback: http://dpaste.com/123112/ Here's my full model: http://dpaste.com/hold/123110/ How c...
[ "What is your MEDIA_ROOT in settings.py? From the back-trace, it seems you have set your MEDIA_ROOT to /static/.\nThis error is coming since Django is trying to access /static/ to which it has no access. Put an absolute pathname for MEDIA_ROOT like C:/Documents/static/ and give full permissions to Django to access ...
[ 5 ]
[]
[]
[ "django", "python", "windows" ]
stackoverflow_0000570952_django_python_windows.txt
Q: In Python, how might one log in, answer a web form via HTTP POST (not url-encoded), and fetch a returned XML file? I am basically trying to export a configuration file, once a week. While the product in question allows you to log in manually via a web client, enter some information, and get an XML file back when ...
In Python, how might one log in, answer a web form via HTTP POST (not url-encoded), and fetch a returned XML file?
I am basically trying to export a configuration file, once a week. While the product in question allows you to log in manually via a web client, enter some information, and get an XML file back when you submit, there's no facility for automating this. I can get away with using Python 2.5 (have used for a while) or 2....
[ "urllib2 should cover all of this.\nHere's a Basic Authentication example.\nHere's a Post with multipart/form-data.\n", "Try mechanize module.\n", "You should look at the MultipartPostHandler:\nhttp://odin.himinbi.org/MultipartPostHandler.py\nAnd if you need to support unicode file names , see a fix at:\nhttp:/...
[ 3, 2, 0 ]
[]
[]
[ "authentication", "cookies", "post", "python" ]
stackoverflow_0000571083_authentication_cookies_post_python.txt
Q: How to program a schedule I have to build a program that schedules based on certain rules. I'm not sure how to explain it, so let me give you an example.. You have Five People A,B,C,D,E. And you Have another set of people S1 S2 S3 S4 S5 S6 S7. If A B C D and E are available every hour from 9 to 5, and S1 S2 S3 S4 ...
How to program a schedule
I have to build a program that schedules based on certain rules. I'm not sure how to explain it, so let me give you an example.. You have Five People A,B,C,D,E. And you Have another set of people S1 S2 S3 S4 S5 S6 S7. If A B C D and E are available every hour from 9 to 5, and S1 S2 S3 S4 S5 S6 and S7 have a list of 3 p...
[ "Here's some python code that will do the trick. You will want to update VISITOR_PEOPLE. And if some people get to schedule before others, you'll need to reorder VISITOR_IDS.\nEdit: I added some more code to account for the fact that people can't be in a different place at the same time. You might want to make tha...
[ 3, 2, 1 ]
[]
[]
[ "python", "scheduling" ]
stackoverflow_0000570912_python_scheduling.txt
Q: Split tags in python I have a file that contains this: <html> <head> <title> Hello! - {{ today }}</title> </head> <body> {{ runner_up }} avasd {{ blabla }} sdvas {{ oooo }} </body> </html> What is the best or most Pythonic way to extract the {{today}}, {{runner_...
Split tags in python
I have a file that contains this: <html> <head> <title> Hello! - {{ today }}</title> </head> <body> {{ runner_up }} avasd {{ blabla }} sdvas {{ oooo }} </body> </html> What is the best or most Pythonic way to extract the {{today}}, {{runner_up}}, etc.? I know it can ...
[ "Mmkay, well here's a generator solution that seems to work well for me. You can also provide different open and close tags if you like.\ndef get_tags(s, open_delim ='{{', \n close_delim ='}}' ):\n\n while True:\n\n # Search for the next two delimiters in the source text\n start = s.fin...
[ 8, 3, 2, 1, 1 ]
[]
[]
[ "python", "split", "template_engine" ]
stackoverflow_0000571186_python_split_template_engine.txt
Q: How can I get the newest file from an FTP server? I am using Python to connect to an FTP server that contains a new list of data once every hour. I am only connecting once a day, and I only want to download the newest file in the directory. Is there a way to do this? A: Seems like any system that is automaticall...
How can I get the newest file from an FTP server?
I am using Python to connect to an FTP server that contains a new list of data once every hour. I am only connecting once a day, and I only want to download the newest file in the directory. Is there a way to do this?
[ "Seems like any system that is automatically generating a file once an hour is likely to be using an automated naming scheme. Are you over thinking the problem by asking the server for the newest file instead of more easily parsing the file names? \nThis wouldn't work in all cases, and if the directory got large ...
[ 1, -1 ]
[]
[]
[ "ftp", "python" ]
stackoverflow_0000570433_ftp_python.txt
Q: Python pysqlite not accepting my qmark parameterization I think I am being a bonehead, maybe not importing the right package, but when I do... from pysqlite2 import dbapi2 as sqlite import types import re import sys ... def create_asgn(self): stmt = "CREATE TABLE ? (login CHAR(8) PRIMARY KEY NOT NULL,...
Python pysqlite not accepting my qmark parameterization
I think I am being a bonehead, maybe not importing the right package, but when I do... from pysqlite2 import dbapi2 as sqlite import types import re import sys ... def create_asgn(self): stmt = "CREATE TABLE ? (login CHAR(8) PRIMARY KEY NOT NULL, grade INTEGER NOT NULL)" stmt2 = "insert into asgn v...
[ "That's because parameters can only be passed to VALUES. The table name can't be parametrized.\nAlso you have quotes around a parametrized argument on the second query. Remove the quotes, escaping is handled by the underlining library automatically for you.\n", "Try removing the quotes in the line that assigns to...
[ 7, 2, 1 ]
[]
[]
[ "pysqlite", "python", "python_db_api", "sqlite" ]
stackoverflow_0000474261_pysqlite_python_python_db_api_sqlite.txt
Q: The `%` operator I want to find all the numbers divisble by all the numbers between 1 and 5. how do I write the program so that if the remainder of 'start' divided by all the numbers that x goes through is equal to 0 that it will print start. Is there any syntax that will calculate what I'm looking for. thanks. im...
The `%` operator
I want to find all the numbers divisble by all the numbers between 1 and 5. how do I write the program so that if the remainder of 'start' divided by all the numbers that x goes through is equal to 0 that it will print start. Is there any syntax that will calculate what I'm looking for. thanks. import math def main(): ...
[ "First of all, you seem to ask for all multiples of 60. Those can be rendered easily like this (beware, this is an infinite loop):\nfrom itertools import count\n\nfor i in count():\n print i*60\n\nIf you just oversimplified your example, this is a more pythonic (and correct) solution of what you wrote (again an ...
[ 3, 0 ]
[]
[]
[ "math", "python" ]
stackoverflow_0000571538_math_python.txt
Q: What's the reason of providing some of the default methods in the global scope in Python? What's the reason of providing some of the default methods in the global scope, like the len function, instead of providing them on an instance level, like: list.len() instead of: len (list) I find methods like len to be ha...
What's the reason of providing some of the default methods in the global scope in Python?
What's the reason of providing some of the default methods in the global scope, like the len function, instead of providing them on an instance level, like: list.len() instead of: len (list) I find methods like len to be harder to discover than instance methods. Is there any reason behind this?
[ "This question is very similar to this one. And the answers is the same:\nBecause Guido van Rossum, the creator of Python, thinks that prefix notation is more readable in some cases. Here is the complete answer. I'm going to quote some parts:\n\n(a) For some operations, prefix notation just reads better than\n pos...
[ 6, 4, 2, 2, 0 ]
[ "You can write\nre.match(r\"\\w+\", \"dog\")\n\ninstead of\npattern = re.compile(r\"\\w+\")\npattern.match(\"dog\") \n\nLike You noticed, sometimes it doesn't make sense.\n" ]
[ -1 ]
[ "function", "python" ]
stackoverflow_0000571522_function_python.txt
Q: Adding elements to python generators Is it possible to append elements to a python generator? I'm currently trying to get all images from a set of disorganized folders and write them to a new directory. To get the files, I'm using os.walk() which returns a list of image files in a single directory. While I can mak...
Adding elements to python generators
Is it possible to append elements to a python generator? I'm currently trying to get all images from a set of disorganized folders and write them to a new directory. To get the files, I'm using os.walk() which returns a list of image files in a single directory. While I can make a generator out of this single list, I d...
[ "You are looking for itertools.chain. It will combine multiple iterables into a single one, like this:\n>>> import itertools \n>>> for i in itertools.chain([1,2,3], [4,5,6]):\n... print(i)\n... \n1\n2\n3\n4\n5\n6\n\n", "This should do it, where directories is your list of directories:\nimport os\nimport itert...
[ 29, 19, 4 ]
[ "Like this.\ndef threeGens( i, j, k ):\n for x in range(i):\n yield x\n for x in range(j):\n yield x\n for x in range(k):\n yield x\n\nWorks well. \n" ]
[ -1 ]
[ "append", "generator", "python" ]
stackoverflow_0000571850_append_generator_python.txt
Q: Solr search with escaping solr reserved keywords How do i query fields that contain solr reserved keywords as ":" in solr? For instance, q = 'uri:http://www.example.com' throws up an error for "http://www.example.com" containing reserved word ":" A: I just tested this and it seem that simply escaping ":" like "...
Solr search with escaping solr reserved keywords
How do i query fields that contain solr reserved keywords as ":" in solr? For instance, q = 'uri:http://www.example.com' throws up an error for "http://www.example.com" containing reserved word ":"
[ "I just tested this and it seem that simply escaping \":\" like \":\" does the trick:\nq = 'uri:http\\://www.example.com'\n\nFor my the index of my own site I tend to simply store the path of the URL though as I know the domain myself so that wasn't an issue for me before. But if you index external URLs then of cou...
[ 5, 1 ]
[]
[]
[ "pysolr", "python", "solr" ]
stackoverflow_0000572599_pysolr_python_solr.txt
Q: Drawing a chart with proportional X axis in Python Is there an easy way to draw a date/value chart in Python, if the "dates" axis had non-equidistant values? For example, given these: 2009-02-01: 10 2009-02-02: 13 2009-02-07: 25 2009-03-01: 80 I'd like the chart to show that between the 2nd and 3nd value there's...
Drawing a chart with proportional X axis in Python
Is there an easy way to draw a date/value chart in Python, if the "dates" axis had non-equidistant values? For example, given these: 2009-02-01: 10 2009-02-02: 13 2009-02-07: 25 2009-03-01: 80 I'd like the chart to show that between the 2nd and 3nd value there's a longer gap than between the 1st and the 2nd. I tried ...
[ "you should be able to do this with matplotlib barchart. you can use xticks to give the x-axis date values, and the 'left' sizes don't have to be homogeneous. see the documentation for barchart for a full list of parameters.\n", "If it is enough for you to get a PNG with the chart, you can use Google Chart API ...
[ 2, 1 ]
[]
[]
[ "charts", "python" ]
stackoverflow_0000572808_charts_python.txt
Q: Python C-API Object Allocation I want to use the new and delete operators for creating and destroying my objects. The problem is python seems to break it into several stages. tp_new, tp_init and tp_alloc for creation and tp_del, tp_free and tp_dealloc for destruction. However c++ just has new which allocates and f...
Python C-API Object Allocation
I want to use the new and delete operators for creating and destroying my objects. The problem is python seems to break it into several stages. tp_new, tp_init and tp_alloc for creation and tp_del, tp_free and tp_dealloc for destruction. However c++ just has new which allocates and fully constructs the object and delet...
[ "The documentation for these is at http://docs.python.org/3.0/c-api/typeobj.html and \nhttp://docs.python.org/3.0/extending/newtypes.html describes how to make your own type.\ntp_alloc does the low-level memory allocation for the instance. This is equivalent to malloc(), plus initialize the refcnt to 1. Python has ...
[ 11, 0 ]
[]
[]
[ "c", "c++", "python", "python_3.x", "python_c_api" ]
stackoverflow_0000573275_c_c++_python_python_3.x_python_c_api.txt
Q: CPython internal structures GAE has various limitations, one of which is size of biggest allocatable block of memory amounting to 1Mb (now 10 times more, but that doesn't change the question). The limitation means that one cannot put more then some number of items in list() as CPython would try to allocate contigu...
CPython internal structures
GAE has various limitations, one of which is size of biggest allocatable block of memory amounting to 1Mb (now 10 times more, but that doesn't change the question). The limitation means that one cannot put more then some number of items in list() as CPython would try to allocate contiguous memory block for element poin...
[ "On a 32-bit system, each of the 8000000 lists you create will allocate 20 bytes for the list object itself, plus 16 bytes for a vector of list elements. So you are trying to allocate at least (20+16) * 8000000 = 20168000000 bytes, about 20 GB. And that's in the best case, if the system malloc only allocates exactl...
[ 8, 0, 0, 0 ]
[]
[]
[ "cpython", "data_structures", "google_app_engine", "internals", "python" ]
stackoverflow_0000572780_cpython_data_structures_google_app_engine_internals_python.txt
Q: Any way to create a NumPy matrix with C API? I read the documentation on NumPy C API I could find, but still wasn't able to find out whether there is a possibility to construct a matrix object with C API — not a two-dimensional array. The function is intended for work with math matrices, and I don't want strange r...
Any way to create a NumPy matrix with C API?
I read the documentation on NumPy C API I could find, but still wasn't able to find out whether there is a possibility to construct a matrix object with C API — not a two-dimensional array. The function is intended for work with math matrices, and I don't want strange results if the user calls matrix multiplication for...
[ "You can call any python callable with the PyObject_Call* functions.\nPyObject *numpy = PyImport_ImportModule(\"numpy\");\nPyObject *numpy_matrix = PyObject_GetAttrString(numpy, \"matrix\");\nPyObject *my_matrix = PyObject_CallFunction(numpy_matrix, \"(s)\", \"0 0; 0 0\");\n\nThis will create a matrix my_matrix of ...
[ 6, 3 ]
[]
[]
[ "numpy", "python", "python_c_api" ]
stackoverflow_0000573487_numpy_python_python_c_api.txt
Q: Using wget in python (Error Code Help me) Heres my code. import os, sys if len(sys.argv) != 2: sys.exit(1) h = os.popen("wget -r %s") % sys.argv[1] fil = open("links.txt","w") dir = os.listdir("%s") % sys.argv[1] for file in dir: print file.replace("@","?") fil.write("%s/"+file.replace("@","?")) ...
Using wget in python (Error Code Help me)
Heres my code. import os, sys if len(sys.argv) != 2: sys.exit(1) h = os.popen("wget -r %s") % sys.argv[1] fil = open("links.txt","w") dir = os.listdir("%s") % sys.argv[1] for file in dir: print file.replace("@","?") fil.write("%s/"+file.replace("@","?")) % sys.argv[1] fil.write("\n") h.close() r...
[ "\nh = os.popen(\"wget -r %s\" % sys.argv[1])\nuse the subprocess module, os.popen is obsolete\npython has urllib, you can consider using that to have pure python code\nthere is pycurl\n\n", "I think you want:\nh = os.popen(\"wget -r %s\" % sys.argv[1])\n\n", "You're putting the % operator in the wrong place: y...
[ 9, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000573914_python.txt
Q: Has anyone used SciPy with IronPython? I've been able to use the standard Python modules from IronPython, but I haven't gotten SciPy to work yet. Has anyone been able to use SciPy from IronPython? What did you have to do to make it work? Update: See Numerical computing in IronPython with Ironclad Update: Microso...
Has anyone used SciPy with IronPython?
I've been able to use the standard Python modules from IronPython, but I haven't gotten SciPy to work yet. Has anyone been able to use SciPy from IronPython? What did you have to do to make it work? Update: See Numerical computing in IronPython with Ironclad Update: Microsoft is partnering with Enthought to make SciP...
[ "Some of my workmates are working on Ironclad, a project that will make extension modules for CPython work in IronPython. It's still in development, but parts of numpy, scipy and some other modules already work. You should try it out to see whether the parts of scipy you need are supported. \nIt's an open-source pr...
[ 12, 8 ]
[]
[]
[ "ironpython", "python", "python.net", "scipy" ]
stackoverflow_0000574604_ironpython_python_python.net_scipy.txt
Q: Include html part in a mail with python libgmail I've a question about its usage: i need to send an html formatted mail. I prepare my message with ga = libgmail.GmailAccount(USERNAME,PASSWORD) msg = MIMEMultipart('alternative') msg.attach(part1) msg.attach(part2) ... ga.sendMessage(msg.as_string()) This way doe...
Include html part in a mail with python libgmail
I've a question about its usage: i need to send an html formatted mail. I prepare my message with ga = libgmail.GmailAccount(USERNAME,PASSWORD) msg = MIMEMultipart('alternative') msg.attach(part1) msg.attach(part2) ... ga.sendMessage(msg.as_string()) This way doesn't works, it seems can't send msg with sendMessage m...
[ "If you refer to libgmail from sourceforge, you need to compose your messages with the email module.\nGenerate the HTML message as a MIME document, and include it as a part of a multipart MIME message. When you have a fully constructed multipart MIME, pass it along as a string to the libgmail constructor, using to...
[ 1 ]
[]
[]
[ "gmail", "html", "libgmail", "mime", "python" ]
stackoverflow_0000574861_gmail_html_libgmail_mime_python.txt
Q: Docs for the internals of CPython Implementation I am currently in the process of making an embedded system port of the CPython 3.0 Python interpreter and I'm particularly interested in any references or documentation that provides details about the design and structure of code for Release 3.0 or even about any of...
Docs for the internals of CPython Implementation
I am currently in the process of making an embedded system port of the CPython 3.0 Python interpreter and I'm particularly interested in any references or documentation that provides details about the design and structure of code for Release 3.0 or even about any of the 2.x releases. One useful document I have found so...
[ "There's the documentation for the C API, which is essentially the API for the internals of Python. It won't cover porting details, though. The code itself is fairly well documented. You might try reading in and around the area you'll need to modify.\n", "Most of the documentation is stored in the minds of var...
[ 8, 1 ]
[]
[]
[ "cpython", "python" ]
stackoverflow_0000574004_cpython_python.txt
Q: Django and Sqlite Concurrency issue I've done a bit of reading related to the concurrency issues with sqlite, but I don't see how they'd apply to Django since it's inherently single threaded. I'm not using any multiprocess modules either. I have absolutely no experience with concurrent programming either, so if so...
Django and Sqlite Concurrency issue
I've done a bit of reading related to the concurrency issues with sqlite, but I don't see how they'd apply to Django since it's inherently single threaded. I'm not using any multiprocess modules either. I have absolutely no experience with concurrent programming either, so if someone can identify WHY the following code...
[ "In the following method function\ndef add_active_residents(self):\n ssa_res = SSA_Resident.objects.select_related(depth=1).filter(ssa=self.ssa, active=True)\n for r in ssa_res:\n self.residents.add(r.resident) # Fails Here\n self.save()\n\nWhy is there a select_related? You only really need the FK...
[ 4, 2, 2, 1 ]
[]
[]
[ "concurrency", "django", "python", "sqlite" ]
stackoverflow_0000572009_concurrency_django_python_sqlite.txt
Q: How does python close files that have been gc'ed? I had always assumed that a file would leak if it was opened without being closed, but I just verified that if I enter the following lines of code, the file will close: >>> f = open('somefile.txt') >>> del f Just out of sheer curiosity, how does this work? I noti...
How does python close files that have been gc'ed?
I had always assumed that a file would leak if it was opened without being closed, but I just verified that if I enter the following lines of code, the file will close: >>> f = open('somefile.txt') >>> del f Just out of sheer curiosity, how does this work? I notice that file doesn't include a __del__ method.
[ "In CPython, at least, files are closed when the file object is deallocated. See the file_dealloc function in Objects/fileobject.c in the CPython source. Dealloc methods are sort-of like __del__ for C types, except without some of the problems inherent to __del__.\n", "Hence the with statement.\nFor Python 2.5, u...
[ 20, 4, 2, 0 ]
[]
[]
[ "del", "file", "garbage_collection", "python" ]
stackoverflow_0000575278_del_file_garbage_collection_python.txt
Q: How can you extract all 6 letter Latin words to a list? I need to have all 6 letter Latin words in a list. I would also like to have words which follow the pattern Xyzzyx in a list. I have used little Python. A: Regular expressions are your friend, my friend! Is this homework? Here's an example that's close to...
How can you extract all 6 letter Latin words to a list?
I need to have all 6 letter Latin words in a list. I would also like to have words which follow the pattern Xyzzyx in a list. I have used little Python.
[ "Regular expressions are your friend, my friend! Is this homework?\nHere's an example that's close to what you want:\negrep \"^\\w{6}$\" /usr/share/dict/words | egrep \"(.)(.)(.)\\3\\2\\1\"\n\nI'll leave it as an exercise for the reader to create a latin word list and deal with the uppercase X in the second regex,...
[ 5, 0 ]
[]
[]
[ "data_mining", "python", "regex" ]
stackoverflow_0000574952_data_mining_python_regex.txt
Q: Sorting dictionary keys in python I have a dict where each key references an int value. What's the best way to sort the keys into a list depending on the values? A: I like this one: sorted(d, key=d.get) A: >>> mydict = {'a':1,'b':3,'c':2} >>> sorted(mydict, key=lambda key: mydict[key]) ['a', 'c', 'b'] A: my_...
Sorting dictionary keys in python
I have a dict where each key references an int value. What's the best way to sort the keys into a list depending on the values?
[ "I like this one:\nsorted(d, key=d.get)\n\n", ">>> mydict = {'a':1,'b':3,'c':2}\n>>> sorted(mydict, key=lambda key: mydict[key])\n['a', 'c', 'b']\n\n", "my_list = sorted(dict.items(), key=lambda x: x[1])\n\n", "[v[0] for v in sorted(foo.items(), key=lambda(k,v): (v,k))]\n\n" ]
[ 357, 107, 17, 4 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0000575819_python_sorting.txt
Q: Succesive calls to cProfile/pstats no updating properly I'm trying to make successive calls of some profiler code however on the second call to the function the update time of the profile file changes but the actual profiler stats stay the same. This isn't the code I'm running but it's as simplified an example I c...
Succesive calls to cProfile/pstats no updating properly
I'm trying to make successive calls of some profiler code however on the second call to the function the update time of the profile file changes but the actual profiler stats stay the same. This isn't the code I'm running but it's as simplified an example I can come up with that shows the same behaviour. On running, th...
[ "Calling profiler.dump_stats (implemented in cProfile.py) calls profiler.create_stats, which in turns calls profiler.disable().\nYou need to call profiler.enable() to make it work again. No, this is not documented.\nThe following seems to do what you want. Note that I got rid of the intermediate data file since pst...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0000575325_python.txt
Q: Is there a special trick to downloading a zip file and writing it to disk with Python? I am FTPing a zip file from a remote FTP site using Python's ftplib. I then attempt to write it to disk. The file write works, however most attempts to open the zip using WinZip or WinRar fail; both apps claim the file is corrup...
Is there a special trick to downloading a zip file and writing it to disk with Python?
I am FTPing a zip file from a remote FTP site using Python's ftplib. I then attempt to write it to disk. The file write works, however most attempts to open the zip using WinZip or WinRar fail; both apps claim the file is corrupted. Oddly however, when right clicking and attempting to extract the file using WinRar, the...
[ "Pass file.write directly inside the retrbinary function instead of passing appender. This will work and it will also not use that much RAM when you are downloading a big file. \nIf you'd like the data stored inside a variable though, you can also have a variable named: \nblocks = []\n\nThen pass to retrbinary ins...
[ 2, 1 ]
[]
[]
[ "ftp", "ftplib", "python" ]
stackoverflow_0000576238_ftp_ftplib_python.txt
Q: Django Project structure, recommended structure to share an extended auth "User" model across apps? I'm wondering what the common project/application structure is when the user model extended/sub-classed and this Resulting User model is shared and used across multiple apps. I'd like to reference the same user mo...
Django Project structure, recommended structure to share an extended auth "User" model across apps?
I'm wondering what the common project/application structure is when the user model extended/sub-classed and this Resulting User model is shared and used across multiple apps. I'd like to reference the same user model in multiple apps. I haven't built the login interface yet, so I'm not sure how it should fit together...
[ "Why are you extending User? Please clarify.\nIf you're adding more information about the users, you don't need to roll your own user and auth system. Django's version of that is quite solid. The user management is located in django.contrib.auth.\nIf you need to customize the information stored with users, first ...
[ 7, 3, 2 ]
[]
[]
[ "django", "django_models", "django_project_architect", "python" ]
stackoverflow_0000576345_django_django_models_django_project_architect_python.txt
Q: How to convert rational and decimal number strings to floats in python? How can I convert strings which can denote decimal or rational numbers to floats >>> ["0.1234", "1/2"] ['0.1234', '1/2'] I'd want [0.1234, 0.5]. eval is what I was thinking but no luck: >>> eval("1/2") 0 A: I'd parse the string if conversio...
How to convert rational and decimal number strings to floats in python?
How can I convert strings which can denote decimal or rational numbers to floats >>> ["0.1234", "1/2"] ['0.1234', '1/2'] I'd want [0.1234, 0.5]. eval is what I was thinking but no luck: >>> eval("1/2") 0
[ "I'd parse the string if conversion fails:\n>>> def convert(s):\n try:\n return float(s)\n except ValueError:\n num, denom = s.split('/')\n return float(num) / float(denom)\n...\n\n>>> convert(\"0.1234\")\n0.1234\n\n>>> convert(\"1/2\")\n0.5\n\nGenerally using eval is a bad idea, since it...
[ 19, 7, 7, 4, 3, 2, 1, 1, 0, 0 ]
[]
[]
[ "python", "rational_numbers" ]
stackoverflow_0000575925_python_rational_numbers.txt
Q: Are Python threads buggy? A reliable coder friend told me that Python's current multi-threading implementation is seriously buggy - enough to avoid using altogether. What can said about this rumor? A: Python threads are good for concurrent I/O programming. Threads are swapped out of the CPU as soon as they bloc...
Are Python threads buggy?
A reliable coder friend told me that Python's current multi-threading implementation is seriously buggy - enough to avoid using altogether. What can said about this rumor?
[ "Python threads are good for concurrent I/O programming. Threads are swapped out of the CPU as soon as they block waiting for input from file, network, etc. This allows other Python threads to use the CPU while others wait. This would allow you to write a multi-threaded web server or web crawler, for example.\nHowe...
[ 58, 16, 9, 5, 2 ]
[ "I've used it in several applications and have never had nor heard of threading being anything other than 100% reliable, as long as you know its limits. You can't spawn 1000 threads at the same time and expect your program to run properly on Windows, however you can easily write a worker pool and just feed it 1000...
[ -2 ]
[ "multithreading", "python" ]
stackoverflow_0000034020_multithreading_python.txt
Q: How to exit a module before it has finished parsing? I have a module that imports a module, but in some cases the module being imported may not exist. After the module is imported there is a class inherits from a class the imported module. If I was to catch the ImportError exception in the case the module doesn't ...
How to exit a module before it has finished parsing?
I have a module that imports a module, but in some cases the module being imported may not exist. After the module is imported there is a class inherits from a class the imported module. If I was to catch the ImportError exception in the case the module doesn't exist, how can I stop Python from parsing the rest of the ...
[ "try: supports an else: clause\ntry:\n from skynet import SkyNet\n\nexcept ImportError:\n class SelfAwareSkyNet():\n pass\n\nelse:\n class SelfAwareSkyNet(SkyNet):\n pass\n\n", "You could use:\ntry:\n from skynet import SkyNet\n inherit_from = SkyNet\nexcept ImportError:\n inherit_fro...
[ 7, 2 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0000577119_import_module_python.txt
Q: How do I design sms service? I want to design a website that can send and receive sms. How should I approach the problem ? What are the resources available ? I know php,python what else do I need or are the better options available? How can experiment using my pc only?[somthing like localhost] What are some good ...
How do I design sms service?
I want to design a website that can send and receive sms. How should I approach the problem ? What are the resources available ? I know php,python what else do I need or are the better options available? How can experiment using my pc only?[somthing like localhost] What are some good hosting services for this? [edit t...
[ "You can take a look at Kannel. It's so simple to create SMS services using it. Just define a keyword, then put in the URL to which the incoming SMS request will be routed (you'll get the info such as mobile number and SMS text in query string parameters), then whatever output your web script generates (you can use...
[ 3, 2, 2, 0, 0 ]
[]
[]
[ "bulksms", "mobile_phones", "php", "python", "sms" ]
stackoverflow_0000576940_bulksms_mobile_phones_php_python_sms.txt
Q: gtk TextView widget doesn't update during function I'm new to GUI programming with python and gtk, so this is a bit of a beginners question. I have a function that is called when a button is pressed which does various tasks, and a TextView widget which I write to after each task is completed. The problem is that ...
gtk TextView widget doesn't update during function
I'm new to GUI programming with python and gtk, so this is a bit of a beginners question. I have a function that is called when a button is pressed which does various tasks, and a TextView widget which I write to after each task is completed. The problem is that the TextView widget doesn't update until the entire func...
[ "After each update to the TextView call\nwhile gtk.events_pending():\n gtk.main_iteration()\n\nYou can do your update through a custom function:\ndef my_insert(self, widget, report, text):\n\n report.insert_at_cursor(text)\n while gtk.events_pending():\n gtk.main_iteration()\n\nFrom the PyGTK FAQ:\nHow can I ...
[ 4 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0000577302_gtk_pygtk_python.txt