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:
regular expression to parse option string in python
I can't seem to create the correct regular expression to extract the correct tokens from my string. Padding the beginning of the string with a space generates the correct output, but seems less than optimal:
>>> import re
>>> s = '-edge_0triggered a-b | -level_Se... | regular expression to parse option string in python | I can't seem to create the correct regular expression to extract the correct tokens from my string. Padding the beginning of the string with a space generates the correct output, but seems less than optimal:
>>> import re
>>> s = '-edge_0triggered a-b | -level_Sensitive c-d | a-b-c'
>>> re.findall(r'\W(-[\w_]+)',' '+s)... | [
"Change the first qualifier to accept either a beginning anchor or a not-word, instead of only a not-word:\n>>> re.findall(r'(?:^|\\W)(-[\\w_]+)', s)\n['-edge_0triggered', '-level_Sensitive']\n\nThe ?: at the beginning of the group simply tells the regex engine to not treat that as a group for purposes of results.\... | [
1,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003019564_python_regex.txt |
Q:
exec: 23: python: not found error?
im trying to build android from source on ubuntu 10.04. when i enter the repo command:
repo init -u git://android.git.kernel.org/platform/manifest.git -b eclair
it get this error back
exec: 23: python: not found
any ideas.
A:
You should check your python instalation as the repo... | exec: 23: python: not found error? | im trying to build android from source on ubuntu 10.04. when i enter the repo command:
repo init -u git://android.git.kernel.org/platform/manifest.git -b eclair
it get this error back
exec: 23: python: not found
any ideas.
| [
"You should check your python instalation as the repo command is an python script made by Google to interact with git repositories.\nIf you do have python installed it is possible that it is not in your shell path or you are using a diferent version than required by repo, ie. you have version 3 while repo requires ... | [
0
] | [] | [] | [
"android",
"python"
] | stackoverflow_0003019742_android_python.txt |
Q:
how to import the parent model on gae-python
main:.
├─a
│ ├─__init__.py
│ └─aa.py
├─b
│ ├─__init__.py
│ └─bb.py
└─cc.py
if i am in aa.py , how to import cc.py ?
this is my code ,but it is error :
from main import cc
what should i do .
thanks
updated
in normal python file (not on gae),i can use th... | how to import the parent model on gae-python | main:.
├─a
│ ├─__init__.py
│ └─aa.py
├─b
│ ├─__init__.py
│ └─bb.py
└─cc.py
if i am in aa.py , how to import cc.py ?
this is my code ,but it is error :
from main import cc
what should i do .
thanks
updated
in normal python file (not on gae),i can use this code :
import os,sys
dirname=os.path.dirname
pa... | [
"I don't understand how the code you've shown can possibly be failing for you. Trying to reproduce your problem, I built the following pared-to-the-bone project:\n$ ls -lR\ntotal 32\n-rw-r--r-- 1 aleax staff 0 Jun 10 21:20 __init__.py\ndrwxr-xr-x 4 aleax staff 136 Jun 10 21:28 a\n-rw-r-----@ 1 aleax staff... | [
0
] | [] | [] | [
"google_app_engine",
"import",
"model",
"parent",
"python"
] | stackoverflow_0003019944_google_app_engine_import_model_parent_python.txt |
Q:
to overcome type error?
i have a file of this format:
3.334 1
2.345 1
1.453 1
3.343 1
and so on
but in middle at times in file there are few number which are not in float format and i receive type msg when i run them performation some operation..
I want to give a condition that:
if(not in float format):
continu... | to overcome type error? | i have a file of this format:
3.334 1
2.345 1
1.453 1
3.343 1
and so on
but in middle at times in file there are few number which are not in float format and i receive type msg when i run them performation some operation..
I want to give a condition that:
if(not in float format):
continue
else:
perform operation
... | [
"You can use an exception handler:\ntry:\n f = float(thing)\nexcept ValueError:\n # This is not a float\n f = 0.0\n\nValueError is thrown by invalid conversions. You should have seen it in your application traceback when an invalid float value conversion was tried.\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0003020375_python.txt |
Q:
Why does "as" cause a SyntaxError in an "except" statement in Jython 2.5?
I got the following syntax error at the following line when I run my program in jython:
except Exception as detail:
SyntaxError: mismatched input 'as' expecting COLON
but on python is it ok? What is wrong? I am trying to use the stanford po... | Why does "as" cause a SyntaxError in an "except" statement in Jython 2.5? | I got the following syntax error at the following line when I run my program in jython:
except Exception as detail:
SyntaxError: mismatched input 'as' expecting COLON
but on python is it ok? What is wrong? I am trying to use the stanford pos tagger api (java) in my python program. Are there other ways?
| [
"There are 2 current versions of Jython: the 2.5 version is the stable one, and 2.7 is a release candidate. The as syntax for except appeared in CPython 2.6 and thus will be supported in Jython 2.7; I guess you're using Jython 2.5,\nYou can use the older (Python 3 incompatible) except syntax in Jython 2.5:\nexcept... | [
15
] | [] | [] | [
"jython",
"python",
"python_2.x"
] | stackoverflow_0003020966_jython_python_python_2.x.txt |
Q:
Problem about python import with error
I have write a small python module with one class and two functions. The skeleton of the module is as following:
#file name: test_module.py
class TestClass:
@classmethod
def method1(cls, param1):
#to do something
pass
def __init__(self, param1):
#to do some... | Problem about python import with error | I have write a small python module with one class and two functions. The skeleton of the module is as following:
#file name: test_module.py
class TestClass:
@classmethod
def method1(cls, param1):
#to do something
pass
def __init__(self, param1):
#to do something
...
def fun1(*params):
#to do so... | [
"Add a proper shebang line to your \"small script\". It's being interpreted as a shell script.\n"
] | [
3
] | [] | [] | [
"import",
"python"
] | stackoverflow_0003021010_import_python.txt |
Q:
Comparing two large sets of attributes
Suppose you have a Django view that has two functions:
The first function renders some XML using a XSLT stylesheet and produces a div with 1000 subelements like this:
<div id="myText">
<p id="p1"><a class="note-p1" href="#" style="display:none" target="bot">✽</a></strong... | Comparing two large sets of attributes | Suppose you have a Django view that has two functions:
The first function renders some XML using a XSLT stylesheet and produces a div with 1000 subelements like this:
<div id="myText">
<p id="p1"><a class="note-p1" href="#" style="display:none" target="bot">✽</a></strong>Lorem ipsum</p>
<p id="p2"><a class="no... | [
"How about something like this:\nhttp://jsfiddle.net/9eXws/\n$('#myText a').each(function() {\n $(\"#myNotes .\" + $(this).attr('class')).show();\n});\n\nInstead of doing an inner each, it simply appends the class for the current a element into the selector, and performs a show() on any items found.\n",
"For ... | [
1,
1,
0,
0
] | [] | [] | [
"django",
"jquery",
"python",
"xml"
] | stackoverflow_0003017714_django_jquery_python_xml.txt |
Q:
PyQt4 Move QTableWidget row with widgets
I have the following method in my PyQt4 app. r2 is the number of row to move, and r1 is the position where it should be moved. To clarify: the table is filled with cellWidgets, not widgetItems.
def move_row(self, r1, r2):
tt = self.tableWidget
tt.insertRow(r1)
f... | PyQt4 Move QTableWidget row with widgets | I have the following method in my PyQt4 app. r2 is the number of row to move, and r1 is the position where it should be moved. To clarify: the table is filled with cellWidgets, not widgetItems.
def move_row(self, r1, r2):
tt = self.tableWidget
tt.insertRow(r1)
for c in range(tt.columnCount()):
tt.se... | [
"I finally ended up with widgets values copying.\n"
] | [
1
] | [] | [] | [
"pyqt",
"pyqt4",
"python"
] | stackoverflow_0002964482_pyqt_pyqt4_python.txt |
Q:
send xml file to http using python
how can i send an xml file on my system to an http server using python standard library??
A:
import urllib
URL = "http://host.domain.tld/resource"
XML = "<xml />"
parameter = urllib.urlencode({'XML': XML})
a) using HTTP POST
response = urllib.urlopen(URL, parameter)
print... | send xml file to http using python | how can i send an xml file on my system to an http server using python standard library??
| [
"import urllib\n\nURL = \"http://host.domain.tld/resource\"\nXML = \"<xml />\"\n\nparameter = urllib.urlencode({'XML': XML})\n\na) using HTTP POST \nresponse = urllib.urlopen(URL, parameter)\nprint response.read()\n\nb) using HTTP GET\nresponse = urllib.urlopen(URL + \"?%s\" % parameter)\nprint response.read()\n\... | [
9,
1
] | [] | [] | [
"http",
"python",
"xml"
] | stackoverflow_0003020979_http_python_xml.txt |
Q:
wav file manupalation
I want get the details of the wave such as its frames into a array of integers.
Using fname.getframes we can ge the properties of the frame and save in list or anything for writing into another wav or anything,but fname.getframes gives information not in integers some thing like a "/xt/x4/0w'... | wav file manupalation | I want get the details of the wave such as its frames into a array of integers.
Using fname.getframes we can ge the properties of the frame and save in list or anything for writing into another wav or anything,but fname.getframes gives information not in integers some thing like a "/xt/x4/0w' etc..
But i want them in i... | [
"I don't know what library you're using, but it looks like it's probably returning a string of bytes. To get it into a list of integers, you could do something like this:\ndata = [ord(character) for character in data]\n\nTo convert it back, you could do something like this:\ndata = ''.join(chr(character) for charac... | [
1,
1,
0
] | [] | [] | [
"python",
"wav"
] | stackoverflow_0003021046_python_wav.txt |
Q:
Help me sort programming languages a bit
so I asked here few days ago about C# and its principles. Now, if I may, I have some additional general questions about some languages, because for novice like me, it seems a bit confusing. To be exact I want to ask more about language functions capabilities than syntax and... | Help me sort programming languages a bit | so I asked here few days ago about C# and its principles. Now, if I may, I have some additional general questions about some languages, because for novice like me, it seems a bit confusing. To be exact I want to ask more about language functions capabilities than syntax and so.
To be honest, its just these special func... | [
"C is portable. That means that on different systems the assembler output for printf will be different... this is something the compiler does based on what your target system is. Write C code and compile as a Linux app and the output will be different than as a Win32 app, and also different than if you compile the ... | [
2,
2,
1,
1,
0
] | [
"\nTo be more specific, I know they are similiar to java and C# in term they are compiled into \n bytecode.\n\nRuby and Python are both interpreted languages, http://en.wikipedia.org/wiki/Interpreted_language, and their code is not translated into bytecode prior the execution.\n"
] | [
-2
] | [
"c",
"programming_languages",
"python",
"ruby"
] | stackoverflow_0003021652_c_programming_languages_python_ruby.txt |
Q:
Defining the hash of an object as the sum of hashes of its members
I have a class that represents undirected edges in a graph. Every edge has two members vertex1 and vertex2 representing the vertices it connects. The problem is, that an edge can be specified two directions. My idea was now to define the hash of an... | Defining the hash of an object as the sum of hashes of its members | I have a class that represents undirected edges in a graph. Every edge has two members vertex1 and vertex2 representing the vertices it connects. The problem is, that an edge can be specified two directions. My idea was now to define the hash of an edge as the sum of the hashes of its vertices. This way, the direction ... | [
"I have had to solve a similar problem and found that using the sum of hashes as a hash results in too many collisions. The distribution of the sum of hashes is just not spread out enough. \nI found that using the product of hashes resulted in much less collisions. This of course depends on the nature of the has... | [
3
] | [] | [] | [
"hash",
"python"
] | stackoverflow_0003021868_hash_python.txt |
Q:
using remove on nested lists
n=[['dgd','sd','gsg'],['fsdsdf','sds','sdf']]
>>> n.remove('sd')
if i have a nested list like above and want to remove 'sd'.how can i doing the above thing is giving an error??
A:
n[0].remove('sd')
or
for i in n:
try:
i.remove('sd')
except ValueError:
pass
A:
When you... | using remove on nested lists | n=[['dgd','sd','gsg'],['fsdsdf','sds','sdf']]
>>> n.remove('sd')
if i have a nested list like above and want to remove 'sd'.how can i doing the above thing is giving an error??
| [
"n[0].remove('sd')\n\nor\nfor i in n:\n try:\n i.remove('sd')\n except ValueError:\n pass\n\n",
"When you have nested lists you need to index the top level list to get to the child lists, only then can you use list operations on the child lists. So you need something like:\nn[0].remove('sd')\n\nThe code y... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003021167_python.txt |
Q:
MySQL Module for Python
What is a good, and easy to install MySQL module for Python? Especially for Mac OS X (in terms of installation)?
A:
I think you should consider to install MacPorts, it will save time for this case and in the future.
Installing py-mysql is a matter of:
sudo port install py-mysql
| MySQL Module for Python | What is a good, and easy to install MySQL module for Python? Especially for Mac OS X (in terms of installation)?
| [
"I think you should consider to install MacPorts, it will save time for this case and in the future.\nInstalling py-mysql is a matter of:\nsudo port install py-mysql\n\n"
] | [
1
] | [] | [] | [
"module",
"mysql",
"python",
"sql"
] | stackoverflow_0003022080_module_mysql_python_sql.txt |
Q:
What's a better choice for SQL-backed number crunching - Ruby 1.9, Python 2, Python 3, or PHP 5.3?
Criteria for 'better': fast in math and simple (few fields, many records) db transactions, convenient to develop/read/extend, flexible, connectible.
The task is to use a common web development scripting language to p... | What's a better choice for SQL-backed number crunching - Ruby 1.9, Python 2, Python 3, or PHP 5.3? | Criteria for 'better': fast in math and simple (few fields, many records) db transactions, convenient to develop/read/extend, flexible, connectible.
The task is to use a common web development scripting language to process and calculate long time series and multidimensional surfaces (mostly selecting/inserting sets of ... | [
"I would suggest Python with it's great Scientifical/Mathematical libraries (SciPy, NumPy). Otherwise the languages are not differing so much, although I doubt that Ruby, PHP or JS can keep up with the speed of Python or Perl.\nAnd what the comments below here say: at this moment, go for the latest Python2 (which i... | [
10,
4
] | [] | [] | [
"math",
"performance",
"php",
"python",
"ruby"
] | stackoverflow_0003022232_math_performance_php_python_ruby.txt |
Q:
working on django development server but not on apache
i am facing an issue with the apache server, we have written the code, in which if the url entered in the form field is valid it will display an error message, when i run the code through django developement server it works fine, displays the error message, bu... | working on django development server but not on apache | i am facing an issue with the apache server, we have written the code, in which if the url entered in the form field is valid it will display an error message, when i run the code through django developement server it works fine, displays the error message, but when running through apache, then does not show the error ... | [
"hey guys, thanks for the support, the issue is resolved, i did it this way.\ndef showAddRecipe(request):\n #global objc\n if \"userid\" in request.session:\n objc[\"ErrorMsgURL\"]= \"\"\n try:\n urlList= request.POST\n URL= str(urlList['url'])\n URL= URL.strip('... | [
1
] | [] | [] | [
"apache",
"django",
"python",
"url"
] | stackoverflow_0003021418_apache_django_python_url.txt |
Q:
Web application architecture, and application servers?
I'm building a web application, and I need to use an architecture that allows me to run it over two servers. The application scrapes information from other sites periodically, and on input from the end user. To do this I'm using Php+curl to scrape the informa... | Web application architecture, and application servers? | I'm building a web application, and I need to use an architecture that allows me to run it over two servers. The application scrapes information from other sites periodically, and on input from the end user. To do this I'm using Php+curl to scrape the information, Php or python to parse it and store the results in a M... | [
"\nHow do go about implementing this? \n\nToo big a question for an answer here. Certainly you don't want 2 sets of code for the scraping (1 for scheduled, 1 for demand) in addition to the added complication, you really don't want to be running job which will take an indefinite time to complete within the thread ge... | [
2,
1
] | [] | [] | [
"application_server",
"cakephp",
"model_view_controller",
"php",
"python"
] | stackoverflow_0003021921_application_server_cakephp_model_view_controller_php_python.txt |
Q:
Get table with maximum number of rows in a page using BeautifulSoup
Can anyone tell me how i can get the table in a HTML page which has a the most rows? I'm using BeautifulSoup.
There is one little problem though. Sometimes, there seems to be one table nested inside another.
<table>
<tr>
<td>
... | Get table with maximum number of rows in a page using BeautifulSoup | Can anyone tell me how i can get the table in a HTML page which has a the most rows? I'm using BeautifulSoup.
There is one little problem though. Sometimes, there seems to be one table nested inside another.
<table>
<tr>
<td>
<table>
<tr>
<td></td>
... | [
"Calculate number_of_rows like that:\nnumber_of_rows = len(table.findAll(lambda tag: tag.name == 'tr' and tag.findParent('table') == table))\n\n"
] | [
3
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0003020841_beautifulsoup_python.txt |
Q:
Python Application in right click menu of OS X
I know that there is the PyObjC bridge is OSX and what I want to do is to put a python application/script in the rightclick context menu of OS X. there is the OnMyCommand plugin but I dont think that supports python. I've had a look at how to do it in Carbon/ Objectiv... | Python Application in right click menu of OS X | I know that there is the PyObjC bridge is OSX and what I want to do is to put a python application/script in the rightclick context menu of OS X. there is the OnMyCommand plugin but I dont think that supports python. I've had a look at how to do it in Carbon/ Objective-C and i'll admit it im a wuss and am just not smar... | [
"Looking through the documentation for OnMyCommand (neat find by the way) I would say you shouldn't have any problem using a Python script. Just make sure the Python script is executable and in your PATH.\nGoing along with the example in 1, instead of executing touch you would simply execute your Python script.\n"
... | [
1
] | [] | [] | [
"macos",
"objective_c",
"python"
] | stackoverflow_0003022691_macos_objective_c_python.txt |
Q:
Can Python ctypes load a 32bit C library on x86-64?
I have a 64 bit RHEL host with 32 bit libraries installed. One vendor has a 32 bit .so I'd like to load into Python using ctypes.
from ctypes import CDLL
CDLL('32bitdinosaur.so')
OSError: 32bitdinosaur.so: wrong ELF class: ELFCLASS32
Of... | Can Python ctypes load a 32bit C library on x86-64? | I have a 64 bit RHEL host with 32 bit libraries installed. One vendor has a 32 bit .so I'd like to load into Python using ctypes.
from ctypes import CDLL
CDLL('32bitdinosaur.so')
OSError: 32bitdinosaur.so: wrong ELF class: ELFCLASS32
Of course 64 bit libraries are OK. Eg:
CDLL('libc.so.6')
W... | [
"It looks like the best way to do this is to have a 32 bit python in a separate process load the .so, and call the 32 bit python from a 64 bit Python.\n"
] | [
1
] | [] | [] | [
"32bit_64bit",
"ctypes",
"python"
] | stackoverflow_0003015970_32bit_64bit_ctypes_python.txt |
Q:
Python equivalent of C++ getline()
In C++ we can enter multiple lines by giving our own choice of delimiting character in the getline() function.. however I am not able to do the same in Python!! it has only raw_input() and sys.stdin.readline() methods that read till I press enter. Is there any way to customize th... | Python equivalent of C++ getline() | In C++ we can enter multiple lines by giving our own choice of delimiting character in the getline() function.. however I am not able to do the same in Python!! it has only raw_input() and sys.stdin.readline() methods that read till I press enter. Is there any way to customize this so that I can specify my own delimite... | [
"Do you still want to press enter to create multiple lines? How do you end the input? Or do you want do specify multiple lines on a single line? \nIf the former, try looping raw_input() until something is written that tells it to stop:\nlines = []\nwhile True:\n user_input = raw_input()\n if user_input.strip(... | [
3,
2,
0
] | [] | [] | [
"c++",
"getline",
"python"
] | stackoverflow_0003022572_c++_getline_python.txt |
Q:
Launch an SWF full screen
I have a swf file (a flash game). I want to run some script to open it in full-screen mode. I'm not attached to any browser, but I do run Linux, so a bash, or generic answer is what I'm looking for. I'm also open to building a lite browser application if need-be.
A:
The SWF can be launc... | Launch an SWF full screen | I have a swf file (a flash game). I want to run some script to open it in full-screen mode. I'm not attached to any browser, but I do run Linux, so a bash, or generic answer is what I'm looking for. I'm also open to building a lite browser application if need-be.
| [
"The SWF can be launched in full screen in several ways, here comes some suggested solutions:\n1) You can open the SWF-file directly (works for me, in Firefox).\n2) You can add a HTML page with this JavaScript that redirects to your SWF-file.\n<script language=\"JavaScript\" type=\"text/javascript\">\n document.... | [
1,
0
] | [] | [] | [
"bash",
"browser",
"firefox",
"flash",
"python"
] | stackoverflow_0002889561_bash_browser_firefox_flash_python.txt |
Q:
How to create temporary files in memory visible for other process, using python
I'm trying to write simple batch file generator in python. Batch file consist of about 30-50 lines of text and is passed to other applications. During the execution of script there a lot of calls to external applications. I want to cre... | How to create temporary files in memory visible for other process, using python | I'm trying to write simple batch file generator in python. Batch file consist of about 30-50 lines of text and is passed to other applications. During the execution of script there a lot of calls to external applications. I want to create file in memory (like named pipes in win32). Is there any platform-independent way... | [
"If you don't mind running a separate server, I'd use Memcached. It's very simple to use and very robust.\nhttp://memcached.org/\n"
] | [
0
] | [] | [] | [
"memory",
"python",
"temporary_files"
] | stackoverflow_0003023438_memory_python_temporary_files.txt |
Q:
Python win32com - Automating Word - How to replace text in a text box?
I'm trying to automate word to replace text in a word document using Python. (I'm on word 2003 if that matters and Python 2.4)
The first part of my replace method below works on everything except text in text boxes. The text just doesn't get ... | Python win32com - Automating Word - How to replace text in a text box? | I'm trying to automate word to replace text in a word document using Python. (I'm on word 2003 if that matters and Python 2.4)
The first part of my replace method below works on everything except text in text boxes. The text just doesn't get selected. I notice when I go into Word manually and hit ctrl-A all of the t... | [
"When I add text boxes to a word document, they are added inside a drawing canvas. Therefore the top level shape is the canvas, and the text boxes are contained within the canvas. You should use the CanvasItems method to access the objects in the canvas, ie the text boxes\nThe following example works for me. I crea... | [
5
] | [] | [] | [
"ms_word",
"python",
"vba",
"win32com"
] | stackoverflow_0003022898_ms_word_python_vba_win32com.txt |
Q:
How to define multi-argument decorators within a class in 2.6
Generally don't do OO-programming in Python. This project requires it and am running into a bit of trouble. Here's my scratch code for attempting to figure out where it went wrong:
class trial(object):
def output( func, x ):
def ya( self, ... | How to define multi-argument decorators within a class in 2.6 | Generally don't do OO-programming in Python. This project requires it and am running into a bit of trouble. Here's my scratch code for attempting to figure out where it went wrong:
class trial(object):
def output( func, x ):
def ya( self, y ):
return func( self, x ) + y
return ya
d... | [
"There's no need for your method decorators to be a part of the class:\ndef output(meth, x):\n def ya(self, y):\n return meth(self, x) + y\n return ya\n\ndef f1(meth):\n return output(meth, 1)\n\nclass trial(object):\n @f1\n def sum1( self, x ):\n return x\n\n>>> trial().sum1(1)\n2\n\nI... | [
5,
0
] | [
"No way. \nThis is a wrong design. \nFollow for The Zen of Python\nWhen you decorate a function calling the decorator by @ it must be already defined.\nYou must at first - define decorator and at the second step decorate a function.\n"
] | [
-2
] | [
"decorator",
"python"
] | stackoverflow_0003023448_decorator_python.txt |
Q:
How to process user supplied formulas?
I have a dictionary containing a set of key values available through a web application:
I want to process user supplied formulas like:
((value1+value3)/value4)*100
What would be the easiest way to get the formula calculated matching values with ones from the dictionary?
Consi... | How to process user supplied formulas? | I have a dictionary containing a set of key values available through a web application:
I want to process user supplied formulas like:
((value1+value3)/value4)*100
What would be the easiest way to get the formula calculated matching values with ones from the dictionary?
Consider this example:
#!/usr/bin/python
values={... | [
"eval can be used execute malicious code.\nDo you trust your users? If so, you can pass values along as a global dict to be used by eval. Thus, eval can evaluate the user formula directly without any additional string manipulation:\nvalues={'value1':10,'value2':1245,'value3':674365,'value4':65432,'value5':131}\nfor... | [
6,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003022414_python.txt |
Q:
How to store password on gae properly when someone registers?
For example:
username:zjm1126
password:11
I store the password to the datastore on gae. When I see the data view at /_ah/admin, I can see the password of all people that have registered.
Is it safe to do so? If not, how to store it properly?
And the ch... | How to store password on gae properly when someone registers? | For example:
username:zjm1126
password:11
I store the password to the datastore on gae. When I see the data view at /_ah/admin, I can see the password of all people that have registered.
Is it safe to do so? If not, how to store it properly?
And the check_password method is:
user=MyUser.get_by_key_name(self.request.ge... | [
"You should never store a password in plain text.\nUse a ir-reversable data hashing algorithm, like sha or md5\nHere is how you can create a hash in python:\nfrom hashlib import sha256\nfrom random import random\nrandom_key = random()\nsha256('%s%s%s'%('YOUR SECRET KEY',random_key,password))\n\nYou should also stor... | [
10,
2,
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"passwords",
"python"
] | stackoverflow_0003022366_google_app_engine_google_cloud_datastore_passwords_python.txt |
Q:
How to list all the objects with a specific date no matter the time in a DateTime Field
I Have a model like this
foo=models.char
bar=models.dateime
In wich several foos arrives in one day in different time. I need to list all the foos in a specific date, no matter the time they arrive.
I can't change the model, s... | How to list all the objects with a specific date no matter the time in a DateTime Field | I Have a model like this
foo=models.char
bar=models.dateime
In wich several foos arrives in one day in different time. I need to list all the foos in a specific date, no matter the time they arrive.
I can't change the model, so splitting the bar in two fields(one for date and one for time) is out of reach right now :(... | [
"I personally used the range filter and the internal datetime timestamps for max/min. For example:\ndate = datetime.date.today()\nYourModel.objects.filter(bar__range=(\n datetime.datetime.combine(\n date,\n ... | [
2,
0
] | [] | [] | [
"date",
"datetime",
"django",
"orm",
"python"
] | stackoverflow_0003023913_date_datetime_django_orm_python.txt |
Q:
How to merge or copy anonymous session data into user data when user logs in?
This is a general question, or perhaps a request for pointers to other open source projects to look at:
I'm wondering how people merge an anonymous user's session data into the authenticated user data when a user logs in. For example, so... | How to merge or copy anonymous session data into user data when user logs in? | This is a general question, or perhaps a request for pointers to other open source projects to look at:
I'm wondering how people merge an anonymous user's session data into the authenticated user data when a user logs in. For example, someone is browsing around your websites saving various items as favourites. He's not... | [
"If very much depends on your system ofcourse. But personally I always try to merge the data and immediately store it in the same way as it would be stored as when the user would be logged in.\nSo if you store it in a session for an anonymous user and in the database for any authenticated user. Just merge all data ... | [
1
] | [] | [] | [
"e_commerce",
"python",
"session",
"web.py"
] | stackoverflow_0003024191_e_commerce_python_session_web.py.txt |
Q:
Finding a list of indices from master array using secondary array with non-unique entries
I have a master array of length n of id numbers that apply to other analogous arrays with corresponding data for elements in my simulation that belong to those id numbers (e.g. data[id]). Were I to generate a list of id numbe... | Finding a list of indices from master array using secondary array with non-unique entries | I have a master array of length n of id numbers that apply to other analogous arrays with corresponding data for elements in my simulation that belong to those id numbers (e.g. data[id]). Were I to generate a list of id numbers of length m separately and need the information in the data array for those ids, what is the... | [
"The current way you are doing it with where searching through the whole array of a each time. You can make this look-up O(1) instead of O(N) using a dict. For instance, I used the following method:\ndef method2(a,b):\n tmpdict = dict(zip(a,range(len(a))))\n idx = numpy.array([tmpdict[bi] for bi in b])\n\nand... | [
1,
0
] | [] | [] | [
"indexing",
"numpy",
"python"
] | stackoverflow_0003024353_indexing_numpy_python.txt |
Q:
Search for a String and replace it with a variable
I am trying to use regular expression to search a document fo a UUID number and replace the end of it with a new number. The code I have so far is:
read_file = open('test.txt', 'r+')
write_file = open('test.txt', 'w')
r = re.compile(r'(self.uid\s*=\s*5EFF837F-EFC... | Search for a String and replace it with a variable | I am trying to use regular expression to search a document fo a UUID number and replace the end of it with a new number. The code I have so far is:
read_file = open('test.txt', 'r+')
write_file = open('test.txt', 'w')
r = re.compile(r'(self.uid\s*=\s*5EFF837F-EFC2-4c32-A3D4\s*)(\S+)')
for l in read_file:
m1 = r.ma... | [
"Why are you using a regex for such a straight forward substitution?\nCouldn't you just use\nfor l in read_file:\n l.replace(\"5EFF837F-EFC2-4c32-A3D4-D15C7F9E1F22\",\n \"5EFF837F-EFC2-4c32-A3D4-RHUI5345JO\")\n # Write to file..\n\nor is there more to the story than you're telling us? Also, unles... | [
3,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003024331_python_regex.txt |
Q:
How do I get python to load .NET .dlls referenced by mixed mode .dlls?
I have a python .pyd that is a mixed mode C++ DLL. The DLL loads fine and loads unmanaged C++ dlls without a problem, but when it tries to load the .NET dlls referenced by the managed C++ dlls it fails with this error message:
Unhandled Except... | How do I get python to load .NET .dlls referenced by mixed mode .dlls? | I have a python .pyd that is a mixed mode C++ DLL. The DLL loads fine and loads unmanaged C++ dlls without a problem, but when it tries to load the .NET dlls referenced by the managed C++ dlls it fails with this error message:
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly '...'
... | [
"I think I've resolved the problem. Assembly loading doesn't use the path set by SetDllDirectory(), and it looks like Python calls this function. By registering a delegate for the event AppDomain.AssemblyResolve(), I can catch the name of the dll that failed, append it to the directory obtained from GetDllDirecto... | [
1,
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0002970681_python_windows.txt |
Q:
Tkinter Spinbox Widget
How do I do a command that will set the default value on a Tkinter spinbox widget?
For some reason they didn't give it the attribute .set()
A:
Maybe you're looking for the "insert" command?
The following example sets the value to 2:
Tkinter.Spinbox(values=(1,2,3,4))
sb.delete(0,"end")
sb.... | Tkinter Spinbox Widget | How do I do a command that will set the default value on a Tkinter spinbox widget?
For some reason they didn't give it the attribute .set()
| [
"Maybe you're looking for the \"insert\" command?\nThe following example sets the value to 2:\nTkinter.Spinbox(values=(1,2,3,4))\nsb.delete(0,\"end\")\nsb.insert(0,2)\n\n"
] | [
2
] | [] | [] | [
"python",
"set",
"tkinter",
"widget"
] | stackoverflow_0003019800_python_set_tkinter_widget.txt |
Q:
how to make a python or perl script portable to both linux and windows?
I was wondering how to make a python script portable to both linux and windows?
One problem I see is shebang. How to write the shebang so that the script can be run on both windows and linux?
Are there other problems besides shebang that I sh... | how to make a python or perl script portable to both linux and windows? | I was wondering how to make a python script portable to both linux and windows?
One problem I see is shebang. How to write the shebang so that the script can be run on both windows and linux?
Are there other problems besides shebang that I should know?
Is the solution same for perl script?
Thanks and regards!
| [
"Windows will just ignore the shebang (which is, after all, a comment); in Windows you need to associate the .py extension to the Python executable in the registry, but you can perfectly well leave the shebang on, it will be perfectly innocuous there.\nThere are many bits and pieces which are platform-specific (man... | [
14,
7,
2,
2
] | [] | [] | [
"cross_platform",
"perl",
"python",
"scripting",
"shebang"
] | stackoverflow_0003020267_cross_platform_perl_python_scripting_shebang.txt |
Q:
Making pygtksourceview work in windows
So, I'm trying to get gtksourceview python bindings work under windows (I'm developing a cross platform gtk application that shows code, so gtksourceview seemed like a natural choice).
I have pygtk installed and working (I followed the instructions in http://www.pygtk.org/dow... | Making pygtksourceview work in windows | So, I'm trying to get gtksourceview python bindings work under windows (I'm developing a cross platform gtk application that shows code, so gtksourceview seemed like a natural choice).
I have pygtk installed and working (I followed the instructions in http://www.pygtk.org/downloads.html)
I tried the instructions in htt... | [
"So in case anyone else is wondering -- I grabbed the wrong libxml dll. The right one is in:\nhttp://ftp.gnome.org/pub/GNOME/binaries/win32/dependencies/libxml2_2.7.7-1_win32.zip\n"
] | [
2
] | [] | [] | [
"gtk",
"pygtk",
"python",
"windows"
] | stackoverflow_0002968273_gtk_pygtk_python_windows.txt |
Q:
How to create a HTML world map with GeoDjango?
The GeoDjango tutorial explains how to insert world borders into a spatial database.
I would like to create a world Map in HTML with these data, with both map and area tags. Something like that.
I just don't know how to retrieve the coordinates for each country (requi... | How to create a HTML world map with GeoDjango? | The GeoDjango tutorial explains how to insert world borders into a spatial database.
I would like to create a world Map in HTML with these data, with both map and area tags. Something like that.
I just don't know how to retrieve the coordinates for each country (required for the area's coords attribute).
from world.mod... | [
"In the worldborders example, the attribute mpoly is where the geographic polygon is actually stored.\nIn your example, you're going to want to access v.mpoly\nYou're not going to be able to use it directly however because mpoly is itself a MultiPolygon field. Consider a country like Canada that has a bunch of isla... | [
0,
0
] | [] | [] | [
"django",
"geodjango",
"gis",
"html",
"python"
] | stackoverflow_0002981450_django_geodjango_gis_html_python.txt |
Q:
Python as an end user script in a python app
I have an app written in python. I want to give my users the ability to manipulate the apps objects by allowing them to run their own scripts. They are likely to make errors in their scripts. If there is an error I want to ensure that the app doesn't stop running. I'd l... | Python as an end user script in a python app | I have an app written in python. I want to give my users the ability to manipulate the apps objects by allowing them to run their own scripts. They are likely to make errors in their scripts. If there is an error I want to ensure that the app doesn't stop running. I'd like to embed a debugger in my app to help them deb... | [
"I would suggest you use a separate interpreter instance (separate python process) to evaluate user's scripts. This will guarantee that whatever breaks in the user script would never affect you application. You can run external processes using os module, this would be one way to do so: http://docs.python.org/librar... | [
3,
1
] | [] | [] | [
"extensibility",
"python"
] | stackoverflow_0003025031_extensibility_python.txt |
Q:
Any simple frameworks for pagination in App Engine?
I want to find a framework for pagination in Google App Engine.
Do you know of one?
A:
If you want to do paging you should read about cursors.
The article linked to by Jason was written before cursors were around. Cursors can simplify paging greatly, especial... | Any simple frameworks for pagination in App Engine? | I want to find a framework for pagination in Google App Engine.
Do you know of one?
| [
"If you want to do paging you should read about cursors.\nThe article linked to by Jason was written before cursors were around. Cursors can simplify paging greatly, especially in cases that Andrew mentions, when dealing with sorts and filters.\n",
"Pagination is not always easy-to-do, especially when you consi... | [
3,
2
] | [] | [] | [
"google_app_engine",
"pagination",
"python"
] | stackoverflow_0003011352_google_app_engine_pagination_python.txt |
Q:
Appengine backreferences - need composite index?
I have a query that is very recently starting to throw:
"The built-in indices are not efficient enough for this query and your data. Please add a composite index for this query."
I checked the line on which this exception is being thrown, and the problem query is t... | Appengine backreferences - need composite index? | I have a query that is very recently starting to throw:
"The built-in indices are not efficient enough for this query and your data. Please add a composite index for this query."
I checked the line on which this exception is being thrown, and the problem query is this one:
count = self.vote_set.filter("direction =", 1... | [
"The backreferences actually just construct a query that's filtered on the reference property, so by adding another filter you have a 2-filter query. \nYour compsite index would look something like:\n- kind: Vote\n properties:\n - name: your_reference_property_name\n - name: direction\n direction: desc\n\n",... | [
3,
3
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003025018_google_app_engine_google_cloud_datastore_python.txt |
Q:
Google App Engine - update_indexes error
I have a Java app deployed on app engine and I use appcfg.py of the
Python SDK to vacuum and update my indexes.
Yesterday I first ran vacuum_indexes and that completed successfully -
i.e. it en-queued tasks to delete my existing indexes.
The next step was probably a mistake... | Google App Engine - update_indexes error | I have a Java app deployed on app engine and I use appcfg.py of the
Python SDK to vacuum and update my indexes.
Yesterday I first ran vacuum_indexes and that completed successfully -
i.e. it en-queued tasks to delete my existing indexes.
The next step was probably a mistake on my part - I then ran
update_indexes even t... | [
"I followed what was suggested in the error logs and that worked for me:\n\nEmpty the index.yaml file (create a backup first)\nRun vacuum_indexes again\nLook at your app's admin console and don't go to the next step till all your indexes are deleted.\nSpecify the indexes you want to be created in index.yaml\nRun up... | [
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"java",
"python"
] | stackoverflow_0003024663_google_app_engine_google_cloud_datastore_java_python.txt |
Q:
Define Classes in Packages
I'm learning Python and I have been playing around with packages. I wanted to know the best way to define classes in packages. It seems that the only way to define classes in a package is to define them in the __init__.py of that package. Coming from Java, I'd kind of like to define indi... | Define Classes in Packages | I'm learning Python and I have been playing around with packages. I wanted to know the best way to define classes in packages. It seems that the only way to define classes in a package is to define them in the __init__.py of that package. Coming from Java, I'd kind of like to define individual files for my classes. Is ... | [
"Go ahead and define your classes in separate modules. Then make __init__.py do something like this:\nfrom RecursionException import RecursionException\nfrom RecursionResult import RecursionResult\nfrom Recursor import Recursor\n\nThat will import each class into the package's root namespace, so calling code can r... | [
10,
2,
1
] | [] | [] | [
"class",
"module",
"package",
"python"
] | stackoverflow_0003024472_class_module_package_python.txt |
Q:
howto scroll a gtk.scrolledwindow object from python code
I'm writing a python application that has a glade gui. Using subprocess to execute some shell commands in the background.
Using a glade GUI which has a scrolledwindow widget and a textview widget inside the scrolledwindow widget. The textview gets populated... | howto scroll a gtk.scrolledwindow object from python code | I'm writing a python application that has a glade gui. Using subprocess to execute some shell commands in the background.
Using a glade GUI which has a scrolledwindow widget and a textview widget inside the scrolledwindow widget. The textview gets populated as the subprocess.Popen object run and display their stdout an... | [
"You need to get the horizontal and/or vertical gtk.Adjustment from the scrolledwindow, and change its values. See \n\nget_vadjustment\ngtk.Adjustment\n\nThe set_all method of gtk.Adjustment is probably what you want.\n",
"This is probably what you are looking for.\nhttp://faq.pygtk.org/index.py?req=show&file=faq... | [
2,
1,
0
] | [] | [] | [
"glade",
"pygtk",
"python",
"subprocess"
] | stackoverflow_0001940957_glade_pygtk_python_subprocess.txt |
Q:
using wild card when listing directories in python
how can I use wild cars like '*' when getting a list of files inside a directory in Python? for example, I want something like:
os.listdir('foo/*bar*/*.txt')
which would return a list of all the files ending in .txt in directories that have bar in their name in... | using wild card when listing directories in python | how can I use wild cars like '*' when getting a list of files inside a directory in Python? for example, I want something like:
os.listdir('foo/*bar*/*.txt')
which would return a list of all the files ending in .txt in directories that have bar in their name inside of the foo parent directory.
how can I do this?
tha... | [
"glob.glob for the win.\n"
] | [
17
] | [] | [] | [
"directory_structure",
"file_io",
"filesystems",
"python"
] | stackoverflow_0003025759_directory_structure_file_io_filesystems_python.txt |
Q:
Can one Python project use both 2.x and 3.x code?
I'm going to start on a long (~1-year) programming project in Python. I want to use wxPython for my GUI (supports 2.6), but I also want to use 3.1 for the rest of the project (to start using the 3.x syntax).
Is there any way for me to design a project that mixes 2.... | Can one Python project use both 2.x and 3.x code? | I'm going to start on a long (~1-year) programming project in Python. I want to use wxPython for my GUI (supports 2.6), but I also want to use 3.1 for the rest of the project (to start using the 3.x syntax).
Is there any way for me to design a project that mixes 2.x and 3.x modules? Or should I just bite the bullet and... | [
"You should use python 2.7 (a release candidate is expected in the next days) that is very close to python 3.1 and to code taking care of no using deprecated features. There is a recent version of wxpython for python 2.7.\nAfter wxpython gets 3.1-3.2 builds, conversion of the code should not be too hurting.\nStill... | [
5,
3,
2
] | [] | [] | [
"python",
"python_2.x",
"python_3.x"
] | stackoverflow_0002951982_python_python_2.x_python_3.x.txt |
Q:
How can I list all form related errors in Django?
Is there a direct way of listing out all form errors in Django templates. I'd like to list out both field and non-field errors and any other form errors.
I've found out how to do this on a per-field basis but as said earlier, I'd like to list out everything.
The me... | How can I list all form related errors in Django? | Is there a direct way of listing out all form errors in Django templates. I'd like to list out both field and non-field errors and any other form errors.
I've found out how to do this on a per-field basis but as said earlier, I'd like to list out everything.
The method I'm using doesn't seem to list out everything.
{% ... | [
"You could loop over all the field in addition to non-field errors: \n\nhttp://docs.djangoproject.com/en/dev/topics/forms/#looping-over-the-form-s-fields\nShort Django snippet: List all Form Errors\n\n"
] | [
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003026310_django_python.txt |
Q:
Is there a performance gain from defining routes in app.yaml versus one large mapping in a WSGIApplication in AppEngine?
Scenario 1
This involves using one "gateway" route in app.yaml and then choosing the RequestHandler in the WSGIApplication.
app.yaml
- url: /.*
script: main.py
main.py
from google.appengine.e... | Is there a performance gain from defining routes in app.yaml versus one large mapping in a WSGIApplication in AppEngine? | Scenario 1
This involves using one "gateway" route in app.yaml and then choosing the RequestHandler in the WSGIApplication.
app.yaml
- url: /.*
script: main.py
main.py
from google.appengine.ext import webapp
class Page1(webapp.RequestHandler):
def get(self):
self.response.out.write("Page 1")
class Page... | [
"The only performance implication relates to the loading of modules: Modules are loaded on an instance when they're first used, and splitting things up requires fewer module loads to serve a page on a new instance.\nThis is pretty minimal, though, as you can just as easily have the handler script dynamically load t... | [
12,
6
] | [] | [] | [
"google_app_engine",
"performance",
"python",
"yaml"
] | stackoverflow_0003025921_google_app_engine_performance_python_yaml.txt |
Q:
Invoking a superclass's class methods in Python
I am working on a Flask extension that adds CouchDB support to Flask. To make it easier, I have subclassed couchdb.mapping.Document so the store and load methods can use the current thread-local database. Right now, my code looks like this:
class Document(mapping.Doc... | Invoking a superclass's class methods in Python | I am working on a Flask extension that adds CouchDB support to Flask. To make it easier, I have subclassed couchdb.mapping.Document so the store and load methods can use the current thread-local database. Right now, my code looks like this:
class Document(mapping.Document):
# rest of the methods omitted for brevity
... | [
"I think you actually need to use super here. That's the neater way to call superclass methods anyway:\nclass A(object):\n @classmethod\n def load(cls):\n return cls\n\nclass B(A):\n @classmethod\n def load(cls):\n # return A.load() would simply do \"A.load()\" and thus return a A\n ... | [
7
] | [] | [] | [
"class_method",
"python",
"superclass"
] | stackoverflow_0003026392_class_method_python_superclass.txt |
Q:
Outgoing UDP sniffer in python?
I want to figure out whether my computer is somehow causing a UDP flood that is originating from my network. So that's my underlying problem, and what follows is simply my non-network-person attempt to hypothesize a solution using python. I'm extrapolating from recipe 13.1 ("Passing... | Outgoing UDP sniffer in python? | I want to figure out whether my computer is somehow causing a UDP flood that is originating from my network. So that's my underlying problem, and what follows is simply my non-network-person attempt to hypothesize a solution using python. I'm extrapolating from recipe 13.1 ("Passing Messages with Socket Datagrams") fro... | [
"It might be easier just to install Wireshark, instead of rolling your own in Python.\n"
] | [
5
] | [] | [] | [
"networking",
"proxy",
"python",
"twisted",
"udp"
] | stackoverflow_0003026833_networking_proxy_python_twisted_udp.txt |
Q:
Universal syntax file format?
Hey as a project to improve my programing skills I've begun programing a nice code editor in python to teach myself project management, version control, and gui programming. I was wanting to utilize syntax files made for other programs so I could have a large collection already. I was... | Universal syntax file format? | Hey as a project to improve my programing skills I've begun programing a nice code editor in python to teach myself project management, version control, and gui programming. I was wanting to utilize syntax files made for other programs so I could have a large collection already. I was wondering if there was any kind of... | [
"If you're planning to do syntax highlighting, check out Pygments, especially the bit about lexers.\nSince you mentioned Geany, you might want to look at the Scintilla docs. (Geany is built upon Scintilla).\nYou might find this post interesting.\nAlso, be sure to get familiar with the venerable lex and yacc.\n",
... | [
2,
0
] | [] | [] | [
"editor",
"python",
"syntax",
"text_editor"
] | stackoverflow_0003026786_editor_python_syntax_text_editor.txt |
Q:
Templates vs. coded HTML
I have a web-app consisting of some html forms for maintaining some tables (SQlite, with CherryPy for web-server stuff). First I did it entirely 'the Python way', and generated html strings via. code, with common headers, footers, etc. defined as functions in a separate module.
I also lik... | Templates vs. coded HTML | I have a web-app consisting of some html forms for maintaining some tables (SQlite, with CherryPy for web-server stuff). First I did it entirely 'the Python way', and generated html strings via. code, with common headers, footers, etc. defined as functions in a separate module.
I also like the idea of templates, so I ... | [
"Although I'm not a Python developer, I'll answer here - I believe the idea of using templates is common for PHP and Python.\nUsing templates has many advantages, like:\n\nkeeping the code clean. Separating the \"logic\" (controller) code from the presentation (view) is very important. Working on projects that mix ... | [
5,
4,
1,
1,
1
] | [] | [] | [
"html",
"python",
"templates"
] | stackoverflow_0003026731_html_python_templates.txt |
Q:
How to use a Proxy with Youtube API? (Python)
I'm working a script that will upload videos to YouTube with different accounts. Is there a way to use HTTPS or SOCKS proxies to filter all the requests. My client doesn't want to leave any footprints for Google. The only way I found was to set the proxy environment va... | How to use a Proxy with Youtube API? (Python) | I'm working a script that will upload videos to YouTube with different accounts. Is there a way to use HTTPS or SOCKS proxies to filter all the requests. My client doesn't want to leave any footprints for Google. The only way I found was to set the proxy environment variable beforehand but this seems cumbersome. Is the... | [
"Setting an environment variable (e.g. import os; os.environ['BLAH']='BLUH' once at the start of your program \"seems cumbersome\"?! What does count as \"non-cumbersome\" for you, pray?\n"
] | [
0
] | [] | [] | [
"api",
"gdata",
"python",
"youtube"
] | stackoverflow_0003026881_api_gdata_python_youtube.txt |
Q:
Execute a PyQt app from an acpi event in linux
I want to use a PyQt application to display an image when some acpi event is triggered under linux.
I already setting up the configuration for the event and the python scrip is executed when the event is triggered, but when program reach the creation of the QApplicati... | Execute a PyQt app from an acpi event in linux | I want to use a PyQt application to display an image when some acpi event is triggered under linux.
I already setting up the configuration for the event and the python scrip is executed when the event is triggered, but when program reach the creation of the QApplication
app = QApplication(sys.argv)
it stops without er... | [
"Your application is run by root who doesn't have access to your users's X display. \nEither set $XAUTHORITY to the path of the X authority file used by your user or use something like this (untested):\nsu your_user -l -c \"xauth extract - $DISPLAY\" | xauth merge -\n\nSee the man pages for xauth and Xsecurity for ... | [
0
] | [] | [] | [
"acpi",
"linux",
"pyqt",
"python",
"qt"
] | stackoverflow_0003026678_acpi_linux_pyqt_python_qt.txt |
Q:
Python imports by folder module
I have a directory structure:
example.py
templates/
__init__.py
a.py
b.py
a.py and b.py have only one class, named the same as the file (because they are cheetah templates). For purely style reasons, I want to be able to import and use these classes in example.py like s... | Python imports by folder module | I have a directory structure:
example.py
templates/
__init__.py
a.py
b.py
a.py and b.py have only one class, named the same as the file (because they are cheetah templates). For purely style reasons, I want to be able to import and use these classes in example.py like so:
import templates
t = templates.a(... | [
"To avoid repeating from <whatever> import * 25 times, you need a loop, such as:\nimport sys\n\ndef _allimports(modnames)\n thismod = sys.modules[__name__]\n\n for modname in modnames:\n submodname = '%s.%s' % (thismod, modname)\n __import__(submodname)\n submod = sys.modules[submodname]\n thismod.__d... | [
4,
3,
3
] | [] | [] | [
"import",
"python"
] | stackoverflow_0003027091_import_python.txt |
Q:
create a class attribute without going through __setattr__
What I have below is a class I made to easily store a bunch of data as attributes.
They wind up getting stored in a dictionary.
I override __getattr__ and __setattr__ to store and retrieve the values back in different types of units.
When I started overrid... | create a class attribute without going through __setattr__ | What I have below is a class I made to easily store a bunch of data as attributes.
They wind up getting stored in a dictionary.
I override __getattr__ and __setattr__ to store and retrieve the values back in different types of units.
When I started overriding __setattr__ I was having trouble creating that initial dicio... | [
"Your __setattr__ in the example doesn't do anything except put things in _data instead of __dict__ Remove it. \nChange your __getattr__ to use __dict__.\nStore your value and units as a simple 2-tuple. \n"
] | [
0
] | [] | [] | [
"class",
"python",
"setattr"
] | stackoverflow_0003024790_class_python_setattr.txt |
Q:
What does this `_time_independent_equals` mean?
In the tornado.web module there is a function called _time_independent_equals:
def _time_independent_equals(a, b):
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0
It is ... | What does this `_time_independent_equals` mean? | In the tornado.web module there is a function called _time_independent_equals:
def _time_independent_equals(a, b):
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0
It is used to compare secure cookie signatures, and thus th... | [
"That function does not simply compare the strings, it tries to always take the same amount of time to execute.\nThis is useful for security tasks like comparing passwords. If the function returned on the first mismatching byte, an attacker could try all possible first bytes and know that the one that takes longes... | [
18
] | [] | [] | [
"python",
"tornado"
] | stackoverflow_0003027286_python_tornado.txt |
Q:
Django not recognizing django admin urls
I just registered my models my models with django admin.
I navigate to the django admin at /admin. I log in sucessfully and I can see all my models. great so far.
But now if I try to click one of the links, for Ex: 'users', django gives me a 404 saying
The current URL, ad... | Django not recognizing django admin urls | I just registered my models my models with django admin.
I navigate to the django admin at /admin. I log in sucessfully and I can see all my models. great so far.
But now if I try to click one of the links, for Ex: 'users', django gives me a 404 saying
The current URL, admin/auth/user/, didn't match any of these.
It... | [
"Do you have this one in your urls.py?:\nfrom django.contrib import admin\n\nadmin.autodiscover()\n\nBut in fact without this you shouldn't even see models from django.contrib.auth... weird, can you post complete urls.pt file?\n"
] | [
1
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0003027440_django_django_admin_python.txt |
Q:
How to select random image of specific size using Django / Python?
I've been using this little snippet to select random images. However I would like to change it to select only images of a certain size. I'm running into trouble checking against image size. If I use get_image_dimensions() I need to use a conditio... | How to select random image of specific size using Django / Python? | I've been using this little snippet to select random images. However I would like to change it to select only images of a certain size. I'm running into trouble checking against image size. If I use get_image_dimensions() I need to use a conditional statement, which then requires that I allow exceptions. So, I guess... | [
"Well, a more direct way to get image dimensions is using the Python Imaging Library (which is what Django uses for get_image_dimensions in the backend anyway).\nSo, you use it like:\n>> import Image\n>> img = Image.open(\"foo.png\")\n>> img.size\n(1729,828)\n\nAnd your very simplest solution would be something lik... | [
1
] | [] | [] | [
"django",
"image",
"limit",
"python",
"size"
] | stackoverflow_0003026274_django_image_limit_python_size.txt |
Q:
Assigning a material in Blender with a script
Question: How do you assign a material with a script to an object in blender?
Info:
I have this script to import a proprietary model type of mine that is basically a star map with object consisting of a single vertex. in order to make them look like stars and be visib... | Assigning a material in Blender with a script | Question: How do you assign a material with a script to an object in blender?
Info:
I have this script to import a proprietary model type of mine that is basically a star map with object consisting of a single vertex. in order to make them look like stars and be visible they are all going to have a halo material assig... | [
"objectName.setMaterials([materials]) --- forgot that little \"s\".\nWhere the argument to setMaterials is a list of 16 items or less, all of which must be Materials or None.\nhttp://www.zoo-logique.org/3D.Blender/scripts_python/API/Object.Object-class.html\n"
] | [
2
] | [] | [] | [
"blender",
"python",
"scripting"
] | stackoverflow_0003026498_blender_python_scripting.txt |
Q:
PycURL RESUME_FROM
I can't seem to get the RESUME_FROM option to work. Here's some example code that I have been testing with:
import os
import pycurl
import sys
def progress(total, existing, upload_t, upload_d):
try:
frac = float(existing)/float(total)
except:
frac = 0
sys.stdout.writ... | PycURL RESUME_FROM | I can't seem to get the RESUME_FROM option to work. Here's some example code that I have been testing with:
import os
import pycurl
import sys
def progress(total, existing, upload_t, upload_d):
try:
frac = float(existing)/float(total)
except:
frac = 0
sys.stdout.write("\r%s %3i%%" % ("file"... | [
"It was actually resuming properly, however it appeared to be starting from the beginning again because the length from os.path.getsize(filename) was not added to existing in the progress function. Just a minor mistake! :)\n"
] | [
3
] | [] | [] | [
"pycurl",
"python",
"resume_download"
] | stackoverflow_0003027677_pycurl_python_resume_download.txt |
Q:
Overlapping matches with finditer() in Python
I'm using a regex to match Bible verse references in a text. The current regex is
REF_REGEX = re.compile('''
(?<!\w) # Not preceded by any words
(?P<quote>q(?:uote)?\s+)? # Match optional 'q' or 'quote' followed by many spaces
(?P<boo... | Overlapping matches with finditer() in Python | I'm using a regex to match Bible verse references in a text. The current regex is
REF_REGEX = re.compile('''
(?<!\w) # Not preceded by any words
(?P<quote>q(?:uote)?\s+)? # Match optional 'q' or 'quote' followed by many spaces
(?P<book>
(?:(?:[1-3]|I{1,3... | [
"A character consumed is consumed, you should not ask the regex engine to go back. \nFrom your examples the verse part (e.g. :1) seems not optional. Removing that will match the last bit.\nref_regex = re.compile('''\n(?<!\\w) # Not preceeded by any words\n((?i)q(?:uote)?\\s+)? # Matc... | [
4
] | [] | [] | [
"iteration",
"overlapping_matches",
"python",
"regex"
] | stackoverflow_0003027718_iteration_overlapping_matches_python_regex.txt |
Q:
Contrary to Python 3.1 Docs, hash(obj) != id(obj). So which is correct?
The following is from the Python v3.1.2 documentation:
From The Python Language Reference Section 3.3.1 Basic Customization:
object.__hash__(self)
... User-defined classes have __eq__() and __hash__() methods
by default; with them, all objec... | Contrary to Python 3.1 Docs, hash(obj) != id(obj). So which is correct? | The following is from the Python v3.1.2 documentation:
From The Python Language Reference Section 3.3.1 Basic Customization:
object.__hash__(self)
... User-defined classes have __eq__() and __hash__() methods
by default; with them, all objects compare unequal (except
with themselves) and x.__hash__() returns id(x).
... | [
"I'm guessing this was a change made in Python 3.x to improve performance. Check out issue 5186, then look a little more closely at your mismatched numbers:\n>>> bin(11893680)\n'0b101101010111101110110000'\n>>> bin(743355)\n'0b10110101011110111011'\n>>> 11893680 >> 4\n743355\n\nIt's probably worth reporting as a d... | [
10
] | [] | [] | [
"hash",
"python"
] | stackoverflow_0003027838_hash_python.txt |
Q:
Compiling C-dll for Python OR SWIG-module creation, how to continue?
I reference this file "kbdext.c" and its headerfile listed on http://www.docdroppers.org/wiki/index.php?title=Writing_Keyloggers (the listings are at the bottom).
I've been trying to compile this into a dll for use in Python or Visual Basic, but ... | Compiling C-dll for Python OR SWIG-module creation, how to continue? | I reference this file "kbdext.c" and its headerfile listed on http://www.docdroppers.org/wiki/index.php?title=Writing_Keyloggers (the listings are at the bottom).
I've been trying to compile this into a dll for use in Python or Visual Basic, but have not succeeded. I'm not familiar with C or GCC to sort out the problem... | [
"I've succeeded in compiling the dll with GCC, and am able to import its functions in C. I have yet to test the import in VB and Python but can't see why it would pose problems.\n"
] | [
0
] | [] | [] | [
"c",
"dll",
"python",
"swig"
] | stackoverflow_0003018249_c_dll_python_swig.txt |
Q:
Urllib's urlopen breaking on some sites (e.g. StackApps api): returns garbage results
I'm using urllib2's urlopen function to try and get a JSON result from the StackOverflow api.
The code I'm using:
>>> import urllib2
>>> conn = urllib2.urlopen("http://api.stackoverflow.com/0.8/users/")
>>> conn.readline()
The r... | Urllib's urlopen breaking on some sites (e.g. StackApps api): returns garbage results | I'm using urllib2's urlopen function to try and get a JSON result from the StackOverflow api.
The code I'm using:
>>> import urllib2
>>> conn = urllib2.urlopen("http://api.stackoverflow.com/0.8/users/")
>>> conn.readline()
The result I'm getting:
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x04\x00\xed\xbd\x07`\x1cI\x96%&/m\xca{... | [
"That almost looks like something you would be feeding to pickle. Maybe something in the User-Agent string or Accepts header that urllib2 is sending is causing StackOverflow to send something other than JSON.\nOne telltale is to look at conn.headers.headers to see what the Content-Type header says.\nAnd this quest... | [
10
] | [] | [] | [
"python",
"urllib",
"urllib2",
"urlopen"
] | stackoverflow_0003028426_python_urllib_urllib2_urlopen.txt |
Q:
Is it possible to detect an incoming call to a GSM modem (HUAWEI E160) plugged into the USB port?
Ideally I'd like to find a library for Python.
All I need is the caller number, I do not need to answer the call.
A:
i don't know for this specific model, but GSM modem are generally handled as a communication port.... | Is it possible to detect an incoming call to a GSM modem (HUAWEI E160) plugged into the USB port? | Ideally I'd like to find a library for Python.
All I need is the caller number, I do not need to answer the call.
| [
"i don't know for this specific model, but GSM modem are generally handled as a communication port. they are mapped as a communication port (COMXX under windows, don't know for linux). \nthe documentation of the modem will give you a set of AT command which will allow you to configure the modem so that it notifies ... | [
0
] | [] | [] | [
"call",
"gsm",
"modem",
"python"
] | stackoverflow_0003024344_call_gsm_modem_python.txt |
Q:
Newbie : installing and upgrading python module
I have downloaded and install a python library, via setup.py , python2.5 setup.py install ...
now the version is changed at the source . a newer library is available. originally , i have clone it via mercurial, and install it. right now , i have updated repository.
... | Newbie : installing and upgrading python module | I have downloaded and install a python library, via setup.py , python2.5 setup.py install ...
now the version is changed at the source . a newer library is available. originally , i have clone it via mercurial, and install it. right now , i have updated repository.
how do i use the newer version ? overwrite the instal... | [
"Yes, just do setup.py install again.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003028561_python.txt |
Q:
Comments in XML at beginning of document
my PYTHON xml parser fails if there´s a comment at the beginnging of an xml file like::
<?xml version="1.0" encoding="utf-8"?>
<!-- Script version: "1"-->
<!-- Date: "07052010"-->
<component name="abc">
<pp>
....
</pp>
</component>
is it illegal to place a comment like... | Comments in XML at beginning of document | my PYTHON xml parser fails if there´s a comment at the beginnging of an xml file like::
<?xml version="1.0" encoding="utf-8"?>
<!-- Script version: "1"-->
<!-- Date: "07052010"-->
<component name="abc">
<pp>
....
</pp>
</component>
is it illegal to place a comment like this?
EDIT:
well it´s not throwing an error b... | [
"It is legal; from XML 1.0 Reference:\n\n2.5 Comments\n[Definition: Comments may appear\n anywhere in a document outside other\n markup; in addition, they may appear\n within the document type declaration\n at places allowed by the grammar. They\n are not part of the document's\n character data; an XML proces... | [
1,
1,
1,
0
] | [] | [] | [
"parsing",
"python",
"xml"
] | stackoverflow_0003021884_parsing_python_xml.txt |
Q:
ruby or python more suitable for scripting in all OSes?
if i want to script a mini-application (in the Terminal) in mac and windows, which one is preferred: ruby or python?
or is there no major difference just a matter of taste?
cause i know python definetely is a good scripting language.
thanks
A:
Matter of tas... | ruby or python more suitable for scripting in all OSes? | if i want to script a mini-application (in the Terminal) in mac and windows, which one is preferred: ruby or python?
or is there no major difference just a matter of taste?
cause i know python definetely is a good scripting language.
thanks
| [
"Matter of taste, really. They each have a pretty good set of libraries and are cross-platform, so it'll be a matter of which one you prefer to code in.\n",
"Personally, I find the documentation for Python is much better than that for Ruby. The Docs for Ruby are full of cryptic examples that are terse, short, and... | [
5,
5,
2,
2,
2,
0
] | [] | [] | [
"python",
"ruby"
] | stackoverflow_0002978801_python_ruby.txt |
Q:
pyODBC and Unicode
I'm working with pyODBC communicate with a MS SQL 2005 Express server.
The table to which i'm trying to save the data consists of nvarchar columns.
query = u"INSERT INTO tblPersons (name, birthday, gender) VALUES('"
query = query + name + u"', '"
query = query + birthday + u"', '"
query = q... | pyODBC and Unicode | I'm working with pyODBC communicate with a MS SQL 2005 Express server.
The table to which i'm trying to save the data consists of nvarchar columns.
query = u"INSERT INTO tblPersons (name, birthday, gender) VALUES('"
query = query + name + u"', '"
query = query + birthday + u"', '"
query = query + gender + u"')"
c... | [
"It could be something related to the odbc driver that pyodbc is using. If that doesn't support unicode, you will probably have to encode the params yourself, like name.encode('utf-16')\nAlso, you should really, really use query parameters, instead of concatenating the sql string yourself, for example:\nquery = \"I... | [
2,
0
] | [] | [] | [
"pyodbc",
"python",
"unicode",
"utf_16"
] | stackoverflow_0003015967_pyodbc_python_unicode_utf_16.txt |
Q:
help('modules') crashing? Not sure how to fix
I was trying to install a module for opencv and added an opencv.pth file to the folder beyond my sites.py file. I have since deleted it and no change.
When I try to run help('modules'), I get the following error:
Please wait a moment while I gather a
list of all av... | help('modules') crashing? Not sure how to fix | I was trying to install a module for opencv and added an opencv.pth file to the folder beyond my sites.py file. I have since deleted it and no change.
When I try to run help('modules'), I get the following error:
Please wait a moment while I gather a
list of all available modules...
/System/Library/Frameworks/Pytho... | [
"This happens because help('modules') imports all modules, which can result in a lot of unsentineled code being executed. There's nothing you can do short of reporting bugs in every single package that causes this (opencv in this case) and wait for them to fix it.\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0003029053_python.txt |
Q:
Too many values problem
i was trying to make a full lot of ips for testing using this code :
ip_is = [i for i in range(256)]
ports = [i for i in range(1024,49152)]
return [str(i1)+"."+str(i2)+"."+str(i3)+"."+str(i4)+":"+str(p) for i1,i2,i3,i4,port in ip_is,ip_is,ip_is,ip_is,ports]
The problem is the 3rd line in ... | Too many values problem | i was trying to make a full lot of ips for testing using this code :
ip_is = [i for i in range(256)]
ports = [i for i in range(1024,49152)]
return [str(i1)+"."+str(i2)+"."+str(i3)+"."+str(i4)+":"+str(p) for i1,i2,i3,i4,port in ip_is,ip_is,ip_is,ip_is,ports]
The problem is the 3rd line in which is made the ip list. If... | [
"You're trying (quite apart from the syntax issues) to make a list of\n256 * 256 * 256 * 256 * (49152 - 1024)\n\nstrings -- i.e., 206708186021888 strings... about two hundred thousand billions of strings.\nIf you made one per microsecond, that would take you 6.5 years (even quite apart from the problem of finding t... | [
6,
5,
5
] | [] | [] | [
"python"
] | stackoverflow_0003029132_python.txt |
Q:
How to draw the "trail" in a maze solving application
Hello i have designed a maze and i want to draw a path between the cells as the 'person' moves from one cell to the next.
So each time i move the cell a line is drawn
Also i am using the graphics module
The graphics module is an object oriented library
Im i... | How to draw the "trail" in a maze solving application | Hello i have designed a maze and i want to draw a path between the cells as the 'person' moves from one cell to the next.
So each time i move the cell a line is drawn
Also i am using the graphics module
The graphics module is an object oriented library
Im importing
from graphics import*
from maze import*
my circle... | [
"You might try this from an interactive Python shell:\n>>> import graphics\n>>> help(graphics.Circle)\n\nThat should tell you what attributes Circle does have.\n",
"You're trying to use getX() and getY() as free-standing FUNCTIONS:\np2 = Point(getX(), getY())\n\nNote that you're calling them as bare names, not qu... | [
1,
1,
0
] | [] | [] | [
"graphics",
"python"
] | stackoverflow_0003027571_graphics_python.txt |
Q:
Programmatically determining the status of a file download
Is there a way I can programmatically determine the status of a download in Chrome or Mozilla Firefox? I would like to know if the download was aborted or completed successfully.
For writing the code I'd be using either Perl, PHP or Python.
Please help.
Th... | Programmatically determining the status of a file download | Is there a way I can programmatically determine the status of a download in Chrome or Mozilla Firefox? I would like to know if the download was aborted or completed successfully.
For writing the code I'd be using either Perl, PHP or Python.
Please help.
Thank You.
| [
"I don't know about Chrome, but recent versions of Firefox keep the download records in a SQLite database (downloads.sqlite in your profile directory). I'm not sure if that gets updated while the download is in progress, but it should tell you the status once the download is complete/aborted.\n"
] | [
1
] | [
"There are scripts out there that output the file in chunks, recording how many bytes they've echoed out, but those are completely unreliable and you can't accurately ascertain whether or not the user successfully received the complete file.\nThe short answer is no, really, unless you write your own download manage... | [
-2
] | [
"download",
"perl",
"php",
"python"
] | stackoverflow_0003029824_download_perl_php_python.txt |
Q:
what does the '~' mean in python?
what does the '~' mean in python?
i found this BF interpreter in python a while ago.
import sys
#c,i,r,p=0,0,[0]*255,raw_input()
c=0
i=0
p=raw_input()
r=[0]*255
while c<len(p):
m,n,u=p[c],0,r[i]
if m==">":i+=1
if m=="<":i-=1
if m=="+":r[i]+=1
if m=="... | what does the '~' mean in python? | what does the '~' mean in python?
i found this BF interpreter in python a while ago.
import sys
#c,i,r,p=0,0,[0]*255,raw_input()
c=0
i=0
p=raw_input()
r=[0]*255
while c<len(p):
m,n,u=p[c],0,r[i]
if m==">":i+=1
if m=="<":i-=1
if m=="+":r[i]+=1
if m=="-":r[i]-=1
if m==".":sys.stdout.wri... | [
"Bitwise NOT, just like in C.\nIn two's complement representation, ~n is equivalent to -n - 1.\n",
"In this particular context, just replace '~' with 'not'. \nPS. ok i guess i will have to explain - started getting slapped with -1's, probably on the premise i don't know the difference between logical and bitwise ... | [
22,
14,
10,
5
] | [] | [] | [
"brainfuck",
"interpreter",
"python"
] | stackoverflow_0003027394_brainfuck_interpreter_python.txt |
Q:
Using Google AppEngine app as a OAuth provider
I'm using the Google AppEngine 1.3.4 SDK which offers to allow your application to act as a OAuth service provider (http://code.google.com/appengine/docs/python/oauth/). Setting up a standard application on my localhost and using the following:
Request URL /_ah/OAuthG... | Using Google AppEngine app as a OAuth provider | I'm using the Google AppEngine 1.3.4 SDK which offers to allow your application to act as a OAuth service provider (http://code.google.com/appengine/docs/python/oauth/). Setting up a standard application on my localhost and using the following:
Request URL /_ah/OAuthGetRequestToken
Authorize URL /_ah/OAuthAuthorizeToke... | [
"I would hazard a guess that the SDK implementation simply grants access regardless. It's also possible you still have a dev_appserver login cookie. Either way, try it in production - it'll almost certainly request login in that case.\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003029556_google_app_engine_python.txt |
Q:
Writing to a file in Python inserts null bytes
I'm writing a todo list program. It keeps a file with a thing to do per line, and lets the user add or delete items. The problem is that for some reason, I end up with a lot of zero bytes at the start of the file, even though the item is correctly deleted. I'll show y... | Writing to a file in Python inserts null bytes | I'm writing a todo list program. It keeps a file with a thing to do per line, and lets the user add or delete items. The problem is that for some reason, I end up with a lot of zero bytes at the start of the file, even though the item is correctly deleted. I'll show you a couple of screenshots to make sure I'm making m... | [
"It looks to me like you're forgetting to rewind your file stream. After f.truncate(0), add f.seek(0). Otherwise, I think your next write will try to start at the position from which you left off, filling in null bytes on its way there.\n(Notice that the number of null characters in your example equals the number... | [
16,
8,
3
] | [] | [] | [
"file",
"file_io",
"python"
] | stackoverflow_0003030343_file_file_io_python.txt |
Q:
"TypeError: draw() takes exactly 1 non-keyword argument (3 given)"
I wrote this code to open a window with Pyglet in Python...
import pyglet
from pyglet import window
class Window(pyglet.window.Window):
def __init__(self):
super(Window, self).__init__()
myLabel = pyglet.text.Label("Prototype"... | "TypeError: draw() takes exactly 1 non-keyword argument (3 given)" | I wrote this code to open a window with Pyglet in Python...
import pyglet
from pyglet import window
class Window(pyglet.window.Window):
def __init__(self):
super(Window, self).__init__()
myLabel = pyglet.text.Label("Prototype")
windowText = myLabel.draw(Window, "Hello World",
... | [
"The three non-keyword arguments you've given are the object instance, Window, and \"Hello World\". It only expects the object instance. Check the docs again for which arguments the draw() method takes. Consider printing the repr() of myLabel so that you know which type it is.\n",
"The three non-keyword arguments... | [
1,
1,
0
] | [] | [] | [
"pyglet",
"python"
] | stackoverflow_0003030579_pyglet_python.txt |
Q:
Python, dictionaries, and chi-square contingency table
This is a problem I've been racking my brains on for a long time, so any help would be great. I have a file which contains several lines in the following format (word, time that the word occurred in, and frequency of documents containing the given word within ... | Python, dictionaries, and chi-square contingency table | This is a problem I've been racking my brains on for a long time, so any help would be great. I have a file which contains several lines in the following format (word, time that the word occurred in, and frequency of documents containing the given word within the given instance in time). Below is an example of what the... | [
"Your 4 numbers for apple/1 add up to 12, more than the total number of observations (11)! There are only 5 documents outside time '1' that don't contain the word 'apple'.\nYou need to partition the observations into 4 disjoint subsets:\na: apple and 1 => 3\nb: not-apple and 1 => 2\nc: apple and not-1 => 1\nd: not-... | [
2
] | [] | [] | [
"dictionary",
"discrete_mathematics",
"python"
] | stackoverflow_0003029600_dictionary_discrete_mathematics_python.txt |
Q:
Image resizing web service
Does someone know a good web service to resize images ? Either an open source (PHP/Python/Ruby) application, or a company providing a web service api.
A:
Make your own service at Utility Mill (http://utilitymill.com). Here's one that I wrote that adds a simulated gallery wrap - http:/... | Image resizing web service | Does someone know a good web service to resize images ? Either an open source (PHP/Python/Ruby) application, or a company providing a web service api.
| [
"Make your own service at Utility Mill (http://utilitymill.com). Here's one that I wrote that adds a simulated gallery wrap - http://utilitymill.com/utility/Gallery_Wrap_Image. Define your own interface, parameters, processing logic, and you get not only an interactive web service, but you also get a callable API... | [
4,
3,
1,
0
] | [] | [] | [
"image_processing",
"php",
"python",
"ruby",
"web_services"
] | stackoverflow_0001000195_image_processing_php_python_ruby_web_services.txt |
Q:
Look for match in a nested list in Python
I have two nested lists of different sizes:
A = [[1, 7, 3, 5], [5, 5, 14, 10]]
B = [[1, 17, 3, 5], [1487, 34, 14, 74], [1487, 34, 3, 87], [141, 25, 14, 10]]
I'd like to gather all nested lists from list B if A[2:4] == B[2:4] and put it into list L:
L = [[1, 17, 3, 5], [1... | Look for match in a nested list in Python | I have two nested lists of different sizes:
A = [[1, 7, 3, 5], [5, 5, 14, 10]]
B = [[1, 17, 3, 5], [1487, 34, 14, 74], [1487, 34, 3, 87], [141, 25, 14, 10]]
I'd like to gather all nested lists from list B if A[2:4] == B[2:4] and put it into list L:
L = [[1, 17, 3, 5], [141, 25, 14, 10]]
Additionally if the match occ... | [
"It looks like this does what you want:\n> [b for b in B if b[2:4] in [a[2:4] for a in A]]\n[[1, 17, 3, 5], [141, 25, 14, 10]]\n\nBut, for efficiency's sake, you may want to precompute the slices of A.\n> a_slices = [a[2:4] for a in A]\n> [b for b in B if b[2:4] in a_slices]\n[[1, 17, 3, 5], [141, 25, 14, 10]]\n\nH... | [
3,
1
] | [] | [] | [
"list",
"nested",
"python"
] | stackoverflow_0003030790_list_nested_python.txt |
Q:
Best style for Python programs: what do you suggest?
A friend of mine wanted help learning to program, so he gave me all the programs that he wrote for his previous classes. The last program that he wrote was an encryption program, and after rewriting all his programs in Python, this is how his encryption program ... | Best style for Python programs: what do you suggest? | A friend of mine wanted help learning to program, so he gave me all the programs that he wrote for his previous classes. The last program that he wrote was an encryption program, and after rewriting all his programs in Python, this is how his encryption program turned out (after adding my own requirements).
#! /usr/bin... | [
"Since you asked about formatting and style, I'm surprised that nobody else has mentioned PEP 8 yet. It's nominally a guide for modules that want to be included in the standard library, but I find most of its guidance to be applicable pretty much everywhere.\n",
"don't use bare excepts;\ntry:\n with open(file... | [
8,
6,
3,
2,
1
] | [] | [] | [
"coding_style",
"encryption",
"python"
] | stackoverflow_0003028961_coding_style_encryption_python.txt |
Q:
GUI not updated from another thread when using PyGtk
I am using PyGTK to build a GUI application. I want to update the textview widget from another thread but the widget is not getting updated everytime i try an update. What should i do to get a reliable GUI updating?
A:
GTK+ is not thread-safe, so you should no... | GUI not updated from another thread when using PyGtk | I am using PyGTK to build a GUI application. I want to update the textview widget from another thread but the widget is not getting updated everytime i try an update. What should i do to get a reliable GUI updating?
| [
"GTK+ is not thread-safe, so you should not simply call GUI update methods from other threads. glib.idle_add (or gobject.idle_add in older PyGTK versions) can be used for this purpose.\nInstead of writing:\nlabel.set_text(\"foo\")\n\nyou would write:\nglib.idle_add(label.set_text, \"foo\")\n\nwhich causes the funct... | [
15,
2
] | [
"the same may be achieved using gobject.idle_add method whose syntax is same as above,you have to import the module gobject\n",
"What Johannes said is correct, however since GTK is a wrapper for the glib and gobject things, you would actually want to use gtk.idle_add(). No need for the unnecessary imports.\n"
] | [
-1,
-1
] | [
"multithreading",
"pygtk",
"python"
] | stackoverflow_0002066767_multithreading_pygtk_python.txt |
Q:
PyQt WebKit CSS background image not showing
I'm making a Twitter client with PyQt, which uses WebKit to draw the tweet list. Now I'm trying to use CSS to set a background image in the WebKit widget - but the image won't show up. This is the relevant part of the CSS:
body ... | PyQt WebKit CSS background image not showing | I'm making a Twitter client with PyQt, which uses WebKit to draw the tweet list. Now I'm trying to use CSS to set a background image in the WebKit widget - but the image won't show up. This is the relevant part of the CSS:
body
{ ... | [
"Try removing the quotes. Also, bear in mind that if you declare a \"background:\" shorthand rule after a \"backround-image:\" rule, the background-image will be overwritten. Also, the file path should be relative to the css file, not the source file.\n",
"you could use the background-image like this:\nbody ... | [
2,
0
] | [] | [] | [
"css",
"pyqt",
"python",
"webkit"
] | stackoverflow_0002602880_css_pyqt_python_webkit.txt |
Q:
AttributeError HELP!
class Account:
def __init__(self, initial):
self.balance = initial
def deposit(self, amt):
self.balance = self.balance + amt
def withdraw(self,amt):
self.balance = self.balance - amt
def getbalance(self):
return self.balance
a = Accoun... | AttributeError HELP! | class Account:
def __init__(self, initial):
self.balance = initial
def deposit(self, amt):
self.balance = self.balance + amt
def withdraw(self,amt):
self.balance = self.balance - amt
def getbalance(self):
return self.balance
a = Account(1000.00)
a.deposit(550.2... | [
"class Account:\n def __init__(self, initial):\n self.balance = initial\n def deposit(self, amt):\n self.balance = self.balance + amt\n def withdraw(self,amt):\n self.balance = self.balance - amt\n def getbalance(self):\n return self.balance\n\nThe way you defined them, they ... | [
5,
2,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003027048_python.txt |
Q:
why does text from socket server erase previously written text?
This is strange enough I'm not sure how to search for an answer. I have a program in Python that communicates via TCP/IP sockets to a telnet-based server. If I telnet in manually and type commands like this:
SET MDI G0 X0 Y0
the server will spit ba... | why does text from socket server erase previously written text? | This is strange enough I'm not sure how to search for an answer. I have a program in Python that communicates via TCP/IP sockets to a telnet-based server. If I telnet in manually and type commands like this:
SET MDI G0 X0 Y0
the server will spit back a line like this:
SET MDI ACK
Pretty standard stuff. Here's the ... | [
"If you print repr(send) and repr(received) instead of just printing sent and received, you'll have a much clearer idea about exactly what you're sending and what you're getting back in return (so you can check if @theatrus' suggestion is correct, etc, etc, and at all times clearly see what you're doing).\nThis is ... | [
3,
2,
1
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0003030634_python_sockets.txt |
Q:
Is it possible to read path in JPEG image with python?
If you Save as > jpg in Adobe Photoshop a path (selection) is stored in the file.
Is it possible to read that path in python, for example to create a composition with PIL?
EDIT
Imagemagick seems to help, example
A:
This code (by /F AKA the effbot, author o... | Is it possible to read path in JPEG image with python? | If you Save as > jpg in Adobe Photoshop a path (selection) is stored in the file.
Is it possible to read that path in python, for example to create a composition with PIL?
EDIT
Imagemagick seems to help, example
| [
"This code (by /F AKA the effbot, author of PIL and generally wondrous Python contributor) shows how to walk through the 8BIM resource blocks (but it's looking for 0x0404, the IPTC/NAA data, so of course you'll need to edit it).\nPer Tom Ruark's post to this thread, paths will have IDs of 2000 to 2999 (the latter ... | [
1,
0
] | [] | [] | [
"image",
"jpeg",
"python"
] | stackoverflow_0003030577_image_jpeg_python.txt |
Q:
Finding the nth number of primes
I can not figure out why this won't work. Please help me
from math import sqrt
pN = 0
numPrimes = 0
num = 1
def checkPrime(x):
'''Check\'s whether a number is a prime or not'''
prime = True
if(x==2):
prime = True
elif(x%2==0):
prime=False
else:
r... | Finding the nth number of primes | I can not figure out why this won't work. Please help me
from math import sqrt
pN = 0
numPrimes = 0
num = 1
def checkPrime(x):
'''Check\'s whether a number is a prime or not'''
prime = True
if(x==2):
prime = True
elif(x%2==0):
prime=False
else:
root=int(sqrt(x))
for i in range(... | [
"You need to change\nroot=int(sqrt(x))\n\ninto\nroot=int(sqrt(x))+1\n\n(Take 9 for instance, int(sqrt(9)) is 3, and range(3, 3, 2) is [], and you do really want to test dividing by 3!).\nTechnically, 1 is not a prime either. Add\nif(x<=1):\n prime = False\n\nand you'll get the same result as http://www.rsok.com/~... | [
5,
1
] | [] | [] | [
"computer_science",
"math",
"primes",
"python"
] | stackoverflow_0003030226_computer_science_math_primes_python.txt |
Q:
how to detect an escape sequence in a string
Given a string named line whose raw version has this value:
\rRAWSTRING
how can I detect if it has the escape character \r? What I've tried is:
if repr(line).startswith('\r'):
blah...
but it doesn't catch it. I also tried find, such as:
if repr(line).find('\r') ... | how to detect an escape sequence in a string | Given a string named line whose raw version has this value:
\rRAWSTRING
how can I detect if it has the escape character \r? What I've tried is:
if repr(line).startswith('\r'):
blah...
but it doesn't catch it. I also tried find, such as:
if repr(line).find('\r') != -1:
blah
doesn't work either. What am I m... | [
"If:\nprint repr(line)\n\nReturns:\n'\\rSET ENABLE ACK\\n'\n\nThen:\nline.find('\\r')\nline.startswith('\\r')\n'\\r' in line\n\nare what you are looking for. Example:\n>>> line = '\\rSET ENABLE ACK\\n'\n>>> print repr(line)\n'\\rSET ENABLE ACK\\n'\n>>> line.find('\\r')\n0\n>>> line.startswith('\\r')\nTrue\n>>> '\\... | [
4,
2,
1,
0,
0,
0
] | [] | [] | [
"escaping",
"parsing",
"python",
"string"
] | stackoverflow_0003030789_escaping_parsing_python_string.txt |
Q:
Serve external template in Django
I want to do something like
return render_to_response("http://docs.google.com/View?id=bla", args)
and serve an external page with django arguments. Django doesn't like this (it looks for templates in very particular places).
What's the easiest way make this work? Right now I'm... | Serve external template in Django | I want to do something like
return render_to_response("http://docs.google.com/View?id=bla", args)
and serve an external page with django arguments. Django doesn't like this (it looks for templates in very particular places).
What's the easiest way make this work? Right now I'm thinking to use urllib to save the pag... | [
"Read the template in as a string and render it yourself.\n"
] | [
2
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0003031056_django_django_templates_python.txt |
Q:
word ladder in python
I'm trying to create a word ladder program in python. I'd like to generate words that are similar to a given word. In c++ or java, I would go through each valid index in the original string, and replace it with each letter in the english alphabet, and see if the result is a valid word. for ex... | word ladder in python | I'm trying to create a word ladder program in python. I'd like to generate words that are similar to a given word. In c++ or java, I would go through each valid index in the original string, and replace it with each letter in the english alphabet, and see if the result is a valid word. for example (pseudocode)
for (int... | [
"A generator of similar words (taking a predicate, i.e. a function argument which returns true or false, to check whether a word is valid) seems a reasonable first step:\nimport string\n\ndef allsimilar(word, valid):\n wl = list(word)\n for i, c in enumerate(wl):\n for x in string.ascii_lowercase:\n if x ... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0003031094_python.txt |
Q:
Python - Bitmap won't draw/display on button
I have been working on this project for some time now - it was originally supposed to be a test to see if, using wxPython, I could build a button 'from scratch.' From scratch means: that i would have full control over all the aspects of the button (i.e. controlling the ... | Python - Bitmap won't draw/display on button | I have been working on this project for some time now - it was originally supposed to be a test to see if, using wxPython, I could build a button 'from scratch.' From scratch means: that i would have full control over all the aspects of the button (i.e. controlling the BMP's that are displayed... what the event handler... | [
"Are your sure you code is working without exceptions because when I run it i get many errors, read the points below and you should have a button which at least draws correctly\n\nWhen O run it it gives error because Custom_Button is passed NULL parent instead pass frame e.g. Custom_Button(self, ...)\nYour drawBitm... | [
1
] | [] | [] | [
"custom_controls",
"python",
"wxpython"
] | stackoverflow_0003020704_custom_controls_python_wxpython.txt |
Q:
PGU HTML Renderer can't render most sites
I am trying to make a web browser using pygame. I am using PGU for html rendering. It works fine when I visit simple sites, like example.com, but when I try and load anything more complex that uses an html form, like google, I get this error:
UnboundLocalError: local varia... | PGU HTML Renderer can't render most sites | I am trying to make a web browser using pygame. I am using PGU for html rendering. It works fine when I visit simple sites, like example.com, but when I try and load anything more complex that uses an html form, like google, I get this error:
UnboundLocalError: local variable 'e' referenced before assignment
I looked ... | [
"I think it's possible to embed PyGame in a PyQT window. That's more of a work around than an elegant solution though. \n"
] | [
1
] | [] | [] | [
"html_rendering",
"pygame",
"python"
] | stackoverflow_0002982016_html_rendering_pygame_python.txt |
Q:
How to update the text of a tag in XML using Elementree
Using elementree, the easiest way to read the text of a tag is to do the following:
import elementtree.ElementTree as ET
sKeyMap = ET.parse("KeyMaps/KeyMap_Checklist.xml")
host = sKeyMap.findtext("/BrowserInformation/BrowserSetup/host")
Now I want to update ... | How to update the text of a tag in XML using Elementree | Using elementree, the easiest way to read the text of a tag is to do the following:
import elementtree.ElementTree as ET
sKeyMap = ET.parse("KeyMaps/KeyMap_Checklist.xml")
host = sKeyMap.findtext("/BrowserInformation/BrowserSetup/host")
Now I want to update the text in the same file, hopefully without having to re-wri... | [
"If you want to update the value of the <host> element in your text file you should get a handle to the element using find() rather than just reading the text using findtext(). Once you have the element you can easily get the text out using element.text. Since you have the element you can easily reset its value as ... | [
1,
1
] | [] | [] | [
"elementtree",
"python",
"xml"
] | stackoverflow_0003018763_elementtree_python_xml.txt |
Q:
Python Pickle: what can cause stack index out of range error?
I'm getting this error:
File "C:\Python26\lib\pickle.py", line 1374, in loads
return Unpickler(file).load()
File "C:\Python26\lib\pickle.py", line 858, in load
dispatch[key](self)
File "C:\Python26\lib\pickle.py", line 1075, in load_obj
... | Python Pickle: what can cause stack index out of range error? | I'm getting this error:
File "C:\Python26\lib\pickle.py", line 1374, in loads
return Unpickler(file).load()
File "C:\Python26\lib\pickle.py", line 858, in load
dispatch[key](self)
File "C:\Python26\lib\pickle.py", line 1075, in load_obj
k = self.marker()
File "C:\Python26\lib\pickle.py", line 874, i... | [
"A \"damaged file\" is the general explanation; single most likely cause is that you forgot to open the file (in Windows) as 'rb' (\"read binary\") and the pickling was done with a binary protocol (i.e., any protocol except the old, slow default protocol 0, ascii only, that basically exists only for legacy purposes... | [
1,
0
] | [] | [] | [
"pickle",
"python"
] | stackoverflow_0003030229_pickle_python.txt |
Q:
Appengine Model SelfReferenceProperty and parent child relationship
I have a scenario in which I need a self reference property as follow:
class Post(db.Model):
creator = db.UserProperty()
post_title = db.StringProperty(required=True)
post_status = db.StringProperty(required=True, choices=['draft', 'publishe... | Appengine Model SelfReferenceProperty and parent child relationship | I have a scenario in which I need a self reference property as follow:
class Post(db.Model):
creator = db.UserProperty()
post_title = db.StringProperty(required=True)
post_status = db.StringProperty(required=True, choices=['draft', 'published'])
post_parent = db.SelfReferenceProperty()
Now, I want ensure that ... | [
"I would suggest using a ListProperty(db.Key) instead, storing the list of ancestors. That way, you can query more efficiently ('get every descendent of node x' is easier), and you can enforce the latter condition easily, like this:\ndef ancestor_list_validator(l):\n if len(l) != len(set(l)):\n raise Exception(... | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003031223_google_app_engine_python.txt |
Q:
is there any way to enforce the 30 seconds limit on local appengine dev server?
Hey, i was wondering if there is a way to enforce the 30 seconds limit that is being enforced online at the appengine production servers to the local dev server? its impossible to test if i reach the limit before going production.
mayb... | is there any way to enforce the 30 seconds limit on local appengine dev server? | Hey, i was wondering if there is a way to enforce the 30 seconds limit that is being enforced online at the appengine production servers to the local dev server? its impossible to test if i reach the limit before going production.
maybe some django middlware?
| [
"You could write (and insert in the WSGI stack) a useful piece of WSGI middleware which uses a threading.Timer which logs the fact that the transaction has exceeded 30 seconds (and of course calls cancel on the timer object on the way out, as there's nothing to log in that case).\nI'd do it at WSGI level, not Djang... | [
1,
1
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0003030593_django_google_app_engine_python.txt |
Q:
How to pickle and unpickle objects with self-references and from a class with slots?
What is a correct way to pickle an object from a class with slots, when this object references itself through one of its attributes? Here is a simple example, with my current implementation, which I'm not sure is 100 % correct:
i... | How to pickle and unpickle objects with self-references and from a class with slots? | What is a correct way to pickle an object from a class with slots, when this object references itself through one of its attributes? Here is a simple example, with my current implementation, which I'm not sure is 100 % correct:
import weakref
import pickle
class my_class(object):
__slots__ = ('an_int', 'ref_to_s... | [
"It looks like what the original post suggests works well enough.\nAs for what PEP 307 reads:\n\nThe __getstate__ method should return a picklable value representing the object's state without referencing the object itself.\n\nI understand that it only means that the __getstate__ method simply must return a represe... | [
6
] | [] | [] | [
"pickle",
"python",
"slots"
] | stackoverflow_0002922628_pickle_python_slots.txt |
Q:
Eclipse + Django: How to get bytecode output when python source files change?
Whenever I change my python source files in my Django project, the .pyc files become out of date. Of course that's because I need to recompile them in order to test them through my local Apache web server. I would like to get around th... | Eclipse + Django: How to get bytecode output when python source files change? | Whenever I change my python source files in my Django project, the .pyc files become out of date. Of course that's because I need to recompile them in order to test them through my local Apache web server. I would like to get around this manual process by employing some automatic means of compiling them on save, or o... | [
"You shouldn't ever need to 'compile' your .pyc files manually. This is always done automatically at runtime by the Python interpreter.\nIn rare instances, such as when you delete an entire .py module, you may need to manually delete the corresponding .pyc. But there's no need to do any other manual compiling.\nWha... | [
2
] | [] | [] | [
"build",
"build_process",
"bytecode",
"django",
"python"
] | stackoverflow_0003031383_build_build_process_bytecode_django_python.txt |
Q:
Setting custom SQL in django admin
I'm trying to set up a proxy model in django admin. It will represent a subset of the original model. The code from models.py:
class MyManager(models.Manager):
def get_query_set(self):
return super(MyManager, self).get_query_set().filter(some_column='value')
class ... | Setting custom SQL in django admin | I'm trying to set up a proxy model in django admin. It will represent a subset of the original model. The code from models.py:
class MyManager(models.Manager):
def get_query_set(self):
return super(MyManager, self).get_query_set().filter(some_column='value')
class MyModel(OrigModel):
objects = MyMana... | [
"Django provides the extra() QuerySet modifier -- a hook for injecting specific clauses into the SQL generated by a QuerySet.\nThis can be used in complex cases, maybe with one or more additional queries.\n",
"If you want to use the ORM further in MyModel.objects raw SQL is no solution. In the case of raw SQL an ... | [
2,
1
] | [] | [] | [
"django_admin",
"python",
"sql"
] | stackoverflow_0003009826_django_admin_python_sql.txt |
Q:
How can I calculate new time zone in python?
Lets say I have a time 04:05 and the timezone is -0100 (GMT)
I want to calculate the new time which will be 03:05
Is there any function in python to do that calculcation ?
Thanks
A:
Try something like this:
>>> import datetime
>>> my_time = datetime.datetime.str... | How can I calculate new time zone in python? | Lets say I have a time 04:05 and the timezone is -0100 (GMT)
I want to calculate the new time which will be 03:05
Is there any function in python to do that calculcation ?
Thanks
| [
"Try something like this:\n >>> import datetime\n >>> my_time = datetime.datetime.strptime('04:05', '%H:%M')\n >>> my_time\n datetime.datetime(1900, 1, 1, 4, 5)\n >>> offset_str = '-0100'\n >>> offset = datetime.timedelta(hours=int(offset_str.lstrip('-')[:2]), minutes=int(offset_str.lstrip('-')[2:])) * ... | [
1,
0
] | [] | [] | [
"datetime",
"gmt",
"python",
"time",
"timezone"
] | stackoverflow_0003031615_datetime_gmt_python_time_timezone.txt |
Q:
Comments on this assumption about running on dev server vs a real instance in app engine (python)?
I'm on an app engine project where I'd like to put in a link to a Javascript test runner that I'd like to only exist when running the development server. I've made some experiments on a local shell with configuration... | Comments on this assumption about running on dev server vs a real instance in app engine (python)? | I'm on an app engine project where I'd like to put in a link to a Javascript test runner that I'd like to only exist when running the development server. I've made some experiments on a local shell with configuration loaded using the technique found in NoseGAE versus live on the 'App Engine Console' [1] and it looks to... | [
"The standard way to test for the development server is as follows:\nDEBUG = os.environ['SERVER_SOFTWARE'].startswith(\"Dev\")\n\nRelying on the existence or nonexistence of a particular module - especially an undocumented one - is probably a bad idea.\n",
"I'd recommend doing it this way:\nimport os\ndef onDevSe... | [
6,
1,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003031886_google_app_engine_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.