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:
Domain Registration API
At my company I have to do a lot of domain registration.
Is there a way for me to write something in a common web-language e.g. Ruby/Python/PHP that would allow me to buy a domain name from my own custom web-interface? In essence I'm looking for an API that would allow me to register domai... | Domain Registration API | At my company I have to do a lot of domain registration.
Is there a way for me to write something in a common web-language e.g. Ruby/Python/PHP that would allow me to buy a domain name from my own custom web-interface? In essence I'm looking for an API that would allow me to register domains.
Any ideas?
| [
"If I understand correctly, you want to create a web interface to register domains from a variety of domain registrars?\nMost of these companies have published APIs or web services to allow just this use case, so you'll need to check with each one you deal with and find out what they offer, and how to use them. Man... | [
4,
3
] | [] | [] | [
"dns",
"php",
"python",
"ruby"
] | stackoverflow_0005149664_dns_php_python_ruby.txt |
Q:
To compare 2 excel files using python
I have a excel file with following fields
Software_name , Version and Count.
This file is a inventory of all softwares installed in the network of an organization which was generated using LANdesk.
I have another excel file which is an purchase inventory of these softwares... | To compare 2 excel files using python | I have a excel file with following fields
Software_name , Version and Count.
This file is a inventory of all softwares installed in the network of an organization which was generated using LANdesk.
I have another excel file which is an purchase inventory of these softwares which is generated manually.
I need to com... | [
"There are several libraries to manipulate .xls files.\nXLRD allows you to extract data from Excel spreadsheet files. So you can compare two files easily. (read)\nXLWT allows you to create some Excel files. (write)\nXLUtils requires both of the xlrd and xlwt packages. So, you can read & write easily thanks to this ... | [
1,
1
] | [] | [] | [
"excel",
"python"
] | stackoverflow_0005370341_excel_python.txt |
Q:
Python: Get max pair in a list of pairs with min y
How i get max pair in a list of pairs with min y?
I got this list:
L =[[1,3],[2,5],[-4,0],[2,1],[0,9]]
With max(L) i get [2,5], but i want [2,1].
A:
max(L, key=lambda item: (item[0], -item[1]))
Output:
[2, 1]
A:
Your request is kind of cryptic, but I think t... | Python: Get max pair in a list of pairs with min y | How i get max pair in a list of pairs with min y?
I got this list:
L =[[1,3],[2,5],[-4,0],[2,1],[0,9]]
With max(L) i get [2,5], but i want [2,1].
| [
"max(L, key=lambda item: (item[0], -item[1]))\n\nOutput:\n[2, 1]\n\n",
"Your request is kind of cryptic, but I think this is what you want:\nx, y = zip(*L)\nmaxPairs = [L[i] for i,a in enumerate(x) if a == max(x)]\nreturnPair = sorted(maxPairs)[0]\n\n",
"import operator\n\nget_y= operator.itemgetter(1)\nmin(L, ... | [
18,
1,
0
] | [] | [] | [
"list",
"max",
"min",
"python"
] | stackoverflow_0005118249_list_max_min_python.txt |
Q:
Encoding a file
This one is a little tricky to explain. I would like to create a file, lets say, a .test file. Now, this is ridiculously easy to create and write, but I would like to encode the information so I could only interpret the information with the Test Program.
So, this Test Program would be able to creat... | Encoding a file | This one is a little tricky to explain. I would like to create a file, lets say, a .test file. Now, this is ridiculously easy to create and write, but I would like to encode the information so I could only interpret the information with the Test Program.
So, this Test Program would be able to create and read the .test ... | [
"If you're really worried about the security of the file, you could encrypt its content. There are several third party libraries such as ezPyCrypto and pyDes that make it simple to implement.\n",
"If you want a really simply version, use python's base64 module. The file won't be recognizable opening in notepad an... | [
2,
1,
0
] | [] | [] | [
"encoding",
"python",
"wxpython"
] | stackoverflow_0005371632_encoding_python_wxpython.txt |
Q:
Distributing Programs Written in Python
Possible Duplicate:
Distributing Python programs
I have several source codes for some GUI programs I made in Python. I'd like to distribute them. However, I'd like to make it as easy as possible for the end user to get the program up and running. What are the common way's ... | Distributing Programs Written in Python |
Possible Duplicate:
Distributing Python programs
I have several source codes for some GUI programs I made in Python. I'd like to distribute them. However, I'd like to make it as easy as possible for the end user to get the program up and running. What are the common way's of going about this problem?
This is in ref... | [
"All noteworthy linux distributions and Mac OS come shipped with some version of Python. Windows don't have Python installed by default, so you must install it separately in order to run a Python module. Of course the installed Python version must be the same as your program (version 2 or 3).\nThe easiest way to di... | [
22,
4
] | [] | [] | [
"python"
] | stackoverflow_0004190635_python.txt |
Q:
How to get an object's fields?
I'm making a function to convert a model object into a dictionary (and all foreignkeys into more dictionaries, recursively). I learned from a friend that I can get a model's fields by looking at obj._meta.fields, but I can't find documentation for this anywhere.
How do I get a model'... | How to get an object's fields? | I'm making a function to convert a model object into a dictionary (and all foreignkeys into more dictionaries, recursively). I learned from a friend that I can get a model's fields by looking at obj._meta.fields, but I can't find documentation for this anywhere.
How do I get a model's fields? How can I interpret what o... | [
"This seemed fairly interesting, so I went looking through the django.forms source, looking specifically for the ModelForm implementation. I figured a ModelForm would be quite good at introspecting a given instance, and it just so happens that there is a handy function available that may help you on your way.\n>>> ... | [
10,
5
] | [] | [] | [
"database",
"django",
"orm",
"python"
] | stackoverflow_0005371531_database_django_orm_python.txt |
Q:
cython setup.py gives .o instead of .dll
I am a newbie to cython, so pardon me if I am missing something obvious here. I am trying to build c extensions to be used in python for enhanced performance. I have fc.py module with a bunch of function and trying to generate a .dll through cython using dsutils and running... | cython setup.py gives .o instead of .dll | I am a newbie to cython, so pardon me if I am missing something obvious here. I am trying to build c extensions to be used in python for enhanced performance. I have fc.py module with a bunch of function and trying to generate a .dll through cython using dsutils and running on win64:
c:\python26\python c:\cythontest\se... | [
"Finally, I was able to build extension for win64. Apparently, if you have VC 2010 express, you can tweak the disuilts to use msvc9compiler for compiling the module. The details can be found here. Many thanks to the guys at nukeitdotorg for putting up this, and also to J.F. Sebastian for his tips.\n",
"Did you tr... | [
1,
0
] | [] | [] | [
"cython",
"dll",
"python",
"win64"
] | stackoverflow_0005293423_cython_dll_python_win64.txt |
Q:
how to interact with a `select` input with PAMIE?
How do I interact with a select box using PAMIE?
A:
It is ie.listBoxSelect, using the source code as documentation.
| how to interact with a `select` input with PAMIE? | How do I interact with a select box using PAMIE?
| [
"It is ie.listBoxSelect, using the source code as documentation.\n"
] | [
0
] | [] | [] | [
"automation",
"internet_explorer",
"pamie",
"python",
"windows"
] | stackoverflow_0005371808_automation_internet_explorer_pamie_python_windows.txt |
Q:
How to send Gmail email with multiple CC:'s
I am looking for a quick example on how to send Gmail emails with multiple CC:'s. Could anyone suggest an example snippet?
A:
If you can use a library, I highly suggest http://libgmail.sourceforge.net/, I have used briefly in the past, and it is very easy to use. You... | How to send Gmail email with multiple CC:'s | I am looking for a quick example on how to send Gmail emails with multiple CC:'s. Could anyone suggest an example snippet?
| [
"If you can use a library, I highly suggest http://libgmail.sourceforge.net/, I have used briefly in the past, and it is very easy to use. You must enable IMAP/POP3 in your gmail account in order to use this. \nAs for a code snippet (I haven't had a chance to try this, I will edit this if I can):\nimport smtplib\nf... | [
1,
1
] | [] | [] | [
"email_headers",
"python"
] | stackoverflow_0005304835_email_headers_python.txt |
Q:
Why is my school's CAS server not redirecting to my site after authenticating?
I'm trying to make a website that only University of Waterloo students can use. It uses CAS for authentication. I started using the django_cas package. Followed the steps pretty much dead on. Here are the things I tested for:
redirected... | Why is my school's CAS server not redirecting to my site after authenticating? | I'm trying to make a website that only University of Waterloo students can use. It uses CAS for authentication. I started using the django_cas package. Followed the steps pretty much dead on. Here are the things I tested for:
redirected to CAS login page - pass
verify user on the CAS server - pass
redirect back to web... | [
"You didn't really provide enough information for someone to give you a meaningful answer.\nTry the following:\n\nMake sure that you properly set CAS_SERVER_URL as per the django_cas documentation.\nTalk to your university to make sure that the CAS server is allowed to redirect to your application. Since some infor... | [
0
] | [] | [] | [
"authentication",
"cas",
"django",
"python"
] | stackoverflow_0005372010_authentication_cas_django_python.txt |
Q:
Python: check if value is in a list no matter the CaSE
I want to check if a value is in a list, no matter what the case of the letters are, and I need to do it efficiently.
This is what I have:
if val in list:
But I want it to ignore case
A:
check = "asdf"
checkLower = check.lower()
print any(checkLower == val... | Python: check if value is in a list no matter the CaSE | I want to check if a value is in a list, no matter what the case of the letters are, and I need to do it efficiently.
This is what I have:
if val in list:
But I want it to ignore case
| [
"check = \"asdf\"\ncheckLower = check.lower()\n\nprint any(checkLower == val.lower() for val in [\"qwert\", \"AsDf\"])\n\n# prints true\n\nUsing the any() function. This method is nice because you aren't recreating the list to have lowercase, it is iterating over the list, so once it finds a true value, it stops it... | [
16,
4,
2,
0,
0
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0005371935_loops_python.txt |
Q:
python: force non-relative import?
I wanted to make a module called utils/django.py in my project. On the top I have the line:
from django.db import models
However, it tries to import from itself, and that causes an error. I know I can force a relative import with a prepended .:
from .django.db import models
is ... | python: force non-relative import? | I wanted to make a module called utils/django.py in my project. On the top I have the line:
from django.db import models
However, it tries to import from itself, and that causes an error. I know I can force a relative import with a prepended .:
from .django.db import models
is there any way to force a non-relative im... | [
"No. You need to explicitly enable absolute imports.\nfrom __future__ import absolute_import\n\n"
] | [
21
] | [] | [] | [
"import",
"importerror",
"module",
"path",
"python"
] | stackoverflow_0005372590_import_importerror_module_path_python.txt |
Q:
python: reportlab, how to remove black borders from image
I am trying to generate a pdf file, using python reportlab, but is seems image is displayed with strange black border in pdf.
Here is the code:
# Standalone script to generate pdf lessons
from reportlab.pdfgen import canvas
def hello(c):
c.drawImage(".... | python: reportlab, how to remove black borders from image | I am trying to generate a pdf file, using python reportlab, but is seems image is displayed with strange black border in pdf.
Here is the code:
# Standalone script to generate pdf lessons
from reportlab.pdfgen import canvas
def hello(c):
c.drawImage("./media/files/1.png", 0, 600, 350, 350)
c = canvas.Canvas("hel... | [
"The problem isn't with a border, rather your chessboard has transparent pixels on the right and bottom sides, and reportlab isn't recognizing the alpha channel and is painting the transparent section as black:\n\nUsing mask='auto' tells drawImage to use the alpha channel in your PNG, so the background shows throug... | [
3
] | [] | [] | [
"python",
"reportlab"
] | stackoverflow_0005370552_python_reportlab.txt |
Q:
Python CGEventTap Bus Error
I get a bus error whenever I run this Python CGEventTap code:
def callback(ent):
loc = CGEventGetLocation(ent)
print loc
tap = CGEventTapCreate(
kCGSessionEventTap,
kCGHeadInsertEventTap,
kCGEventTapOptionDefault,
CGEventMaskBit(kCGEventMouseMoved),
callb... | Python CGEventTap Bus Error | I get a bus error whenever I run this Python CGEventTap code:
def callback(ent):
loc = CGEventGetLocation(ent)
print loc
tap = CGEventTapCreate(
kCGSessionEventTap,
kCGHeadInsertEventTap,
kCGEventTapOptionDefault,
CGEventMaskBit(kCGEventMouseMoved),
callback(CGEventRef) )
loop = CFMachP... | [
"\nI have tried all of the following:... Which of these do I need and not need? And what do you mean by linking? – Teak\n\nReplying to your comment with an answer because it won't fit in a comment. Sorry.\nThe situation is perhaps a little convoluted. PyObjC has a whole bunch of information (metadata and some helpe... | [
1
] | [] | [] | [
"events",
"macos",
"objective_c",
"pyobjc",
"python"
] | stackoverflow_0004996085_events_macos_objective_c_pyobjc_python.txt |
Q:
GBase Snippets Feed, how do I extract the URL?
In this example http://code.google.com/apis/base/docs/1.0/pythondevguide.html (search for entry.title.text) it gives entry.title.text as the only example for a Snippets feed attribute. What do I put there to get the URL? I was able to find entry.link but it only gives... | GBase Snippets Feed, how do I extract the URL? | In this example http://code.google.com/apis/base/docs/1.0/pythondevguide.html (search for entry.title.text) it gives entry.title.text as the only example for a Snippets feed attribute. What do I put there to get the URL? I was able to find entry.link but it only gives me [<atom.Link object at 0x020E6E90>, <atom.Link ob... | [
"You can get the URL from the link's href attribute:\nfor link in entry.link:\n print link.href\n\n"
] | [
1
] | [] | [] | [
"gdata",
"gdata_api",
"python"
] | stackoverflow_0005369009_gdata_gdata_api_python.txt |
Q:
How to avoiding multiple updates in a list of dictionaries in Python?
I have a list of 5 dictionaries, and when I am updating dictionary[0], it also simultaneously updates dictionary[4]. The strange thing is that it is not systematic, and the dictionaries seem independent to me, although they share the same conten... | How to avoiding multiple updates in a list of dictionaries in Python? | I have a list of 5 dictionaries, and when I am updating dictionary[0], it also simultaneously updates dictionary[4]. The strange thing is that it is not systematic, and the dictionaries seem independent to me, although they share the same content.
Program 1 shows the problem as I encountered it.
Program 2 shows a way t... | [
"The values in both dictionaries are the same because python only stores references to objects. When you assign a list to a value in two different dictionaries, what's actually stored in those dictionaries is a reference to the same list. So you only actually create one list and just use the reference in both dicti... | [
1,
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0005372007_dictionary_python.txt |
Q:
String Concatenation appends Junk Characters with ctypes
I am appending "00000000" to a string and it works fine for the first time. However, when run second time "Junk Characters" are appended instead of "000000". This is the sample code how I am doing it in the actual program.
File one.py
# File One.py
from two ... | String Concatenation appends Junk Characters with ctypes | I am appending "00000000" to a string and it works fine for the first time. However, when run second time "Junk Characters" are appended instead of "000000". This is the sample code how I am doing it in the actual program.
File one.py
# File One.py
from two import *
def One():
while(1):
key = Two()
... | [
"create_string_buffer can be initialized with a string or a length. If initialized with a string s, it allocates space for len(s)+1 chars, so that the terminating null can be appended. But if initialized with an integer value, create_string_buffer assumes that since you are the human, you must know what you are d... | [
1
] | [] | [] | [
"ctypes",
"python",
"string",
"string_concatenation"
] | stackoverflow_0005369800_ctypes_python_string_string_concatenation.txt |
Q:
How to manually install Python modules in CentOS 5.5?
I have a specific Python module that I wrote that I want to add to my CentOS server. I'm not sure where to add it though...
In Windows, its pretty easy, just drop it in C:\Python2.X\Lib or site-packages and Python finds it. I'm not sure how to accomplish the sa... | How to manually install Python modules in CentOS 5.5? | I have a specific Python module that I wrote that I want to add to my CentOS server. I'm not sure where to add it though...
In Windows, its pretty easy, just drop it in C:\Python2.X\Lib or site-packages and Python finds it. I'm not sure how to accomplish the same thing in Linux.
Do I need to use yum somehow? Or do I si... | [
"The clean option: write a setup.py, then run that.\nThe quick option: drop it in /usr/local/lib/python2.X/site-packages.\n",
"If you want to install the package globally, use this command:\n$ python -c \"import site; print site.getsitepackages()\" # Python >= 2.7\n\nIf you're fine with per-user installation, use... | [
4,
2
] | [] | [] | [
"centos",
"linux",
"python"
] | stackoverflow_0005372757_centos_linux_python.txt |
Q:
Issue with making object callable in python
I wrote code like this
>>> class a(object):
def __init__(self):
self.__call__ = lambda x:x
>>> b = a()
I expected that object of class a should be callable object but eventually it is not.
>>> b()
Traceback (most recent call last):
File "<pyshe... | Issue with making object callable in python | I wrote code like this
>>> class a(object):
def __init__(self):
self.__call__ = lambda x:x
>>> b = a()
I expected that object of class a should be callable object but eventually it is not.
>>> b()
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
b()
TypeError... | [
"Special methods are looked up on the type (e.g., class) of the object being operated on, not on the specific instance. Think about it: otherwise, if a class defines __call__ for example, when the class is called that __call__ should get called... what a disaster! But fortunately the special method is instead look... | [
21,
19,
2
] | [] | [] | [
"python"
] | stackoverflow_0001705928_python.txt |
Q:
Python module for binary plist
Is there any Python project/module working on a binary plist writer? I need one for a REST implementation I'm doing. I would like the server to send a HTTP REsponse containing a binary plist instead of json, for example. The server is Apache with mod_python and django installed. Cons... | Python module for binary plist | Is there any Python project/module working on a binary plist writer? I need one for a REST implementation I'm doing. I would like the server to send a HTTP REsponse containing a binary plist instead of json, for example. The server is Apache with mod_python and django installed. Considering adding bplist format alongsi... | [
"I was afraid I might have to learn SWIG, implement this myself, or switch to another language for this hobby project that involves parsing binary plists -- but after a quick pip search plist, I found biplist.\n",
"What about plistlib in the default Python distribution? It is available for all platforms since Pyt... | [
14,
2
] | [] | [] | [
"iphone",
"plist",
"python"
] | stackoverflow_0003725268_iphone_plist_python.txt |
Q:
Python reading csv problem : extra whitespace
When I tried to parse a csv which was exported by MS SQL 2005 express edition's query, the string python gives me is totally unexpected. For example if the line in the csv file is :"
aaa,bbb,ccc,dddd", then when python parsed it as string, it becomes :" a a a a , b b b... | Python reading csv problem : extra whitespace | When I tried to parse a csv which was exported by MS SQL 2005 express edition's query, the string python gives me is totally unexpected. For example if the line in the csv file is :"
aaa,bbb,ccc,dddd", then when python parsed it as string, it becomes :" a a a a , b b b , c c c, d d d d" something like that.....What hap... | [
"Sounds to me like the output of the MS SQL 2005 query is a unicode file. The python csv module cannot handle unicode files, but there is some sample code in the documentation for the csv module describing how to work around the problem.\nAlternately, some text editors allow you to save a file with a different enco... | [
3,
-2
] | [
"Try to open the file in notepad and use the replace all function to replace ' ' with ''\n",
"Your file is most likely encoded with a 2byte character encoding - most likely utf-16 (but it culd be some other encoding.\nTo get the CSV proper reading it, you'd open it with a codec so that it is decoded as its read -... | [
-1,
-1
] | [
"csv",
"python"
] | stackoverflow_0005373195_csv_python.txt |
Q:
Python, how can I change value of a variable in the parent scope?
for example:
assginment statement will declare a new local variable.
foo = 'global'
def func1():
foo = 'func1'
def func2():
foo = 'local variable in func2'
use global declaration will use the foo in global:
def func2():
global f... | Python, how can I change value of a variable in the parent scope? | for example:
assginment statement will declare a new local variable.
foo = 'global'
def func1():
foo = 'func1'
def func2():
foo = 'local variable in func2'
use global declaration will use the foo in global:
def func2():
global foo
foo = 'global changed in func2' #changed the foo value in globa... | [
"In Python 3, I believe, you can use the nonlocal keyword to get permission to modify a variable in an enclosing non-global scope. In Python 2, you cannot reassign foo in an enclosing scope; instead, set foo equal to a mutable object like a list [] and then stick the value you want stored in the list:\ndef func1()... | [
17,
7
] | [] | [] | [
"global",
"python",
"python_nonlocal",
"scope"
] | stackoverflow_0005373377_global_python_python_nonlocal_scope.txt |
Q:
Django RegexField Letters and Numbers only
I need a regexfield in a django form to only accept letters and numbers, and nothing else. I've tried this, but it didn't work:
myfield = forms.RegexField(label=("My Label"), max_length=31, regex=r'[a-zA-Z0-9]',
error_message = ("This value must contain only lett... | Django RegexField Letters and Numbers only | I need a regexfield in a django form to only accept letters and numbers, and nothing else. I've tried this, but it didn't work:
myfield = forms.RegexField(label=("My Label"), max_length=31, regex=r'[a-zA-Z0-9]',
error_message = ("This value must contain only letters and numbers."),
I am not very good at using... | [
"regex=r'[a-zA-Z0-9]',\nIs one letter.\nDo you want more than one letter? Then use a repeat\nregex=r'[a-zA-Z0-9]+',\nThere are numerous tutorials on regular expressions. Please google for \"Regular Expression Tutorial.\" \n",
"regex=r'^[a-zA-Z0-9]+$',\n\nthis will only accept letters and numbers and will requir... | [
7,
5,
0
] | [] | [] | [
"django",
"python",
"regex"
] | stackoverflow_0003826822_django_python_regex.txt |
Q:
Strip path from filename
The code block below works but I would like to un-comment filename = os.path.basename(filename), when I do I am unable to specify an absolute path for filename because k.set_contents_from_filename will not longer reference the the actual location of the file, only file in the current worki... | Strip path from filename | The code block below works but I would like to un-comment filename = os.path.basename(filename), when I do I am unable to specify an absolute path for filename because k.set_contents_from_filename will not longer reference the the actual location of the file, only file in the current working directory will work if un-c... | [
"Unless I'm missing something completely, why can't you do something like this?\n# List files in directory and upload them to bucket\nfor filename in all_files:\n #skip all directory entries which are not a file\n if not os.path.isfile(filename):\n continue \n k = Key(bucket)\n k.key = os.pa... | [
7
] | [] | [] | [
"python",
"scripting"
] | stackoverflow_0005373499_python_scripting.txt |
Q:
Removing tab delimited spaces from a text file using for loop
For my python class, I am working on opening a .tsv file and taking 15 rows of data, broken down in 4 columns, and turning it into lists for each line. To do this, I must remove the tabs in between each column.
I've been advised to use a for loop and l... | Removing tab delimited spaces from a text file using for loop | For my python class, I am working on opening a .tsv file and taking 15 rows of data, broken down in 4 columns, and turning it into lists for each line. To do this, I must remove the tabs in between each column.
I've been advised to use a for loop and loop through each line. This makes sense but I can't figure out how... | [
"To read lines from a file, and split each line on the tab delimiter, you can do this:\nrows = []\nfor line in open('file.tsv', 'rb'):\n rows.append(line.strip().split('\\t'))\n\n",
"Properly, this should be done using the Python CSV module (as mentioned in another answer) as this will handle escaped separator... | [
4,
4,
3,
2
] | [] | [] | [
"loops",
"python",
"split",
"strip"
] | stackoverflow_0005372696_loops_python_split_strip.txt |
Q:
Using cx_Freeze (Python 2.7) on a Windows box OOTB
I have been plagued with this problem ever since I started with Python, I want to write a Python script, and then export it as an EXE that I can run on any Windows XP (and up) machine.
cx_Freeze covers all of this perfectly, the only problem is that it required Vi... | Using cx_Freeze (Python 2.7) on a Windows box OOTB | I have been plagued with this problem ever since I started with Python, I want to write a Python script, and then export it as an EXE that I can run on any Windows XP (and up) machine.
cx_Freeze covers all of this perfectly, the only problem is that it required Visual C++ Runtime to be installed on the client computer ... | [
"AFAIK if you have a Visual Studio licence, you have the right to bundle the appropriate msvcrXY.dll with your application. That will make it run without having to install the runtime files.\nIf you don't have a Visual Studio licence, I can think of two solutions:\nOne is to bundle the VS runtime installer with you... | [
0
] | [] | [] | [
"cx_freeze",
"msvcrt",
"python",
"windows",
"windows_xp"
] | stackoverflow_0005373558_cx_freeze_msvcrt_python_windows_windows_xp.txt |
Q:
Python Using Lambda Within a Function
I am trying to create a function called calc(f,a,b) where x is an equation with the variable f and I want to put this code within the function.
def calc(f, a, b):
limits = [a, b]
integral = odeint(lambda y, x : f, 0, limits)
return integral[1]
This ... | Python Using Lambda Within a Function | I am trying to create a function called calc(f,a,b) where x is an equation with the variable f and I want to put this code within the function.
def calc(f, a, b):
limits = [a, b]
integral = odeint(lambda y, x : f, 0, limits)
return integral[1]
This function gets the integral using the built ... | [
"If one were to rewrite the function calc as follows:\ndef calc(f, a, b):\n limits = [a, b]\n integral = odeint(lambda y, x: f(x), 0, limits)\n\n return integral[1][0]\n\nThen one may use this function thus:\n>>> calc(lambda x: x ** 2, 0, 1) # Integrate x ** 2 over the interval [0, 1] (expected answer: ... | [
2,
1,
0,
0
] | [] | [] | [
"python",
"scipy"
] | stackoverflow_0005372321_python_scipy.txt |
Q:
[Google App Engine]How to use filter()?
I'm getting started with Google App Engine, and I want to make something like twitter.
class User(db.Model):
account = db.StringProperty()
password = db.StringProperty()
name = db.StringProperty()
class Message(db.Model):
user = db.ReferenceProperty()
text = Strin... | [Google App Engine]How to use filter()? | I'm getting started with Google App Engine, and I want to make something like twitter.
class User(db.Model):
account = db.StringProperty()
password = db.StringProperty()
name = db.StringProperty()
class Message(db.Model):
user = db.ReferenceProperty()
text = StringProperty()
created = DateTimeProperty(auto... | [
"There is no GQL JOIN operation. Check out the article on modeling relationships for some other techniques you can use. Also, be sure to watch Building Scalable, Complex Apps on App Engine, it will be well worth your time.\nWith your current models, you would need to fetch the user entity (or build its key!) then... | [
6,
0
] | [] | [] | [
"filter",
"google_app_engine",
"python"
] | stackoverflow_0005373776_filter_google_app_engine_python.txt |
Q:
DJANGO translation - Translate models including "slugs" with django-datatrans
I'm reviewing django-datatrans to use it in parallel with django-localeurl.
What I want to do is translate slugs so that my translated object is accessed as follows:
www.mysite.com/fr/bonjour (in french)
www.mysite.com/en/hello (in e... | DJANGO translation - Translate models including "slugs" with django-datatrans | I'm reviewing django-datatrans to use it in parallel with django-localeurl.
What I want to do is translate slugs so that my translated object is accessed as follows:
www.mysite.com/fr/bonjour (in french)
www.mysite.com/en/hello (in english)
For this I need the 'get' to depend on the 'current language'.
To clarify ... | [
"The easiest solution in this case is querying the KeyValue model\nfrom datatrans.models import KeyValue\nfrom datatrans.utils import get_current_language, get_default_language\n\ndigest = KeyValue.objects.get(value=slug_from_url, language=get_current_language()).digest\nvalue = KeyValue.objects.get(digest=digest, ... | [
3
] | [] | [] | [
"django",
"multilingual",
"python",
"url_routing"
] | stackoverflow_0005368822_django_multilingual_python_url_routing.txt |
Q:
Releasing the GIL after destroying a sub-interpreter
I am embedding Python 3.2 in a C++ application and I have several sub interpreters that run at various times in the programs (created by Py_NewInterpreter). They acquire and release the GIL at various times, but I have run into a problem when I want to destroy o... | Releasing the GIL after destroying a sub-interpreter | I am embedding Python 3.2 in a C++ application and I have several sub interpreters that run at various times in the programs (created by Py_NewInterpreter). They acquire and release the GIL at various times, but I have run into a problem when I want to destroy one of the sub interpreters.
To destroy a sub interpreter, ... | [
"What happens if you call PyEval_ReleaseLock() directly after you call Py_EndInterpreter()? That's what the docs tells you to do anyway. :)\n"
] | [
3
] | [] | [] | [
"gil",
"interpreter",
"python",
"python_3.x"
] | stackoverflow_0005371910_gil_interpreter_python_python_3.x.txt |
Q:
Having trouble with getting URL config to work
I have an app, which I want to be the root of the website. So, I included the following urlpattern in my main urls.py like so:
(r'^$', include('search.urls')),
In my search urls.py, I have it set up in the following way:
urlpatterns = patterns('search.views',
(r'... | Having trouble with getting URL config to work | I have an app, which I want to be the root of the website. So, I included the following urlpattern in my main urls.py like so:
(r'^$', include('search.urls')),
In my search urls.py, I have it set up in the following way:
urlpatterns = patterns('search.views',
(r'^$', 'index'),
(r'^results/$', 'results'),
)
Th... | [
"Try this(put the searchurl include at the end and remove the $):\nurlpatterns = patterns('',\n (r'^books/', include('books.urls')),\n\n (r'^admin/', include(admin.site.urls)),\n\n\n (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),\n (r'^', include('search... | [
5
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005374904_django_python.txt |
Q:
QtSql (from PyQT) seems to be broken
I cannot access mysql server (on localhost).
Python 3.1 & latest PyQt
my code:
from PyQt4 import QtSql
db = QtSql.QSqlDatabase.addDatabase("QMYSQL")
db.setHostName("localhost")
db.setDatabaseName("test")
db.setUserName("root")
db.setPassword("admin")
db.open() #this always retu... | QtSql (from PyQT) seems to be broken | I cannot access mysql server (on localhost).
Python 3.1 & latest PyQt
my code:
from PyQt4 import QtSql
db = QtSql.QSqlDatabase.addDatabase("QMYSQL")
db.setHostName("localhost")
db.setDatabaseName("test")
db.setUserName("root")
db.setPassword("admin")
db.open() #this always returns true. why?
P.S. I'm beginer.
| [
"It always returns True, or it always returns False? Make up your mind.\nAnyway, the docs says: \n\nOpens the database connection using\n the current connection values. Returns\n true on success; otherwise returns\n false. Error information can be\n retrieved using lastError().\n\nSo if it always returns False,... | [
2
] | [] | [] | [
"pyqt4",
"python",
"python_3.x",
"qtsql"
] | stackoverflow_0005062963_pyqt4_python_python_3.x_qtsql.txt |
Q:
What are some elegant ways to abstract out repetitive exception handling in python?
When handling exceptions in python, I find myself repeating code quite often. The basic pattern is something of the form:
try:
action_here()
except CommonException1:
Action_always_taken_for_CommonException1()
except CommonExce... | What are some elegant ways to abstract out repetitive exception handling in python? | When handling exceptions in python, I find myself repeating code quite often. The basic pattern is something of the form:
try:
action_here()
except CommonException1:
Action_always_taken_for_CommonException1()
except CommonException2:
Action_always_taken_for_CommonException2()
except Exception:
Default_action_a... | [
"This situation is one of the main use cases for context managers and the with statement:\nfrom __future__ import with_statement # Needed in 2.5, but not in 2.6 or later\n\nfrom contextlib import contextmanager\n\n@contextmanager\ndef handle_exceptions():\n try:\n yield # Body of the with statement effect... | [
20,
6,
5
] | [] | [] | [
"exception_handling",
"python"
] | stackoverflow_0005374357_exception_handling_python.txt |
Q:
Change system date
I need to change my computer's local date to an earlier date (e.g. 2010). I couldnt do that in BIOS. Does anybody know how to do this task, for example by writing a Python snippet?
Thanks.
A:
If you use Windows, you should be able to do that in the time and date control panel (should be self ... | Change system date | I need to change my computer's local date to an earlier date (e.g. 2010). I couldnt do that in BIOS. Does anybody know how to do this task, for example by writing a Python snippet?
Thanks.
| [
"If you use Windows, you should be able to do that in the time and date control panel (should be self explaining). \nIf you use Linux, use the date command, and maybe hwclock (more info in the man pages).\nIf you use AmigaOS, use the appropriate settings window in the system Preferences folder.\nIf you use any othe... | [
1,
1
] | [] | [] | [
"date",
"python"
] | stackoverflow_0005217033_date_python.txt |
Q:
How can I remotely debug Django application?
I created a Django application, it works fine on my machine.
After that I checked out it at the test server but something doesn't work.
How can I debug it?
Is it possible to do it using PyDev Eclipse plugin or maybe are there some other ways?
In the best case I would ... | How can I remotely debug Django application? |
I created a Django application, it works fine on my machine.
After that I checked out it at the test server but something doesn't work.
How can I debug it?
Is it possible to do it using PyDev Eclipse plugin or maybe are there some other ways?
In the best case I would like to use "step into", "step over", "step out" ... | [
"This is a HOWTO for debugging application deployed via mod_wsgi:\nhttp://code.google.com/p/modwsgi/wiki/DebuggingTechniques\nDo you have root access to test machine? That would make it much easier. You can stop the Apache service and bring it up in a single process mode for debugging. \n",
"The simplest way is t... | [
3,
1,
0
] | [] | [] | [
"debugging",
"django",
"python"
] | stackoverflow_0005375519_debugging_django_python.txt |
Q:
Why Is My Stackless Executable So Much Smaller
I wrote a few games for a competition in Stackless Python and needed to create an executable. Accidentally though, I used CPython 2.6 instead of using Stackless Python 2.5 to build the executable. I rebuilt correctly, and found that the final size of the dist was down... | Why Is My Stackless Executable So Much Smaller | I wrote a few games for a competition in Stackless Python and needed to create an executable. Accidentally though, I used CPython 2.6 instead of using Stackless Python 2.5 to build the executable. I rebuilt correctly, and found that the final size of the dist was down from slightly over 30 MB down to around 8. Out of c... | [
"py2exe does look through to your dependencies and only includes the ones it thinks you're using. You can manually specify an exclude list if it's including extra modules.\nCheck out this py2exe script (replace \"setup.py\" with the name of your own main py file). This setup script skips the bundling step, so you c... | [
0
] | [] | [] | [
"cpython",
"py2exe",
"python",
"python_stackless",
"stackless"
] | stackoverflow_0005375859_cpython_py2exe_python_python_stackless_stackless.txt |
Q:
auto completion in a self written gui edit for HTML/CSS/PHP
I'd like to write my own GUI text edit for HTML, CSS and PHP. The whole user interface should be as mouse centered as I can get it. If you type "bo" there should be a list with stuff like "body" and "bold", just like you have in every other IDE. Could you... | auto completion in a self written gui edit for HTML/CSS/PHP | I'd like to write my own GUI text edit for HTML, CSS and PHP. The whole user interface should be as mouse centered as I can get it. If you type "bo" there should be a list with stuff like "body" and "bold", just like you have in every other IDE. Could you point me to some resources on making a fancy editor window?
My c... | [
"I'd suggest you to check out Scintilla, a GTK+ component for editing source code. You might find interesting ideas in its code, or use it as a core building block for your project.\n"
] | [
1
] | [] | [] | [
"html",
"python",
"text_editor",
"user_interface"
] | stackoverflow_0005375875_html_python_text_editor_user_interface.txt |
Q:
Attaching csv file to email in django
I need to create a mail that should have a csv file as an attachment. How do I attach a csv file to a mail in django?
A:
To attach files to emails sent by django, you'll have to create an EmailMessage instance and attach the file using the .attach() method.
For example, ass... | Attaching csv file to email in django | I need to create a mail that should have a csv file as an attachment. How do I attach a csv file to a mail in django?
| [
"To attach files to emails sent by django, you'll have to create an EmailMessage instance and attach the file using the .attach() method.\nFor example, assuming you have the CSV content in csv_data:\nemail = EmailMessage('Subject', 'email body', 'from@mail.com', ['to@mail.com'])\nemail.attach('name.csv', csv_data, ... | [
8
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005375769_django_python.txt |
Q:
How do I force Python PyMQI 1.2 to use my GCC compiler when I build it?
When I run the following command on AIX 6.1 to build PyMQI 1.2:
python setup.py build server
I get the following error:
Building PyMQI server 32bits
running build
running build_py
running build_ext
building 'pymqe' extension
cc_r -qlanglvl=ex... | How do I force Python PyMQI 1.2 to use my GCC compiler when I build it? | When I run the following command on AIX 6.1 to build PyMQI 1.2:
python setup.py build server
I get the following error:
Building PyMQI server 32bits
running build
running build_py
running build_ext
building 'pymqe' extension
cc_r -qlanglvl=extc89 -DNDEBUG -O3 -qstrict -qtune=pwr4 -qarch=pwr4 -qcpluscmt -D_LARGE_FILES ... | [
"The setup.py build command has the following two options\n --compiler (-c) specify the compiler type\n --help-compiler list available compilers\n\nUse those to specify the compiler which you want to use.\n"
] | [
1
] | [] | [] | [
"ibm_mq",
"pymqi",
"python"
] | stackoverflow_0005376514_ibm_mq_pymqi_python.txt |
Q:
Printing a list using python
I have a list compiled from excel cells, using python - say listlist. Each element in the cell/list is in unicode. When I print the list as
print listlist
I see 'u' prepended to each member of the list. But when I print the list like
for member in listlist:
print member
I do not s... | Printing a list using python | I have a list compiled from excel cells, using python - say listlist. Each element in the cell/list is in unicode. When I print the list as
print listlist
I see 'u' prepended to each member of the list. But when I print the list like
for member in listlist:
print member
I do not see the 'u' prepended to the member... | [
"This is because print list is equivalent to\nprint \"[\", \", \".join(repr(i) for i in list), \"]\"\n\nrepr(s) is u\"blabla\" for a unicode string while print s prints only blabla.\n",
"When printing the list, it shows each object within the list using the object's __repr__\nWhen printing the object alone, it us... | [
7,
4,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0005376529_python.txt |
Q:
encoding in python: what type is the variable
Python file
# -*- coding: UTF-8 -*-
a = 'Köppler'
print a
print a.__class__.__name__
mydict = {}
mydict['name'] = a
print mydict
print mydict['name']
Output:
Köppler
str
{'name': 'K\xc3\xb6ppler'}
Köppler
It seems that the name remains the same, but only when printin... | encoding in python: what type is the variable | Python file
# -*- coding: UTF-8 -*-
a = 'Köppler'
print a
print a.__class__.__name__
mydict = {}
mydict['name'] = a
print mydict
print mydict['name']
Output:
Köppler
str
{'name': 'K\xc3\xb6ppler'}
Köppler
It seems that the name remains the same, but only when printing a dictionary I get this strange escaped character... | [
"The reason for that behavior is that the __repr__ function in Python 2 escapes non-ASCII unicode characters. As the link shows, this is fixed in Python 3.\n",
"Yes, that's the UTF-8 representation of ö (U+00F6 LATIN SMALL LETTER O WITH DIAERESIS). It consists of a 0xC3 octet followed by a 0xB6 octet. UTF-8 is ... | [
5,
4,
1,
0
] | [] | [] | [
"encoding",
"python"
] | stackoverflow_0005376328_encoding_python.txt |
Q:
Php and python regexp difference?
I need to parse a string 'Open URN: 100000 LA: ' and get 100000 from it.
on python regexp (?<=Open URN: )[0-9]+(?= LA:) works fine but in php it gives following error:
preg_match(): Unknown modifier '['
I need it working php, so please help me to solve this problem and tell about... | Php and python regexp difference? | I need to parse a string 'Open URN: 100000 LA: ' and get 100000 from it.
on python regexp (?<=Open URN: )[0-9]+(?= LA:) works fine but in php it gives following error:
preg_match(): Unknown modifier '['
I need it working php, so please help me to solve this problem and tell about difference in python and php regexps.
| [
"You have to use delimiters when you are using the Perl Compatible Regular Expressions (PCRE) functions in PHP (to which preg_match() belongs).\nFrom the documentation:\n\nWhen using the PCRE functions, it is required that the pattern is enclosed by delimiters. A delimiter can be any non-alphanumeric, non-backslash... | [
3,
1
] | [] | [] | [
"php",
"python",
"regex"
] | stackoverflow_0002913626_php_python_regex.txt |
Q:
How can I do an "if run from ipython" test in Python?
To ease debugging from Ipython, I include the following in the beginning of my scripts
from IPython.Debugger import Tracer
debug = Tracer()
However, if I launch my script from the command line with
$ python myscript.py
I get an error related to Ipython. Is th... | How can I do an "if run from ipython" test in Python? | To ease debugging from Ipython, I include the following in the beginning of my scripts
from IPython.Debugger import Tracer
debug = Tracer()
However, if I launch my script from the command line with
$ python myscript.py
I get an error related to Ipython. Is there a way to do the following
if run_from_ipython():
fr... | [
"This is probably the kind of thing you are looking for:\ndef run_from_ipython():\n try:\n __IPYTHON__\n return True\n except NameError:\n return False\n\n",
"The Python way is to use exceptions. Like:\ntry:\n from IPython.Debugger import Tracer\n debug = Tracer()\nexcept ImportEr... | [
59,
13
] | [] | [] | [
"ipython",
"python"
] | stackoverflow_0005376837_ipython_python.txt |
Q:
Execute MongoDb Statements in Python
I have a Webserver running in Python. He is getting some Data from some Apps and need to store these in MongoDB. My MongoDB is sharded.
Now i want that my Webserver know how much Shards MongoDB has. At the moment he reads this from a cfg file. There is an Statement in MongoDb ... | Execute MongoDb Statements in Python | I have a Webserver running in Python. He is getting some Data from some Apps and need to store these in MongoDB. My MongoDB is sharded.
Now i want that my Webserver know how much Shards MongoDB has. At the moment he reads this from a cfg file. There is an Statement in MongoDb named printshardingstatus where u can see ... | [
"There is no server command for printShardingStatus -- it is just a mongo (javascript) shell helper function. The helper is a few queries against\nthe config database and then some grouping and formatting to make things look nicer.\nIf you ever want to see how things work in the javascript shell you\ncan just remov... | [
1,
0,
0
] | [] | [] | [
"mongodb",
"pymongo",
"python"
] | stackoverflow_0005350599_mongodb_pymongo_python.txt |
Q:
Which is better C Vs Python?
I am being told that Python is far superior to C in the ease of programming. I am an average( dont want to praise myself) user of C. Will it be helpful if I learn Python to implement my codes in future?
A:
It depends on what do you expect from your language. For example I am develop... | Which is better C Vs Python? | I am being told that Python is far superior to C in the ease of programming. I am an average( dont want to praise myself) user of C. Will it be helpful if I learn Python to implement my codes in future?
| [
"It depends on what do you expect from your language. For example I am developing firmware for embedded device. I can boot Linux in it and do my work in Python, but I need really fast code tuned for the hardware, so I use C on bare metal (without operating system). On the other hand, I need to develop many programs... | [
12,
4
] | [] | [] | [
"c",
"python"
] | stackoverflow_0005377123_c_python.txt |
Q:
How to estimate the number of pixels in a satellite image using python matplotlib
I'm working with satellite images. I have a program (Python) to contrast satellite images by temperature of the cloud's top, the program is below:
from pylab import *
#import pylab imread,imshow
sat=imread('1101092045G13I04.tif')
im... | How to estimate the number of pixels in a satellite image using python matplotlib | I'm working with satellite images. I have a program (Python) to contrast satellite images by temperature of the cloud's top, the program is below:
from pylab import *
#import pylab imread,imshow
sat=imread('1101092045G13I04.tif')
imshow(sat)
map=imread('map.tif')
map=mean(map,2,)/3
#contour(map,cmap=cm.gray)
imshow(... | [
"\nNow i need to estimate the number of pixels for each scale of temperatures.\n\nI suppose histogram function is what you need.\n"
] | [
6
] | [] | [] | [
"image_processing",
"matplotlib",
"python"
] | stackoverflow_0005377065_image_processing_matplotlib_python.txt |
Q:
Profiling of a python function
Do you have any idea of how can I make this function more time-efficient?
def c(n):
word = 32
#l = []
c = 0
for i in range(0, 2**word):
#print(str(bin(i)))#.count('1')
if str(bin(i)).count('1') == n:
c = c + 1
print(c)
... | Profiling of a python function | Do you have any idea of how can I make this function more time-efficient?
def c(n):
word = 32
#l = []
c = 0
for i in range(0, 2**word):
#print(str(bin(i)))#.count('1')
if str(bin(i)).count('1') == n:
c = c + 1
print(c)
if i == 2**28:
print('6... | [
"You are counting how many 32-bit numbers have a given number of 1s. This number is the binomial coefficient 32 choose bits, and can be calculated with:\nfrom math import factorial\nprint factorial(32) // (factorial(bits) * factorial(32-bits))\n\n"
] | [
8
] | [] | [] | [
"profiling",
"python",
"python_3.x"
] | stackoverflow_0005377795_profiling_python_python_3.x.txt |
Q:
Doing shell backquote in python?
I am translating bash scripts into python for some reasons.
Python is more powerfull, nevertheless, it is much more harder to code simple bash code like this :
MYVAR = `grep -c myfile`
With python I have first to define a backquote function could be :
def backquote(cmd,noErrorCod... | Doing shell backquote in python? | I am translating bash scripts into python for some reasons.
Python is more powerfull, nevertheless, it is much more harder to code simple bash code like this :
MYVAR = `grep -c myfile`
With python I have first to define a backquote function could be :
def backquote(cmd,noErrorCode=(0,),output=PIPE,errout=PIPE):
p... | [
"In Python 2.7 or above, there is subprocess.check_output() which basically does what you are after.\n",
"The os.subprocess documentation describes how to replace backquotes:\noutput=`mycmd myarg`\n==>\noutput = Popen([\"mycmd\", \"myarg\"], stdout=PIPE).communicate()[0]\n\n",
"Having defined this backquote fun... | [
9,
4,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0005377229_python.txt |
Q:
wxpython GridBagSizer problem
when ever I use span in GridBagSizer I get a problem, here's my code:
hbox3.Add(arrangeLabel)
hbox3.Add(self.arrangeComboBox, flag=wx.LEFT, border=10)
sizer.Add(hbox3, pos=(7,0), span=(7,3), flag=wx.ALL, border=15)
#######################
hbox4 = wx.BoxSizer(wx.HO... | wxpython GridBagSizer problem | when ever I use span in GridBagSizer I get a problem, here's my code:
hbox3.Add(arrangeLabel)
hbox3.Add(self.arrangeComboBox, flag=wx.LEFT, border=10)
sizer.Add(hbox3, pos=(7,0), span=(7,3), flag=wx.ALL, border=15)
#######################
hbox4 = wx.BoxSizer(wx.HORIZONTAL)
runButton = wx.Button... | [
"I think you're misunderstanding the span argument. span=(7,3) is telling the sizer to stretch the widget across 7 rows and 3 columns from its starting position. If you want it to cover 7,0 to 7,3, try span=(1,4).\n"
] | [
2
] | [] | [] | [
"python",
"user_interface",
"wxpython"
] | stackoverflow_0005364329_python_user_interface_wxpython.txt |
Q:
Python proper logging with filehandlers
I am using python logging in my django application. A class that connects to a backend api initialises this logger with a filehandler if needed. The class gets instantiated everytime an api call is made. I have tried making sure additional handlers are not added every time, ... | Python proper logging with filehandlers | I am using python logging in my django application. A class that connects to a backend api initialises this logger with a filehandler if needed. The class gets instantiated everytime an api call is made. I have tried making sure additional handlers are not added every time, but
lsof | grep my.log
shows an increasing... | [
"I did not analysed if for a long time, but it looks like a concurrency problem.\nEach process/thread is keeping it's own list of the file handles to the opened log files.\nHow to fix it? For the multithreaded code, make sure that there is a global dictionary where all handles are kept. For the multiprocess - I'm a... | [
1
] | [] | [] | [
"django",
"filehandler",
"logging",
"python"
] | stackoverflow_0005323791_django_filehandler_logging_python.txt |
Q:
Bind to same function in Python
I need to use two events to send a message from child frame to main frame and close the child frame (by using pubsub). One of the events is the click event of a "Cancel" button on the child frame and the other one is the close event of the child frame. So I use a common "OnClose" fu... | Bind to same function in Python | I need to use two events to send a message from child frame to main frame and close the child frame (by using pubsub). One of the events is the click event of a "Cancel" button on the child frame and the other one is the close event of the child frame. So I use a common "OnClose" function for both of them. Here is my r... | [
"Try reversing the order of your calls in your OnClose method. Put the pubsub call first and the Close call last. Or just use Destroy() at the end instead of Close().\n"
] | [
2
] | [] | [] | [
"publish_subscribe",
"python",
"wxpython"
] | stackoverflow_0005375193_publish_subscribe_python_wxpython.txt |
Q:
how to calculate trendline for stock charts
I have read the topic: How do I calculate a trendline for a graph?
What I am looking for though is how to find the line that touches the outer extreme points of a graph. The intended use is calculation of support, resistance lines for stock charts. So it is not a merely... | how to calculate trendline for stock charts | I have read the topic: How do I calculate a trendline for a graph?
What I am looking for though is how to find the line that touches the outer extreme points of a graph. The intended use is calculation of support, resistance lines for stock charts. So it is not a merely simple regression but it should also limit the n... | [
"You could think about using a method that calculates the concave hull of your data. There are probably existing python implementations you could find. This will give you the boundary that encloses your timeseries. If there are outliers in your dataset that you wish to exclude, you could apply some sort of filter o... | [
0,
0
] | [] | [] | [
"python",
"stocks"
] | stackoverflow_0005377347_python_stocks.txt |
Q:
Simple Hotkey Script in Python - How to set a global hotkey to send a string of text?
I was wondering how I could use wxPython along with the win32apis to create a simple script that will activate a window (if it is not already active) with a certain title and output text (keystrokes). One possible application for... | Simple Hotkey Script in Python - How to set a global hotkey to send a string of text? | I was wondering how I could use wxPython along with the win32apis to create a simple script that will activate a window (if it is not already active) with a certain title and output text (keystrokes). One possible application for this would be keyboard shortcuts in gaming. I have read up on the wxPython RegisterHotKey(... | [
"Are you talking about activating a window that you created in wx or a separate application, like notepad? If it's with wx, then it's trivial. You'd just use Raise() to bring whatever frame you need into focus. You would probably use PubSub or PostEvent to let the sub-frame know that it needs to Raise.\nIf you're t... | [
4
] | [] | [] | [
"python",
"pywin32",
"wxpython"
] | stackoverflow_0005365133_python_pywin32_wxpython.txt |
Q:
Django Model Inheritance and Admin System
I'm trying to build a system for managing the various types of content in a page. For example, a page may have text content, hyperlink content, video content, ect.
In my modeling code, I have a base class:
class ContentItem(models.Model):
title = models.CharField(ma... | Django Model Inheritance and Admin System | I'm trying to build a system for managing the various types of content in a page. For example, a page may have text content, hyperlink content, video content, ect.
In my modeling code, I have a base class:
class ContentItem(models.Model):
title = models.CharField(max_length=1000)
page_order = models.IntegerF... | [
"This is a fine way to do it. Unfortunately, Django's ORM doesn't handle model inheritance as smoothly as you might want. page.contents will contain a QuerySet of Content objects. If you want to access the subtypes, you need to create some way of downcasting a content object. The problem is that this requires an... | [
3
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0005378748_django_django_admin_django_models_python.txt |
Q:
Why does assertAlmostEqual(-inf,-inf) fail?
Numpy's log method gives -inf for log(0). This value is comparable:
>>> np.log(0) == np.log(0)
True
Now in unittesting the following works fine:
self.assertEqual(np.log(0),np.log(0))
but this fails:
self.assertAlmostEqual(np.log(0),np.log(0))
Why is this behaviour lik... | Why does assertAlmostEqual(-inf,-inf) fail? | Numpy's log method gives -inf for log(0). This value is comparable:
>>> np.log(0) == np.log(0)
True
Now in unittesting the following works fine:
self.assertEqual(np.log(0),np.log(0))
but this fails:
self.assertAlmostEqual(np.log(0),np.log(0))
Why is this behaviour like this? Is this a bug or intended? If intended, h... | [
"From the doc of unittest assertAlmostEqual(a, b) is by default equivalent to round(a-b, 7) == 0. so in your case you have :\nIn [8]: np.log(0) - np.log(0)\nOut[8]: nan\n\nIn [9]: round(np.log(0) - np.log(0), 7)\nOut[9]: nan\n\nIn [11]: np.nan == 0\nOut[11]: False\n\nThat explain why your test fail.\nFor making it ... | [
5,
4,
3
] | [] | [] | [
"infinity",
"numpy",
"python",
"unit_testing"
] | stackoverflow_0005376853_infinity_numpy_python_unit_testing.txt |
Q:
Calculate tkinter window width based on title length
How can I calculate and set the width of a tkinter.Frame-derived window based on the window's title length?
I.e., could someone help me out with the with the width = ???-expression in the the code below? (well aware of that the result depends on the font being ... | Calculate tkinter window width based on title length | How can I calculate and set the width of a tkinter.Frame-derived window based on the window's title length?
I.e., could someone help me out with the with the width = ???-expression in the the code below? (well aware of that the result depends on the font being used, system buttons, etc.)
Thanks in advance
/Harald
impo... | [
"You can't do this based on the window title. The display (and thus the width) is controlled by the window manager. The only way you can do this is if you know for certain what font is being used in the title bar. In that case you can use the measure1 method of a font object to compute the width of a string in that... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0005376211_python_tkinter.txt |
Q:
Efficient Context-Free Grammar parser, preferably Python-friendly
I am in need of parsing a small subset of English for one of my project, described as a context-free grammar with (1-level) feature structures (example) and I need to do it efficiently .
Right now I'm using NLTK's parser which produces the right out... | Efficient Context-Free Grammar parser, preferably Python-friendly | I am in need of parsing a small subset of English for one of my project, described as a context-free grammar with (1-level) feature structures (example) and I need to do it efficiently .
Right now I'm using NLTK's parser which produces the right output but is very slow. For my grammar of ~450 fairly ambiguous non-lexic... | [
"By all means take a look at Pyparsing. It's the most pythonic implementations of parsing I've come across, and it's a great design from a purely academic standpoint.\nI used both ANTLR and JavaCC to teach translator and compiler theory at a local university. They're both good and mature, but I wouldn't use them in... | [
16,
2,
2,
2,
1,
1,
0,
0
] | [] | [] | [
"grammar",
"nlp",
"nltk",
"parsing",
"python"
] | stackoverflow_0004543008_grammar_nlp_nltk_parsing_python.txt |
Q:
Iteratively write XML nodes in python
There are many ways to read XML, both all-at-once (DOM) and one-bit-at-a-time (SAX). I have used SAX or lxml to iteratively read large XML files (e.g. wikipedia dump which is 6.5GB compressed).
However after doing some iterative processing (in python using ElementTree) of that... | Iteratively write XML nodes in python | There are many ways to read XML, both all-at-once (DOM) and one-bit-at-a-time (SAX). I have used SAX or lxml to iteratively read large XML files (e.g. wikipedia dump which is 6.5GB compressed).
However after doing some iterative processing (in python using ElementTree) of that XML file, I want to write out the (new) XM... | [
"Fredrik Lundh's elementtree.SimpleXMLWriter will let you write out XML incrementally. Here's the demo code embedded in the module:\nfrom elementtree.SimpleXMLWriter import XMLWriter\nimport sys\n\nw = XMLWriter(sys.stdout)\n\nhtml = w.start(\"html\")\n\nw.start(\"head\")\nw.element(\"title\", \"my document\")\nw.e... | [
4,
1,
1,
1
] | [] | [] | [
"memory",
"python",
"xml"
] | stackoverflow_0005377980_memory_python_xml.txt |
Q:
How to write this query?
Suppose I have an sqlite table like this:
Id|B|C|D
And I have a list containing some values of Id. Maybe [1,3,45,67](something like that.)
I want to get the rows with Id's in the list, whose B values are greater than 5 and eventually order it by C.
I think the title I put for this is horr... | How to write this query? | Suppose I have an sqlite table like this:
Id|B|C|D
And I have a list containing some values of Id. Maybe [1,3,45,67](something like that.)
I want to get the rows with Id's in the list, whose B values are greater than 5 and eventually order it by C.
I think the title I put for this is horrible, if you can think of a be... | [
"Assuming ids_list is your list of ids and tablename is your table: \nc = sqlite3.connect('foo').cursor()\nc.execute(\"\"\"\nselect Id, B, C, D\nfrom tablename\nwhere \n Id in (%s) and \n B >= 5\norder by C\n\"\"\" % \",\".join( str(int(id)) for id in ids_list ))\n\nThe %s replacement is bad practice because ... | [
3,
3,
2,
0
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0005378616_python_sqlite.txt |
Q:
django lambda and django-activity-stream
I am not familiar with the lambda function itself, and don't really know how to debug this issue.
Django-1.1.2
I am using, django-activity-stream in order to render activity streams for my users.
In the documentation for this items it says that you need to pass two lambda f... | django lambda and django-activity-stream | I am not familiar with the lambda function itself, and don't really know how to debug this issue.
Django-1.1.2
I am using, django-activity-stream in order to render activity streams for my users.
In the documentation for this items it says that you need to pass two lambda functions to incorporate with existing newtwork... | [
"Somewhere above where these lambdas are defined, you need to import the names get_people_i_follow and get_my_followers. I'm not familiar with django-activity-stream, but it's probably something like from activity_stream import get_people_i_follow, get_my_follwers. \nLambda is a keyword for creating anonymous fun... | [
1,
1,
0
] | [] | [] | [
"django",
"lambda",
"python"
] | stackoverflow_0005379093_django_lambda_python.txt |
Q:
Keeping track of changes since the last save in django models
A couple of times I've run into a situation, when at save time I need to know which model fields are going to be updated and act accordingly.
The most obvious solution to this is to take the primary key field and retrieve a copy of the model from the da... | Keeping track of changes since the last save in django models | A couple of times I've run into a situation, when at save time I need to know which model fields are going to be updated and act accordingly.
The most obvious solution to this is to take the primary key field and retrieve a copy of the model from the database:
class MyModel(models.Model):
def save(self, force_inse... | [
"I think your solution looks reasonable.\nAlternatively you could have a Manager method called get_and_copy() (or something) that hung a copy of the original object off of what is returned. You could then use another Manager method, save_and_check() which took advantage of the copied original.\nFWIW: If you are pla... | [
2,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0002029814_django_django_models_python.txt |
Q:
Altering python-gearman worker tasks during job processing
I'm attempting to change the tasks available on a python-gearman worker during its work cycle. My reason for doing this is to allow me a little bit of control over my worker processes and allowing them to reload from a database. I need every worker to re... | Altering python-gearman worker tasks during job processing | I'm attempting to change the tasks available on a python-gearman worker during its work cycle. My reason for doing this is to allow me a little bit of control over my worker processes and allowing them to reload from a database. I need every worker to reload at regular intervals, but I don't want to simply kill the p... | [
"It looks like subclassing the GearmanWorker class and adding a few flags can work around this issue. I need to allow the job to complete before I start issuing new commands from the worker to the server, which seems to interrupt the current job. So if we overwrite the on_job_complete function we can check for th... | [
1,
0
] | [] | [] | [
"gearman",
"python",
"python_gearman"
] | stackoverflow_0005362830_gearman_python_python_gearman.txt |
Q:
Combining file and directory selection options
I would like to combine the functionality of two arguments to one. Currently -f may be used to specify a single file or wild-card, -d may specify a directory. I would like -f to handle its currently functionality or a directory.
Here's the current options statements:
... | Combining file and directory selection options | I would like to combine the functionality of two arguments to one. Currently -f may be used to specify a single file or wild-card, -d may specify a directory. I would like -f to handle its currently functionality or a directory.
Here's the current options statements:
parser.add_option('-d', '--directory',
actio... | [
"You can pass a list of wildcards, directories and files to this function. However, your shell will expand your wildcards if you do not put them between quotes in the command line.\nimport os\nimport glob\n\ndef combine(arguments):\n all_files = []\n for arg in arguments:\n if '*' in arg or '?' in arg:... | [
1
] | [] | [] | [
"command_line_arguments",
"function",
"python",
"scripting"
] | stackoverflow_0005380279_command_line_arguments_function_python_scripting.txt |
Q:
Problem adding to solr index using Django-Haystack
I'm trying to index a model in Solr with django-haystack, but it returns me the following error(when using rebuild_index or update_index) :
Failed to add documents to Solr: [Reason: ERROR:unknown field 'django_ct']
I followed step by step the "getting started" of... | Problem adding to solr index using Django-Haystack | I'm trying to index a model in Solr with django-haystack, but it returns me the following error(when using rebuild_index or update_index) :
Failed to add documents to Solr: [Reason: ERROR:unknown field 'django_ct']
I followed step by step the "getting started" of Haystack-Search.
I'm using :
the latest version of Apa... | [
"Be sure your $SOLR_HOME/conf/schema.xml file contains the 'django_ct' field declaration. That is a custom field and needs to be added manually along with any other custom fields you are using.\n",
"Try using text = CharField(document\n"
] | [
1,
0
] | [] | [] | [
"django",
"django_haystack",
"python"
] | stackoverflow_0005365116_django_django_haystack_python.txt |
Q:
django requests get mixed up?
I have 3 django projects with different settings, 2 under the subdomains parents.abc.com,teachers.abc.com and abc.com. They all come under a shared apache instance. Here is my httpd configuration file:
LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agen... | django requests get mixed up? | I have 3 django projects with different settings, 2 under the subdomains parents.abc.com,teachers.abc.com and abc.com. They all come under a shared apache instance. Here is my httpd configuration file:
LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
CustomLog /home/use... | [
"I think you need to specify the server name in each vhost\nAdd in:\nServerName parents.abc.com\n\nand:\nServerName teachers.abc.com\n\nServerAlias, as far as I know, by itself is not enough to define a name based virtual host.\n"
] | [
1
] | [] | [] | [
"apache",
"django",
"python"
] | stackoverflow_0005380150_apache_django_python.txt |
Q:
Idiom for socket receive in Python
I have some experience with socket programming using the Berkeley socket API in C. Generally, any socket programming requires a strategy that enables the receiving socket to know how much data it should receive. This can be accomplished with either header length fields, or deli... | Idiom for socket receive in Python | I have some experience with socket programming using the Berkeley socket API in C. Generally, any socket programming requires a strategy that enables the receiving socket to know how much data it should receive. This can be accomplished with either header length fields, or delimiter characters. Generally, I prefer a... | [
"You can use the struct module convert Python integers to and from strings/byte arrays. Just read the number of bytes that correspond to the size of the type header and convert it with the struct module and you should be good to go. (note: be sure to use the right endian-flags when encoding/decoding)\n",
"The sys... | [
5,
0,
0
] | [] | [] | [
"c",
"python",
"sockets"
] | stackoverflow_0005380531_c_python_sockets.txt |
Q:
building a tree from a csv file using python
My csv file has the following format
Col1 Col2
a b
b c
c d
d e
x b
y c
z c
m x
h b
i b
I will create a dictionary to hold this data like this
{ b:[a,x,h,i] , c:[b... | building a tree from a csv file using python | My csv file has the following format
Col1 Col2
a b
b c
c d
d e
x b
y c
z c
m x
h b
i b
I will create a dictionary to hold this data like this
{ b:[a,x,h,i] , c:[b,y,z], d:[c], e:[d], x:[m] }
From this dictionar... | [
"You can use Python-Graph.\npairs = read_from_csv(...)\n\nfrom pygraph.classes.digraph import digraph \ngr = digraph()\ngr.add_nodes(set([x for (x,y) in pairs]+[y for (x,y) in pairs]))\n\nfor pair in pairs:\n gr.add_edge(pair)\n\n#and now you can do something with the graph...\n\nfrom pygraph.algorithms.searchin... | [
3,
0,
0
] | [] | [] | [
"csv",
"python",
"tree"
] | stackoverflow_0005381060_csv_python_tree.txt |
Q:
How can I know if a email is sent correctly with Django/Python?
I need know that if a email is sent correctly for to do several operations but the function always return True.
Any idea?
Thanks you.
A:
There is no way to check that a mail has actually been received. This is not because of a failing in Django, but... | How can I know if a email is sent correctly with Django/Python? | I need know that if a email is sent correctly for to do several operations but the function always return True.
Any idea?
Thanks you.
| [
"There is no way to check that a mail has actually been received. This is not because of a failing in Django, but a consequence of the way email works.\nIf you need some form of definite delivery confirmation, you need to use something other than email.\n",
"When running unit tests emails are stored as EmailMessa... | [
9,
9,
3,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005374818_django_python.txt |
Q:
How to to optimize this python problem?
Here is the problem. And my solution is:
import sys
LIST_ITEM = []
NUMBER_OF_TEST_CASES = int(raw_input())
def non_decreasing(my_list):
if len(my_list) < 2:
return my_list
my_list.sort()
return my_list
if __name__ == "__main__":
if NUMBER_OF_TEST_CAS... | How to to optimize this python problem? | Here is the problem. And my solution is:
import sys
LIST_ITEM = []
NUMBER_OF_TEST_CASES = int(raw_input())
def non_decreasing(my_list):
if len(my_list) < 2:
return my_list
my_list.sort()
return my_list
if __name__ == "__main__":
if NUMBER_OF_TEST_CASES >= 1000001 or NUMBER_OF_TEST_CASES <= 0:
... | [
"EDIT: Well shit, apparently you aren't supposed to have dupes? That changes things, and your current code doesn't work right anyway. Leaving my old answer for now...\nThe simple answer is profile it! I generated data with:\nimport random\nout = open('foobar.txt', 'w')\n\ntotal = random.randint(100000, 1e6)\nout.wr... | [
3,
2,
1
] | [] | [] | [
"optimization",
"python",
"sorting"
] | stackoverflow_0005380481_optimization_python_sorting.txt |
Q:
How to secure webapp reachable by other app?
Scenario is that my webapp gets data
and clients app is fetching them.
Its server to server communication.
Are there any python examples or packages
that will secure my app from unverified request?
I looked at 'nonce'.Is it over kill?
If not are there examples how i cou... | How to secure webapp reachable by other app? | Scenario is that my webapp gets data
and clients app is fetching them.
Its server to server communication.
Are there any python examples or packages
that will secure my app from unverified request?
I looked at 'nonce'.Is it over kill?
If not are there examples how i could implement
it in python.
| [
"If I understood correctly your problem you could use Django, a framework for developing web application that naturally supports authentication upon web requests. For example, if you want to grant access to a view on your server to authenticated users you can just use decorators to secure it.\nfrom django.contrib.a... | [
1
] | [] | [] | [
"authentication",
"python"
] | stackoverflow_0005380996_authentication_python.txt |
Q:
Checking for bounding box intersections/collisions with a view frustum
I want to check a view frustum against the axis aligned bounding boxes of some objects, to check roughly whether those objects are in the field of view or not. Speed is not a big deal.
A:
I figured out that building a world-space model of the... | Checking for bounding box intersections/collisions with a view frustum | I want to check a view frustum against the axis aligned bounding boxes of some objects, to check roughly whether those objects are in the field of view or not. Speed is not a big deal.
| [
"I figured out that building a world-space model of the view frustum and checking for bbox collisions with it was the wrong way to go about this. A much simpler method is to go the opposite way and convert each vertex of a given bbox to screen-space, and if any vertex of the bbox is within the screen bounds then co... | [
3,
2
] | [] | [] | [
"bounding_box",
"collision_detection",
"frustum",
"python"
] | stackoverflow_0005348163_bounding_box_collision_detection_frustum_python.txt |
Q:
Error getting variables from files to int() in Python
I'm trying to get a value from a variable inside some files, here is the code:
path = '/opt/log/...'
word = 'somevariable'
def enumeratepaths(path=path):
paths = []
for dirpath, dirnames, files in os.walk(path):
for file in files:
f... | Error getting variables from files to int() in Python | I'm trying to get a value from a variable inside some files, here is the code:
path = '/opt/log/...'
word = 'somevariable'
def enumeratepaths(path=path):
paths = []
for dirpath, dirnames, files in os.walk(path):
for file in files:
fullpath = os.path.join(dirpath, file)
paths.app... | [
"If find can't find the string you are searching for, it will return -1. So you can check the return value of search.find(word) to see if word was actually found.\nAt the moment you just proceed even if the searched word as not found. find_start will end up as 6, find_end as 8, and probably search[6:8] contains the... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0005382040_python.txt |
Q:
Scrollbars for a .jpg image on a Tkinter Canvas in Python
I'm trying to make a jpeg on a canvas scrollable but I can't seem to get my scrollbars to work. Here's some example code:
from Tkinter import *
import Image, ImageTk
root = Tk()
frame = Frame(root, bd=2, relief=SUNKEN)
frame.grid_rowconfigure(0, weight=1... | Scrollbars for a .jpg image on a Tkinter Canvas in Python | I'm trying to make a jpeg on a canvas scrollable but I can't seem to get my scrollbars to work. Here's some example code:
from Tkinter import *
import Image, ImageTk
root = Tk()
frame = Frame(root, bd=2, relief=SUNKEN)
frame.grid_rowconfigure(0, weight=1)
frame.grid_columnconfigure(0, weight=1)
xscrollbar = Scrollb... | [
"You need to tell the canvas what part of the drawing space to scroll. Use something like:\ncanvas.config(scrollregion=canvas.bbox(ALL))\n\nMore information can be found here: http://effbot.org/tkinterbook/canvas.htm#coordinate-systems\n"
] | [
7
] | [] | [] | [
"jpeg",
"python",
"scrollbar",
"tkinter"
] | stackoverflow_0005382039_jpeg_python_scrollbar_tkinter.txt |
Q:
Python Script to enumerate registry
from _winreg import *
areg=ConnectRegistry(None,HKEY_LOCAL_MACHINE)
akey=OpenKey(areg,r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall")
count=0
for i in range (1024):
try:
subkey=EnumKey(akey,i)
asubkey = OpenKey(akey, subkey)
"""print subkey"... | Python Script to enumerate registry | from _winreg import *
areg=ConnectRegistry(None,HKEY_LOCAL_MACHINE)
akey=OpenKey(areg,r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall")
count=0
for i in range (1024):
try:
subkey=EnumKey(akey,i)
asubkey = OpenKey(akey, subkey)
"""print subkey"""
val=QueryValueEx(asubkey,"Di... | [
" list1.append(val[0])\n if(len(val[0])==0):\n pass\n\nHere you put a value in list1, but bail afterward. I have a hunch you meant to check and bail without actually adding anything to list1.\n"
] | [
0
] | [] | [] | [
"enumeration",
"python",
"registry"
] | stackoverflow_0005359432_enumeration_python_registry.txt |
Q:
Appending associative arrays in Python
I've been all over looking for a solution to this recently, and so far to no avail. I'm coming from php to python, and running into an associative array difference I'm not sure now to overcome.
Take this line:
data[user]={i:{'item':row[0],'time':row[1]}}
This overwrites each... | Appending associative arrays in Python | I've been all over looking for a solution to this recently, and so far to no avail. I'm coming from php to python, and running into an associative array difference I'm not sure now to overcome.
Take this line:
data[user]={i:{'item':row[0],'time':row[1]}}
This overwrites each of my data[user] entries, obviously, as it'... | [
"Something like this should work. Note that unlike PHP, Python has separate primitive types for numeric arrays (called \"lists\") and associative arrays (called \"dictionaries\" or \"dicts\").\nif user not in data:\n data[user] = []\ndata[user].append({'item': row[0], 'time': row[1]})\n\n",
"import collection... | [
12,
4,
1,
0
] | [] | [] | [
"append",
"dictionary",
"list",
"python"
] | stackoverflow_0005382188_append_dictionary_list_python.txt |
Q:
Python: getting max of a of a {(tuple): value } dictionary per fieldname in tuple
another list-dictionary question.
I have a dict as follows with unit names and testnames in a list:
dictA = {('unit1', 'test1'): 10, ('unit2', 'test1'): 78, ('unit2', 'test2'): 2, ('unit1', 'test2'): 45}
units = ['unit1', 'unit2']... | Python: getting max of a of a {(tuple): value } dictionary per fieldname in tuple | another list-dictionary question.
I have a dict as follows with unit names and testnames in a list:
dictA = {('unit1', 'test1'): 10, ('unit2', 'test1'): 78, ('unit2', 'test2'): 2, ('unit1', 'test2'): 45}
units = ['unit1', 'unit2']
testnames = ['test1','test2']
How do we find the max of the values for each test in ... | [
">>> dictA = {('unit1', 'test1'): 10, ('unit2', 'test1'): 78, ('unit2', 'test2'): 2, ('unit1', 'test2'): 45}\n>>> maxDict={}\n>>> for (unitName,testName),grade in dictA.items():\n maxDict[testName]=max(maxDict.get(testName,0),grade)\n\n\n>>> maxDict\n{'test1': 78, 'test2': 45}\n\nI guess this should solve it.\... | [
6,
0
] | [] | [] | [
"dictionary",
"list",
"max",
"python",
"tuples"
] | stackoverflow_0005380497_dictionary_list_max_python_tuples.txt |
Q:
"DLL load failed" when using mercurial on trac
My mercurial repository works correctly in trac when I use the tracd server.
However, when I use apache, I get the following warning at the top of all trac pages:
Warning: Can't synchronize with
repository "(default)" (Unsupported
version control system "hg": DLL... | "DLL load failed" when using mercurial on trac | My mercurial repository works correctly in trac when I use the tracd server.
However, when I use apache, I get the following warning at the top of all trac pages:
Warning: Can't synchronize with
repository "(default)" (Unsupported
version control system "hg": DLL load
failed: The specified module could not
be ... | [
"I have the same problem. There is no problem in mercurial package version 1.7.1. The mistake appears in higher versions, up to 1.8.\n",
"I ran into a similar error when setting up hgweb (no trac). Hopefully this helps you and anyone else doing the same thing and finding this question via Google.\nI solved the pr... | [
1,
0
] | [] | [] | [
"apache",
"mercurial",
"mod_wsgi",
"python",
"trac"
] | stackoverflow_0005158523_apache_mercurial_mod_wsgi_python_trac.txt |
Q:
More than one row returned by a subquery in PostgreSQL
In the table1 there is a column named calendar_date, the record is in the format 10/8/2010, in the table2 there is a column named date, with the format of 10/8.
In the table2 there are other two columns named daynoleap, dayleap, which indicates the julian dat... | More than one row returned by a subquery in PostgreSQL | In the table1 there is a column named calendar_date, the record is in the format 10/8/2010, in the table2 there is a column named date, with the format of 10/8.
In the table2 there are other two columns named daynoleap, dayleap, which indicates the julian date number of either noleap year or leap year. Now I need to a... | [
"This is a very basic update statement. There should be zero sub-queries and correlated queries:\nUPDATE table1 \n SET julian_date = dayleap\nFROM table2\nWHERE date = %s \n\nPS:\n\nI would not name your columns after data types (date). Although its allowed it can bite you in subtle and insidious ways.\nYour hopef... | [
2,
1,
0
] | [] | [] | [
"postgresql",
"python",
"subquery"
] | stackoverflow_0005344932_postgresql_python_subquery.txt |
Q:
Python string interpolation and tuples
Which of these Python string interpolations is proper (not a trick question)?
'%s' % my_string
'%s' % (my_string)
'%s' % (my_string, )
If it varies by version, please summarize.
A:
Old format
The first one is the most common one. The third has unnecessary parenthesis and ... | Python string interpolation and tuples | Which of these Python string interpolations is proper (not a trick question)?
'%s' % my_string
'%s' % (my_string)
'%s' % (my_string, )
If it varies by version, please summarize.
| [
"Old format\nThe first one is the most common one. The third has unnecessary parenthesis and doesn't help the legibility if you've only one object you want to use in your format-string. The second is just plain silly, because that's not even a tuple.\nNew format\nNowadays starting with Python 2.6, there's a new and... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0005382014_python.txt |
Q:
determine a boolean value based on min and max value
right now I have min, max value from table1 that defines the range of a value. There is a boolean column in table2 of which the value is determined by the min and max value in table1. If the actual number is within the range, the value would be F (means no probl... | determine a boolean value based on min and max value | right now I have min, max value from table1 that defines the range of a value. There is a boolean column in table2 of which the value is determined by the min and max value in table1. If the actual number is within the range, the value would be F (means no problem), and vice versa. after i ran my codes, only the first ... | [
"take notice the way range works in python...\n>>> range(1,5)\n[1, 2, 3, 4]\n>>>\n\nYou may be better off making your comparison statement:\nif record2 <= record1 <= record3:\nalso from what it looks like you are updating the entire table with your statement instead of the row of the records in your comparision. \n... | [
2,
0
] | [] | [] | [
"boolean",
"database",
"for_loop",
"python"
] | stackoverflow_0005277297_boolean_database_for_loop_python.txt |
Q:
QWebKit linkClicked signal never fires
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import QWebView
app = QApplication(sys.argv)
web_view = QWebView()
def url_changed(url): print 'url changed: ', url
def link_clicked(url): print 'link clicked: ', url
def load_started(): ... | QWebKit linkClicked signal never fires | import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import QWebView
app = QApplication(sys.argv)
web_view = QWebView()
def url_changed(url): print 'url changed: ', url
def link_clicked(url): print 'link clicked: ', url
def load_started(): print 'load started'
def load_finished(ok): ... | [
"The link delegation policy must be set appropriately for the linkClicked signal to be emitted.\nimport sys\n\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtWebKit import QWebPage, QWebView\n\napp = QApplication(sys.argv)\nweb_view = QWebView()\nweb_view.page().setLinkDelegationPolicy(QWebPage... | [
7
] | [] | [] | [
"pyqt",
"python",
"qt",
"qwebkit",
"qwebview"
] | stackoverflow_0005383032_pyqt_python_qt_qwebkit_qwebview.txt |
Q:
Gracefully recover from parse error in expat
XML is supposed to be strict, and so there are some Unicode characters which aren't allowed in XML. However I'm trying to work with RSS feeds which often contain these characters anyway, and I'd like to either avoid parse errors from invalid characters or recover gracef... | Gracefully recover from parse error in expat | XML is supposed to be strict, and so there are some Unicode characters which aren't allowed in XML. However I'm trying to work with RSS feeds which often contain these characters anyway, and I'd like to either avoid parse errors from invalid characters or recover gracefully from them and present the document anyway.
Se... | [
"Looks like that RSS feed contained a vertical tab character \\x0c which is illegal per the XML 1.0 spec.\nMy advice is to filter out the illegal characters before passing the data to expat, rather than attempting to catch errors and recover. Here is a routine to filter out the Unicode characters which are illegal... | [
4,
1
] | [] | [] | [
"expat_parser",
"parsing",
"python",
"unicode",
"xml"
] | stackoverflow_0005381577_expat_parser_parsing_python_unicode_xml.txt |
Q:
Cython correctness
Is code produced by Cython always just as correct as the Python code it was produced from?
It may help other readers to address the use of Cython static type declarations and other Cython features (if any), though I am only interested in the case of creating Cython files by renaming the Python m... | Cython correctness | Is code produced by Cython always just as correct as the Python code it was produced from?
It may help other readers to address the use of Cython static type declarations and other Cython features (if any), though I am only interested in the case of creating Cython files by renaming the Python modules to *.pyx.
I only ... | [
"Generally, yes. Of course there are bugs (many revolve around expanding the supported Python subset though, bugs that actually make generated C code incorrect are relatively rare), and there are a few necessary caveats (although it seems that only one item on that short list diverts from Python semantics).\nWhen y... | [
10
] | [] | [] | [
"correctness",
"cython",
"python"
] | stackoverflow_0005382028_correctness_cython_python.txt |
Q:
Singleton class in python
For a class in python how to implement singleton properties to it.Please provide an example for the following class.What i am basically trying to understand is that if an instance of the class exist then it should return the existing instance else create an instance of that class
class ... | Singleton class in python | For a class in python how to implement singleton properties to it.Please provide an example for the following class.What i am basically trying to understand is that if an instance of the class exist then it should return the existing instance else create an instance of that class
class Test:
name
age
... | [
"You should not implement singleton as a class. Use a module, that works great as a singleton.\nAlso: Is there a simple, elegant way to define singletons?\n",
"I personally wouldn't use a singleton design pattern on such a class, as with a singleton you are ensuring that there is, and only ever will be one of the... | [
7,
2
] | [] | [] | [
"python"
] | stackoverflow_0005383393_python.txt |
Q:
Python or Lua - Realtime application
I have started using Python in a real-time application (serial communication with to gps modules at once), but have found out recently about Lua. Which language would be more suited to the application?
My definition of real-time in this context is the fastest possible time to r... | Python or Lua - Realtime application | I have started using Python in a real-time application (serial communication with to gps modules at once), but have found out recently about Lua. Which language would be more suited to the application?
My definition of real-time in this context is the fastest possible time to receive, process and output the data. (Feed... | [
"Both are fine languages. Neither should take you years to learn. An easy way to make the decision is to look at what modules are out there already.\nFor example, you mentioned that your application is related to GPS. Take a look at what libraries are already written to hook Python and Lua into your particular GPS ... | [
7,
6
] | [] | [] | [
"lua",
"python"
] | stackoverflow_0005383145_lua_python.txt |
Q:
question about else statement...blackjack in python
Python newbie here. I'm trying to create a black jack game in which the user plays against the computer. I think where I'm having trouble is with the if, elif statements here. What I want to know is, what happens when none of the criteria of any of the if and e... | question about else statement...blackjack in python | Python newbie here. I'm trying to create a black jack game in which the user plays against the computer. I think where I'm having trouble is with the if, elif statements here. What I want to know is, what happens when none of the criteria of any of the if and elif statements are met when I don't have an else statemen... | [
"If none of the conditions are met then none of the conditionals in any of the if or elif blocks are executed. If it is ok that neither the computer or the player wins in a round, then it's fine. Otherwise you should include an else statement to cover that case.\n",
"If you don't have an else, the code will simpl... | [
2,
1,
0,
0
] | [] | [] | [
"blackjack",
"python"
] | stackoverflow_0005383194_blackjack_python.txt |
Q:
python wildcard import
Strange problem when importing modules:
File structure:
pages/
test.py
spawn.py
From spawn.py, if I do
from pages import test
everything works as expected.
If I do
from pages import *
I get
NameError: name 'test' is not defined
I don't get ImportError. I have commented out everythi... | python wildcard import | Strange problem when importing modules:
File structure:
pages/
test.py
spawn.py
From spawn.py, if I do
from pages import test
everything works as expected.
If I do
from pages import *
I get
NameError: name 'test' is not defined
I don't get ImportError. I have commented out everything but two lines of code. I ... | [
"You have to put import test in pages/__init__.py. \nJust because pages is a module does not mean it magically imports all the files in the same folder. You still have to name the modules you want to import (or write code that imports them automatically).\n",
"It matters because the pages/__init__.py contains the... | [
1,
0
] | [] | [] | [
"import",
"python",
"wildcard"
] | stackoverflow_0005384069_import_python_wildcard.txt |
Q:
How to parse a HTML page including hidden tags
I'm trying to parse some web pages for future use. For parsing webpages, I've used different modules like urllib, lxml, BeautifulSoup, HTMLParser to reach my goal.
I didn't meet any problem while parsing web pages until I faced the hidden tags.
When I opened the page... | How to parse a HTML page including hidden tags | I'm trying to parse some web pages for future use. For parsing webpages, I've used different modules like urllib, lxml, BeautifulSoup, HTMLParser to reach my goal.
I didn't meet any problem while parsing web pages until I faced the hidden tags.
When I opened the page with a chrome browser and used the developer tools ... | [
"This \"hidden\" code is probably generated by JavaScript at runtime.\nYou might have better luck finding out how the JavaScript works and where it gets its data (the URLs) than attempting to have something run the script and then parse the resulting DOM tree...\n"
] | [
1
] | [] | [] | [
"html",
"python"
] | stackoverflow_0005383623_html_python.txt |
Q:
Help for arrays: converting php code to python
For the first time this is not python => php but php => python.
I've got small problem with arrays in python.
(I've already been to docs.python.org)
Here's my problem:
I get in python couples of strings like this:
(People 1):
<criteria a> <data of the criteria>
<c... | Help for arrays: converting php code to python | For the first time this is not python => php but php => python.
I've got small problem with arrays in python.
(I've already been to docs.python.org)
Here's my problem:
I get in python couples of strings like this:
(People 1):
<criteria a> <data of the criteria>
<criteria b> <data of the criteria>
<criteria c> <da... | [
"In Python you have \"dictionaries\" instead of \"string indexed arrays\".\nTheir syntax is different than for arrays.\nYou can do\ndata = {}\ndata[\"people 1\"] = {}\ndata[\"people 1\"][\"criteria a\"] = \"bla\"\ndata[\"people 1\"][\"criteria b\"] = \"ble\"\ndata[\"people 2\"] = {}\n\n...\nYou can retrieve all co... | [
3,
0
] | [] | [] | [
"php",
"python"
] | stackoverflow_0005378227_php_python.txt |
Q:
MIME Header in message when sending e-mail with Python
So I am trying to send out an email using this template and using a log file as the body, the email gets sent fine. However, it has this really ugly header in the body of the message (As seen below)
From nobody Thu Mar 17 14:13:14 2011
Content-Type: text/plain... | MIME Header in message when sending e-mail with Python | So I am trying to send out an email using this template and using a log file as the body, the email gets sent fine. However, it has this really ugly header in the body of the message (As seen below)
From nobody Thu Mar 17 14:13:14 2011
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Enco... | [
"With MIMEText you have already created the message object. You just need to add the proper headers to it:\nFROM = \"my-username\"\nTO = [\"recipients\"]\nSUBJECT = \"Stereo log: %s\" % today\nfp = open(textfile, 'rb')\nTEXT = MIMEText(fp.read())\nfp.close()\nTEXT['From'] = FROM\nTEXT['To'] = \",\".join(TO)\nTEXT['... | [
2
] | [] | [] | [
"email",
"mime",
"python"
] | stackoverflow_0005380348_email_mime_python.txt |
Q:
Python unicode woes
What is the correct way to convert '\xbb' into a unicode string? I have tried the following and only get UnicodeDecodeError:
unicode('\xbb', 'utf-8')
'\xbb'.decode('utf-8')
A:
Since it comes from Word it's probably CP1252.
>>> print '\xbb'.decode('cp1252')
»
A:
It looks to be Latin-1 encod... | Python unicode woes | What is the correct way to convert '\xbb' into a unicode string? I have tried the following and only get UnicodeDecodeError:
unicode('\xbb', 'utf-8')
'\xbb'.decode('utf-8')
| [
"Since it comes from Word it's probably CP1252.\n>>> print '\\xbb'.decode('cp1252')\n»\n\n",
"It looks to be Latin-1 encoded. You should use:\nunicode('\\xbb', 'Latin-1')\n",
"Not sure what you are trying to do. But in Python3 all strings are unicode per default. In Python2.X you have to use u'my unicode string... | [
8,
1,
0
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0005384105_python_unicode.txt |
Q:
what _ means in expression: reprColor = [_("White"), _("Black")] and why it fails
There is a file const.py with lines like this:
reprColor = [ _("White"), _("Black")]
I got an error on this line:
NameError: name '_' is not defined<br>
What is the problem?
Environment: Python 2.7 / Windows XP
I have read that... | what _ means in expression: reprColor = [_("White"), _("Black")] and why it fails | There is a file const.py with lines like this:
reprColor = [ _("White"), _("Black")]
I got an error on this line:
NameError: name '_' is not defined<br>
What is the problem?
Environment: Python 2.7 / Windows XP
I have read that underscore is used as convention for private variables.
| [
"A single underscore is used as convention for one of the translation functions in gettext. Either bind it yourself, or call one of the install() functions or methods.\n",
"A _() call usually means GNU gettext is in use. It's for internationalization of strings.\n"
] | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0005384632_python.txt |
Q:
Why aren't bound instance methods in python reference equal?
>>> class foo(object):
... def test(s):
... pass
...
>>> a=foo()
>>> a.test is a.test
False
>>> print a.test
<bound method foo.test of <__main__.foo object at 0x1962b90>>
>>> print a.test
<bound method foo.test of <__main__.foo object at 0x19... | Why aren't bound instance methods in python reference equal? | >>> class foo(object):
... def test(s):
... pass
...
>>> a=foo()
>>> a.test is a.test
False
>>> print a.test
<bound method foo.test of <__main__.foo object at 0x1962b90>>
>>> print a.test
<bound method foo.test of <__main__.foo object at 0x1962b90>>
>>> hash(a.test)
28808
>>> hash(a.test)
28808
>>> id(a.tes... | [
"They're bound at runtime; accessing the attribute on the object rebinds the method anew each time. The reason they're different when you put both on the same line is that the first method hasn't been released by the time the second is bound.\n"
] | [
7
] | [] | [] | [
"equality",
"python",
"sentinel"
] | stackoverflow_0005384621_equality_python_sentinel.txt |
Q:
Python hex editor/editing component
I am looking for a hex editor or a hex editing component written in Python. So far, the only thing I have come up with is YaHEbwinPy, but it crashes with "pure virtual function call"
upon exit when I finally got it to run.
| Python hex editor/editing component | I am looking for a hex editor or a hex editing component written in Python. So far, the only thing I have come up with is YaHEbwinPy, but it crashes with "pure virtual function call"
upon exit when I finally got it to run.
| [] | [] | [
"Have you tried PSPad\n"
] | [
-1
] | [
"hex_editors",
"python"
] | stackoverflow_0004713344_hex_editors_python.txt |
Q:
Python instance string in a list
I have a simple class in python that has a __str__() function. Like this:
class Foo(object):
def __init__():
self.name = 'something'
def __str__():
return self.name
My real class does more than that, but this is an example.
So then I do this:
a = Foo()
b = Fo... | Python instance string in a list | I have a simple class in python that has a __str__() function. Like this:
class Foo(object):
def __init__():
self.name = 'something'
def __str__():
return self.name
My real class does more than that, but this is an example.
So then I do this:
a = Foo()
b = Foo()
print a
print b
print [a,b]
Exce... | [
"You need to add a __repr__ method as well:\nclass Foo(object):\n def __repr__(self):\n return str(self)\n\n def __str__(self):\n return self.name\n\nSee this question about the difference between __str__ and __repr__.\nNote also that you're missing the self arguments to the methods in your sample c... | [
4,
3
] | [] | [] | [
"class",
"python"
] | stackoverflow_0005385134_class_python.txt |
Q:
Slow python file I:O; Ruby runs better than this; Got the wrong language?
Please advise - I'm going to use this asa learning point. I'm a beginner.
I'm splitting a 25mb file into several smaller file.
A Kindly guru here gave me a Ruby sript. It works beautifully fast. So, in order to learn I mimicked it with a pyt... | Slow python file I:O; Ruby runs better than this; Got the wrong language? | Please advise - I'm going to use this asa learning point. I'm a beginner.
I'm splitting a 25mb file into several smaller file.
A Kindly guru here gave me a Ruby sript. It works beautifully fast. So, in order to learn I mimicked it with a python script. This runs like a three-legged cat (slow). I wonder if anyone can te... | [
"There are many reasons why your script is slow -- the main reason being that you reopen the outputfile for almost every line you write. Since the old file gets implicitly closed on opening a new one (due to Python garbage collection), the write buffer is flushed for every single line you write, which is quite exp... | [
6,
2,
0,
0
] | [] | [] | [
"python",
"regex",
"ruby",
"text"
] | stackoverflow_0005383817_python_regex_ruby_text.txt |
Q:
Finding file names (from a directory) in a file
I want to find if all the files of a certain type have been logged by my program. So essentially, I have a logfile with just the file names and then I use a function to run through the file to check if the file is present. Now the contents are huge but I did this in ... | Finding file names (from a directory) in a file | I want to find if all the files of a certain type have been logged by my program. So essentially, I have a logfile with just the file names and then I use a function to run through the file to check if the file is present. Now the contents are huge but I did this in a crude way. Unfortunately, it's not working properly... | [
"The problem is tha the lines in the file are read only in the first pass, and that a file object (i in your case) doesn't support the use of the in operator as you expect. You can change the code to something like:\nlines = open(\"all_output_logs\",\"r\").readlines()\nfor filename in locate(\"*.dll\"):\n for li... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0005385090_python.txt |
Q:
Access gtk.TreeIter inside render() Function of gtk.CellRenderer -- pygtk
I am trying to code the following: Two Columns. One contains a itemId, the other one contains a typeId. I want to render the itemId only when the typeId equals a specific value.
class IDRenderer(gtk.CellRendererText):
def __init__(self):... | Access gtk.TreeIter inside render() Function of gtk.CellRenderer -- pygtk | I am trying to code the following: Two Columns. One contains a itemId, the other one contains a typeId. I want to render the itemId only when the typeId equals a specific value.
class IDRenderer(gtk.CellRendererText):
def __init__(self):
gtk.CellRendererText.__init__(self)
def do_render(self,window, widget, ... | [
"I now found out, thanks to a nice guy on #pygtk on gimpIRC:\nYou can do that, with binding so called cell data functions to the corresponding gtk.TreeViewColumn as done here in this example\ndef renderId(celllayout, cell, model, iter):\n if model.get_value(iter,1) == 3:\n cell.set_property('visible',True)\n e... | [
2,
0
] | [] | [] | [
"cellrenderer",
"pygtk",
"python"
] | stackoverflow_0005331031_cellrenderer_pygtk_python.txt |
Q:
Python reading logfile with timestamp including microseconds
I've got a timestamp in a log file with the format like:
2010-01-01 18:48:14.631829
I've tried the usual suspects like strptime, and no matter what i do, I'm getting that it doesn't match the format I specify. ("%Y-%m-%d %H:%M:%S" OR "%Y-%m-%d %H:%M:%S.... | Python reading logfile with timestamp including microseconds | I've got a timestamp in a log file with the format like:
2010-01-01 18:48:14.631829
I've tried the usual suspects like strptime, and no matter what i do, I'm getting that it doesn't match the format I specify. ("%Y-%m-%d %H:%M:%S" OR "%Y-%m-%d %H:%M:%S.%f")
I've even tried splitting the value by "." so I can just comp... | [
"You can use strptime like so (Python 2.6+ only):\n>>> import datetime\n>>> s = \"2010-01-01 18:48:14.631829\"\n>>> datetime.datetime.strptime(s, \"%Y-%m-%d %H:%M:%S.%f\")\ndatetime.datetime(2010, 1, 1, 18, 48, 14, 631829)\n\nDocs: http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior\n\n...\n... | [
4,
0,
0
] | [] | [] | [
"datetime",
"python",
"time"
] | stackoverflow_0005385238_datetime_python_time.txt |
Q:
How do I compare dates in Django?
I have a Django model class with a class variable due_date:
due_date = models.DateField()
I want to output in the Django admin if the object is due or not based on today's date.
My function is as follows:
def is_due_today(self):
dd = self.due_date
today = datetime.date.no... | How do I compare dates in Django? | I have a Django model class with a class variable due_date:
due_date = models.DateField()
I want to output in the Django admin if the object is due or not based on today's date.
My function is as follows:
def is_due_today(self):
dd = self.due_date
today = datetime.date.now
return dd - today > 0
But my out... | [
"Subtracting two datetime objects in Python gives you a timedelta object, which you can't compare to an integer. You can, however, get something like total_seconds() from it to see if it's nonzero.\n>>> now = datetime.datetime.now()\n# wait 3 seconds\n>>> now2 = datetime.datetime.now()\n>>> td = now2 - now\n>>> td... | [
6,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005385344_django_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.