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:
Connect to a website using Python
Let's say I want to connect an app I created to a website (SSL) to get values from the content at a certain page.
How can I do it?
A:
httplib2 if you wanna make https call. Check out the doc for more info.
--Sai
A:
If you need something more complex you could use mechanize, wh... | Connect to a website using Python | Let's say I want to connect an app I created to a website (SSL) to get values from the content at a certain page.
How can I do it?
| [
"httplib2 if you wanna make https call. Check out the doc for more info.\n--Sai\n",
"If you need something more complex you could use mechanize, which is a Python library that simulates a browser. So you can interact with the page just like with a normal browser (in case there's no simple direct URL you could ret... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004828238_python.txt |
Q:
PyQt vs PySide comparison
I currently develop many applications in a Qt heavy C++/Python environment on Linux, porting to PC/Mac as needed. I use Python embedded in C++ as well as in a stand alone GUI. Qt is used fro xml parsing/event handling/GUI/threading and much more. Right now all my Python work is in PyQt an... | PyQt vs PySide comparison | I currently develop many applications in a Qt heavy C++/Python environment on Linux, porting to PC/Mac as needed. I use Python embedded in C++ as well as in a stand alone GUI. Qt is used fro xml parsing/event handling/GUI/threading and much more. Right now all my Python work is in PyQt and I wanted to see how everyone ... | [
"We were recently thinking about using PySide, but we haven't found any information about whether it is supported by py2exe. That's why we kept to PyQt. If you need to develop for Windows, it's safer to use good ol' PyQt :-)\n",
"As of PySide 1.0 beta (Qt 4.7.1), there is an official Windows installer that works.... | [
8,
0
] | [
"PySide currently does not run on Windows, which limits your capability. If you were developing on Linux and needed to avoid pure GPL, then PySide is a candidate. \nFrom an API standpoint, I find the signal/slots capability feels more \"Pythonic\".\n"
] | [
-1
] | [
"c++",
"pyqt",
"pyside",
"python",
"qt"
] | stackoverflow_0002058492_c++_pyqt_pyside_python_qt.txt |
Q:
Change skin colour programmatically
Does anyone have any information or advice about adjusting one image so that the skin tones in it will match that of another image?
It is a bit of an obscure question but I was hoping there would be someone that has come across this problem before! The purpose of me doing this i... | Change skin colour programmatically | Does anyone have any information or advice about adjusting one image so that the skin tones in it will match that of another image?
It is a bit of an obscure question but I was hoping there would be someone that has come across this problem before! The purpose of me doing this is so that I can replace a face in one ima... | [
"Here's some general high-level advice for how to get started.\nBasically, what you are doing is an optimization problem. These algorithms are used for a lot of problems, and there are several well-known ways to do this. They boil down to this\n\nCreate a scoring function that can tell you a single number of how g... | [
4
] | [] | [] | [
"image_manipulation",
"image_processing",
"python",
"skin"
] | stackoverflow_0003345637_image_manipulation_image_processing_python_skin.txt |
Q:
Determine coding of text
I'm getting some weird characters as a response to a webpage. I'm pretty sure its a message in Russian language, but the coding seems to be all weird. The webpage info tells me the the encoding is ISO-8859-1. Here is the sample response.
Âû ñòðàíè÷êå ïðåâüþøêàìè
Is there a way to decrypt ... | Determine coding of text | I'm getting some weird characters as a response to a webpage. I'm pretty sure its a message in Russian language, but the coding seems to be all weird. The webpage info tells me the the encoding is ISO-8859-1. Here is the sample response.
Âû ñòðàíè÷êå ïðåâüþøêàìè
Is there a way to decrypt this response? Is the response... | [
"It looks like the encoding is actually Cyrillic Windows-1251. Switch your web-browsers encoding accordingly.\nFor example, the text you supplied in that encoding is:\n\nВы страничке превьюшками\n\nwhich an auto-translation says means \"You page previews\".\n",
"It is hardly possible to automatically recognize 8... | [
4,
3
] | [] | [] | [
"character_encoding",
"iso_8859_1",
"python",
"unicode"
] | stackoverflow_0004829025_character_encoding_iso_8859_1_python_unicode.txt |
Q:
How to make the argument to filter() a variable?
I have this model
class Item(db.Model):
...
glam = db.StringProperty()
casual = db.StringProperty()
speaking = db.StringProperty()
and this handler with a form with radio buttons:
class SortForm(webapp.RequestHandler):
def get(self):
... | How to make the argument to filter() a variable? | I have this model
class Item(db.Model):
...
glam = db.StringProperty()
casual = db.StringProperty()
speaking = db.StringProperty()
and this handler with a form with radio buttons:
class SortForm(webapp.RequestHandler):
def get(self):
self.response.out.write("""
<form name="su... | [
"Would that do what you're looking for:\nchoice = self.request.get(\"tag\")\nquery.filter(choice, choice)\n\nHowever, I agree with Wooble below. The way you have designed it, you dont' really use glam, casual, speaking as StringProperty, since they are either empty or have a specific value.\nWhat you probably want ... | [
3,
1
] | [] | [] | [
"filter",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004829138_filter_google_app_engine_google_cloud_datastore_python.txt |
Q:
Python and C++ script interaction
I am trying to optimize the interaction between two scripts I have.
Two things I thought of are the c++ program not terminating unless you manually kill it, or generating all info in python before feeding it to c++.
Explanation of the problem:
What the scripts do:
C++ program (not... | Python and C++ script interaction | I am trying to optimize the interaction between two scripts I have.
Two things I thought of are the c++ program not terminating unless you manually kill it, or generating all info in python before feeding it to c++.
Explanation of the problem:
What the scripts do:
C++ program (not made by me, and I can't program in c++... | [
"Firstly, just to be pedantic, there are no C++ scripts in normal use. C++ compiles, ultimately, to machine code, and the C++ program is properly referred to as a \"program\" and not a \"script\".\nBut to answer your question, you could indeed set up the C++ program to stay in memory, where it listens for connectio... | [
1,
1,
1,
0,
0
] | [] | [] | [
"c++",
"interaction",
"optimization",
"python"
] | stackoverflow_0004826896_c++_interaction_optimization_python.txt |
Q:
Python search list of objects that contain objects, partial matches
I'm trying to build a simple search engine for a small website. My initial thought is to avoid using larger packages such as Solr, Haystack, etc. because of the simplistic nature of my search needs.
My hope is that with some guidance I can make my... | Python search list of objects that contain objects, partial matches | I'm trying to build a simple search engine for a small website. My initial thought is to avoid using larger packages such as Solr, Haystack, etc. because of the simplistic nature of my search needs.
My hope is that with some guidance I can make my code more pythonic, efficient, and most importantly function properly.
I... | [
"Prepare all variables outside of the loops and use in instead of .find if you don't need the position of the substring:\ndef product_search(*params):\n results = []\n upperParams = [ param.upper() for param in params ]\n\n for product in products:\n name = str(product.name).upper()\n item_nu... | [
0,
0
] | [] | [] | [
"full_text_search",
"pymssql",
"python",
"search"
] | stackoverflow_0004829250_full_text_search_pymssql_python_search.txt |
Q:
Excel VBA FormatConditions in Python
I am trying to convert the following code into python:
Columns("C:C").Select
Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreaterEqual _
, Formula1:="=50"
Selection.FormatConditions(Selection.FormatConditions.... | Excel VBA FormatConditions in Python | I am trying to convert the following code into python:
Columns("C:C").Select
Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreaterEqual _
, Formula1:="=50"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With S... | [
"Probably change\nexcel.XlFormatConditionType.xlCellValue\nexcel.XlFormatConditionOperator.xlGreaterEqual\n\nto \nwin32com.client.constants.xlCellValue\nwin32com.client.constants.xlGreaterEqual\n\n"
] | [
3
] | [] | [] | [
"excel",
"python",
"vba"
] | stackoverflow_0004829310_excel_python_vba.txt |
Q:
How to filter() for different items?
This is a follow up to my previous question.
I am using the same model
class Item(db.Model):
...
glam = db.StringProperty()
casual = db.StringProperty()
speaking = db.StringProperty()
and assume that I have 2 items and 1 is tagged "glam" the other tagged "sp... | How to filter() for different items? | This is a follow up to my previous question.
I am using the same model
class Item(db.Model):
...
glam = db.StringProperty()
casual = db.StringProperty()
speaking = db.StringProperty()
and assume that I have 2 items and 1 is tagged "glam" the other tagged "speaking".
If I filter like this
query.f... | [
"With your current schema and the current datastore API, you cannot acheive this with a single query.\nIf 'glam', 'casual', and 'speaking' are mutually exclusive, you can use an IN query on a single field:\nclass Item(db.Model):\n ...\n tag = db.StringProperty()\n\nquery.filter(\"tag IN\", [\"glam\", \"speaking... | [
1
] | [] | [] | [
"filter",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004829736_filter_google_app_engine_google_cloud_datastore_python.txt |
Q:
Speed up a program that calculate the average of the neighbors in a huge array
I have a problem with the speed of my program. I want to calculate the average of four neighbors in a huge array. Here is a part of my code. Do you have any ideas how to change the last line? Or should I use another array?
for a in np.a... | Speed up a program that calculate the average of the neighbors in a huge array | I have a problem with the speed of my program. I want to calculate the average of four neighbors in a huge array. Here is a part of my code. Do you have any ideas how to change the last line? Or should I use another array?
for a in np.arange(100000):
for x in np.arange(size):
for y in np.arange(size):
... | [
"You would not need the loop at all. Assuming v, vnew and unchangeableflag are 1-d arrays with size*size entries, you can do\nv = v.reshape(size, size)\nvnew = vnew.reshape(size, size)\nunchangeableflag = unchangeableflag.reshape(size, size)\naverage = v[1:-1, 2:]\naverage += v[1:-1, :-2] \naverage += v[2:, 1:-1]\... | [
4,
3,
1
] | [] | [] | [
"numerical",
"numpy",
"performance",
"python"
] | stackoverflow_0004829738_numerical_numpy_performance_python.txt |
Q:
Efficiently solving a letter/number problem in Python
If a = 15 and 152 is represented as a2 while 215 is represented as 2a then a number x has to be found such that
8x = 8*x8
I tried this naive Python code
>>> i = 0
>>> while(i<=100000000000000000):
... if(int("8"+str(i))==8*int(str(i)+"8")):
... break
... ... | Efficiently solving a letter/number problem in Python | If a = 15 and 152 is represented as a2 while 215 is represented as 2a then a number x has to be found such that
8x = 8*x8
I tried this naive Python code
>>> i = 0
>>> while(i<=100000000000000000):
... if(int("8"+str(i))==8*int(str(i)+"8")):
... break
... i = i+1
... print i
but it is taking a huge amount of ti... | [
"A bit of math helps here: Let x be a natural number with n digits. Then 8x = 8 * 10^n + x, and x8 = 10*x + 8. So the equation to be solved is 8 * 10^n + x = 8 * (10*x + 8) = 80*x + 64, where x and n must be natural numbers. It immediately follows that x = (8 * 10^n - 64) / 79. Now we only have to check which of th... | [
10,
1
] | [] | [] | [
"math",
"python"
] | stackoverflow_0004829950_math_python.txt |
Q:
Running Time Complexity of my Algorithm - how do i compute this and further optimize the algorithm?
I designed a recursive algorithm and wrote it down in Python. When I measure the running time with different parameters, it seems to take exponential time. Furthermore; it takes more than half an hour to end with sm... | Running Time Complexity of my Algorithm - how do i compute this and further optimize the algorithm? | I designed a recursive algorithm and wrote it down in Python. When I measure the running time with different parameters, it seems to take exponential time. Furthermore; it takes more than half an hour to end with small numbers such as 50. (I didn't wait until it finishes, but it doesn't seem to finish in a reasonable a... | [
"You can do it in O(n + m), where m is the number of characters in SEA, and n the number of characters in SRC:\nlast = 1\nfor i = 1 to m do\n while SRC[last] != SEA[i]\n ++last\n\n print last\n ++last (skip this match)\n\nBasically, for each character in SEA, find its position in SRC, but only scan ... | [
4,
3,
0
] | [] | [] | [
"algorithm",
"big_o",
"exponential",
"python",
"time_complexity"
] | stackoverflow_0004829332_algorithm_big_o_exponential_python_time_complexity.txt |
Q:
combinatorics implementation and puzzle
Found this puzzle inside an image. According to my thinking the total number of ways should be
2*comb(7,i) for i <- 1 to 7 where comb is defined as follows. Is my approach correct? I am concerned with the result that I get and not the function written below.
def comb(N,k):
... | combinatorics implementation and puzzle |
Found this puzzle inside an image. According to my thinking the total number of ways should be
2*comb(7,i) for i <- 1 to 7 where comb is defined as follows. Is my approach correct? I am concerned with the result that I get and not the function written below.
def comb(N,k):
if (k > N) or (N < 0) or (k < 0):
... | [
"There are 7! ways to line up the children (7 choices for the first spot, 6 for the second, 5 for the third, etc.)\nEach child can face inward or outward. That's like an extra bit for each position.\nSo multiply by 2**7. (i.e. there are 2 choices for each spot).\nNow for each ordering, if you rotate the circle, you... | [
6
] | [] | [] | [
"combinatorics",
"math",
"python"
] | stackoverflow_0004830376_combinatorics_math_python.txt |
Q:
os.stat failing on file with funky characters
Using Python 2.6.5 on Windows XP, I'm processing a directory of files by calling os.stat on them to obtain their size. The script is failing when it reaches a particular file that happens to have non-ASCII characters embedded within the name. The exception being thrown... | os.stat failing on file with funky characters | Using Python 2.6.5 on Windows XP, I'm processing a directory of files by calling os.stat on them to obtain their size. The script is failing when it reaches a particular file that happens to have non-ASCII characters embedded within the name. The exception being thrown is that os.stat couldn't find the file specified. ... | [
"Try inserting the line # coding=UTF-8 at the top of your python file (only makes a difference for unicode in your script, as Philipp points out), and make sure you are storing the file names as unicode instead of str.\nTested with the following:\n# coding=UTF-8\n\nimport os\nfname = u'/temp/1-02 Só Danço Samba (... | [
1
] | [] | [] | [
"python",
"windows_xp"
] | stackoverflow_0004829669_python_windows_xp.txt |
Q:
HTTP Error 400 when trying to send json data with urllib2 to toggl api
When using the following code to connect to the toggl api I connect and am authorised just fine.
username = token
password = 'api_token'
url = 'http://www.toggl.com/api/v3/tasks.json'
req = urllib2.Request(url)
auth_string = base64.encodestrin... | HTTP Error 400 when trying to send json data with urllib2 to toggl api | When using the following code to connect to the toggl api I connect and am authorised just fine.
username = token
password = 'api_token'
url = 'http://www.toggl.com/api/v3/tasks.json'
req = urllib2.Request(url)
auth_string = base64.encodestring('%s:%s' % (username, password))
req.add_header("Authorization", "Basic %s"... | [
"According to the API documentation, you're missing at least a header. Try:\nreq = urllib2.Request(url, data, {\"Content-type\": \"application/json\"})\n\nIf that's not enough, try using urllib.urlencode on data. If that's still not enough, add a user:password to the request, like in the API example.\n",
"I have ... | [
3,
2
] | [] | [] | [
"json",
"python",
"urllib2"
] | stackoverflow_0004807328_json_python_urllib2.txt |
Q:
How to Create Multiple FormatConditions in Excel using Python
With the following code, in theory, it should set 2 different formatconditions with different colors for each one in the range of F through AA columns. Unfortunetly once I run this Python script, excel only gets the information for the first condition, ... | How to Create Multiple FormatConditions in Excel using Python | With the following code, in theory, it should set 2 different formatconditions with different colors for each one in the range of F through AA columns. Unfortunetly once I run this Python script, excel only gets the information for the first condition, where the 2nd condition is in excel but missing the color fill. Any... | [
"Found my mistake I needed to set the index of FormatConditions:\n formula1 = \"=95\" \n formula2 = \"=100\"\n wb.ActiveSheet.Columns(\"F:AA\").FormatConditions.Add(win32c.xlCellValue , win32c.xlBetween , formula1,formula2) \n #wb.ActiveSheet.Columns(\"F:AA\")... | [
1
] | [] | [] | [
"excel",
"python",
"vba"
] | stackoverflow_0004830378_excel_python_vba.txt |
Q:
How to create a text file in python without csv.writer?
I need a comma seperated txt file with txt extension.
"a,b,c"
I used csv.writer to create a csv file changed the extension. Another prog would not use/process the data. I tried "wb", "w."
F = open(Fn, 'w')
w = csv.writer(F)
w.writerow(sym)
F.close()
opene... | How to create a text file in python without csv.writer? | I need a comma seperated txt file with txt extension.
"a,b,c"
I used csv.writer to create a csv file changed the extension. Another prog would not use/process the data. I tried "wb", "w."
F = open(Fn, 'w')
w = csv.writer(F)
w.writerow(sym)
F.close()
opened with notepad ---These are the complete files.
Their file: c... | [
"To me, it look like you don't exactly know you third party application input format. If a .CSV isn't reconized, it might be something else.\nDid you try to change the delimiter fromn ';' to ',' \nimport csv\nspamWriter = csv.writer(open('eggs.csv', 'wb'), delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\ns... | [
3,
2,
1,
1,
1
] | [] | [] | [
"csv",
"python",
"text_files"
] | stackoverflow_0004818367_csv_python_text_files.txt |
Q:
arranging definitions
in python there is way to declare def's without putting it in class. So, if i just need to store many def's in separated class, i should simple do this:
def first_method():
pass
def second_method():
pass
and not use @classmethod or @staticmethod?:
class methods():
@classmethod
... | arranging definitions | in python there is way to declare def's without putting it in class. So, if i just need to store many def's in separated class, i should simple do this:
def first_method():
pass
def second_method():
pass
and not use @classmethod or @staticmethod?:
class methods():
@classmethod
def first_method(cls):
... | [
"Yes. Just keep functions that are not instance methods out of your classes.\nYou're thinking like you would in Java. Python isn't Java. Python has no true way to have public and private methods -- you can change the names to indicate that you'd like some form of privacy (_ or __ at the beginning of the name), but ... | [
3,
3
] | [] | [] | [
"function",
"oop",
"python"
] | stackoverflow_0004831253_function_oop_python.txt |
Q:
Django Can't Read Membase Data?
I have two Membase clients - a Django website and a small python test file. I observed that the data saved by the python file can't be seen by the Django website, it returns None. However, If I save the same data (same keys and values) in the Django website, the site will be able to... | Django Can't Read Membase Data? | I have two Membase clients - a Django website and a small python test file. I observed that the data saved by the python file can't be seen by the Django website, it returns None. However, If I save the same data (same keys and values) in the Django website, the site will be able to read the keys/values then.
This is t... | [
"A good troubleshooting step is just to telnet manually to 127.0.0.1 on port 11211 and do a 'get ' for that key. If you get something back then at least you know the Membase server is functioning properly and you can focus on the Django side of things...where I'm much less knowledgeable.\n"
] | [
1
] | [] | [] | [
"membase",
"python"
] | stackoverflow_0004829903_membase_python.txt |
Q:
Making shlex.split respect UNC paths
I'm using shlex.split to tokenize arguments for a subprocess.Popen call. However, when one of those args is a UNC path, things get hairy:
import shlex
raw_args = '-path "\\\\server\\folder\\file.txt" -arg SomeValue'
args = shlex.split(raw_args)
print raw_args
print args
prod... | Making shlex.split respect UNC paths | I'm using shlex.split to tokenize arguments for a subprocess.Popen call. However, when one of those args is a UNC path, things get hairy:
import shlex
raw_args = '-path "\\\\server\\folder\\file.txt" -arg SomeValue'
args = shlex.split(raw_args)
print raw_args
print args
produces
-path "\\server\folder\file.txt" -arg... | [
"I don't know if this helps you:\n>>> shlex.split(raw_args, posix=False)\n['-path', '\"\\\\\\\\server\\\\folder\\\\file.txt\"', '-arg', 'SomeValue']\n\n",
"Try this:\nraw_args = r'-path \"\\\\\\\\server\\\\folder\\\\file.txt\" -arg SomeValue'\n\nNote r before the opening single quote.\n"
] | [
14,
0
] | [] | [] | [
"python",
"shlex"
] | stackoverflow_0004830874_python_shlex.txt |
Q:
Matplotlib not displaying figures
This must be a really basic question: I am trying to use Matplotlib. Here's the basic example from the documentation.
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,5,0.1)
y = np.sin(x)
plt.plot(x,y)
I have tried this in ipython, bpython and the default interp... | Matplotlib not displaying figures | This must be a really basic question: I am trying to use Matplotlib. Here's the basic example from the documentation.
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,5,0.1)
y = np.sin(x)
plt.plot(x,y)
I have tried this in ipython, bpython and the default interpreter (Ubuntu 10.10, 64 bit) and all I ... | [
"You're missing plt.show() to order matplotlib to show a window with the graph.\n",
"In its default configuration, matplotlib needs to be told to render. That's what plt.show() does.\nMatplotlib also has an interactive mode that can be useful when you're working interactively and want your plotting commands to ... | [
15,
6
] | [] | [] | [
"matplotlib",
"numpy",
"python",
"scipy"
] | stackoverflow_0004831220_matplotlib_numpy_python_scipy.txt |
Q:
What can be used instead of parse_qs function
I have the following code for parsing youtube feed and returning youtube movie id. How can I rewrite this to be python 2.4 compatible which I suppose doesn't support parse_qs function ?
YTSearchFeed = feedparser.parse("http://gdata.youtube.com" + path)
videos = []
for ... | What can be used instead of parse_qs function | I have the following code for parsing youtube feed and returning youtube movie id. How can I rewrite this to be python 2.4 compatible which I suppose doesn't support parse_qs function ?
YTSearchFeed = feedparser.parse("http://gdata.youtube.com" + path)
videos = []
for yt in YTSearchFeed.entries:
url_data = urlparse... | [
"I assume your existing code runs in 2.6 or something newer, and you're trying to go back to 2.4? parse_qs used to be in the cgi module before it was moved to urlparse. Try import cgi, cgi.parse_qs.\nInspired by TryPyPy's comment, I think you could make your source run in either environment by doing:\nimport urlp... | [
13
] | [
"I tried that, and still.. it wasn't working.\nIt's easier to simply copy the parse_qs/qsl functions over from the cgi module to the urlparse module.\nProblem solved.\n"
] | [
-3
] | [
"deprecated",
"feedparser",
"python",
"python_2.4"
] | stackoverflow_0004646560_deprecated_feedparser_python_python_2.4.txt |
Q:
GTK+ Filechooser to open both files and folders
How do I get my filechooser to be able to select both files and folders when the open button on the filechooser dialog is hit ? I want to squeeze the ability to open files and filders in just one filechooser. I am using GTK+ and Python.
A:
I was thinking about this... | GTK+ Filechooser to open both files and folders | How do I get my filechooser to be able to select both files and folders when the open button on the filechooser dialog is hit ? I want to squeeze the ability to open files and filders in just one filechooser. I am using GTK+ and Python.
| [
"I was thinking about this, and although in your comments you've decided to go another route, I do have a suggestion: Write your own file chooser subclass of the GTK+ one and provide two \"Open\" buttons, one to \"Open File\" and another to \"Open Directory\". That would eliminate the ambiguity discussed above.\n"
... | [
2
] | [] | [] | [
"filechooser",
"gtk",
"pygtk",
"python"
] | stackoverflow_0004376500_filechooser_gtk_pygtk_python.txt |
Q:
How to pickle a callback chain
I have a user-defined state machine in Twisted. The user can define handlers for different state changes, which I implement by using a Twisted deferred that I let them add callbacks to. Whenever I move from one state to another, I simply fire the appropriate deferred.
One of the proj... | How to pickle a callback chain | I have a user-defined state machine in Twisted. The user can define handlers for different state changes, which I implement by using a Twisted deferred that I let them add callbacks to. Whenever I move from one state to another, I simply fire the appropriate deferred.
One of the project requirements is the ability to s... | [
"Don't try to pickle Deferreds. It's not supported by Twisted. Even if you manage to construct something that seems to work (and it's not entirely impossible), a later release of Twisted might break all of your saved state.\nDeferreds are for controlling the flow of events through your code. They're not for stor... | [
2,
0
] | [] | [] | [
"deferred",
"pickle",
"python",
"twisted"
] | stackoverflow_0004831178_deferred_pickle_python_twisted.txt |
Q:
I'm using Django user authentication with PHP. Will this cookie based authentication scheme be secure?
I have a site written in PHP, and am adding new features using Python and Django. Part of this will be Django authentication using the standard contribs.auth package.
Once someone has logged in using our Django s... | I'm using Django user authentication with PHP. Will this cookie based authentication scheme be secure? | I have a site written in PHP, and am adding new features using Python and Django. Part of this will be Django authentication using the standard contribs.auth package.
Once someone has logged in using our Django set up, when they come to the PHP side I need to see that they're logged in and use user info from the databa... | [
"If you can unpickle in PHP what Django pickled into the session, then you can just grab the relevant session data directly form database (using session id from cookie), and then you'll have a direct info which user is logged in Django site - if any.\nEDIT:\nHere's the \"encryption\" Django uses: \nhttp://code.djan... | [
3,
0
] | [] | [] | [
"authentication",
"cookies",
"django",
"php",
"python"
] | stackoverflow_0004827701_authentication_cookies_django_php_python.txt |
Q:
How to loop through the one-to-many relations query results?
I am confused about how to filter and display one-to-many relations.
Following this question and this article (and my previous question) I created a new ReferenceProperty Tag in addition to Item:
class Item(db.Model):
...
title = db.StringPropert... | How to loop through the one-to-many relations query results? | I am confused about how to filter and display one-to-many relations.
Following this question and this article (and my previous question) I created a new ReferenceProperty Tag in addition to Item:
class Item(db.Model):
...
title = db.StringProperty()
url = db.StringProperty()
image_source_url = db.String... | [
"You need two loops here. query is a list of Tag objects. Each object itself has a list of items. So you need to loop through query, then through each tag's items.\nHowever, there is a second problem: the ReferenceProperty is the wrong way round. As I understand it, a ReferenceProperty is like a ForeignKey in norma... | [
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"one_to_many",
"python"
] | stackoverflow_0004831787_google_app_engine_google_cloud_datastore_one_to_many_python.txt |
Q:
Cannot import markdown because of COMMAND_LINE_LOGGING_LEVEL
I've got a weird error where I can import markdown in Python, and I can import markdown in python inside the Django runserver, but I get the following when trying to import markdown inside of gunicorn's app server.
* ImportError: cannot import name COMMA... | Cannot import markdown because of COMMAND_LINE_LOGGING_LEVEL | I've got a weird error where I can import markdown in Python, and I can import markdown in python inside the Django runserver, but I get the following when trying to import markdown inside of gunicorn's app server.
* ImportError: cannot import name COMMAND_LINE_LOGGING_LEVEL
This is even more confusing because I found ... | [
"Gunicorn, for reasons I don't understand yet, adds the virtualenv/bin directory to the sys.path. Markdown installs a markdown.py into that bin directory. That markdown.py tries to import COMMAND_LINE_LOGGING_LEVEL from markdown the library. This results in a circular failure.\nI don't know why Gunicorn does this, ... | [
2,
2
] | [] | [] | [
"django",
"markdown",
"python"
] | stackoverflow_0004270893_django_markdown_python.txt |
Q:
How to aggregate data from one collection into another in efficient way using MongoDB?
I have a problem that i am not sure how to solve efficiently.
I have two collections:
1)
hits = {
'day': '',
'number_of_hits': 0
'user_id': 0
}
2)
stats = {
'day': '',
'total_number_of_hits': 0
'user_id... | How to aggregate data from one collection into another in efficient way using MongoDB? | I have a problem that i am not sure how to solve efficiently.
I have two collections:
1)
hits = {
'day': '',
'number_of_hits': 0
'user_id': 0
}
2)
stats = {
'day': '',
'total_number_of_hits': 0
'user_id': 0
...
some other stuff
}
I need to get sums of number_of_hits for each day (ther... | [
"May be try to re-design you structure as\nstats{\n 'day': '',\n 'user_id': 0,\n 'hits':{ \n // Array of your hits document\n }\n}\n\nand get only one document with all hits. You can calculate total at any time.\n",
"Your problem seems like a classic case for Mongo's map/reduce capabilities. See h... | [
3,
0,
0
] | [] | [] | [
"mapreduce",
"mongodb",
"python"
] | stackoverflow_0004830602_mapreduce_mongodb_python.txt |
Q:
Converting An Integer to a Byte (for PySerial, using Python25)
This seems like it should be simple, but I haven't been able to figure it out...
I'm trying to use PySerial to communicate with a microcontroller. I want to send an index location, but when I send it, it PySerial sends the ASCII of the number (so when... | Converting An Integer to a Byte (for PySerial, using Python25) | This seems like it should be simple, but I haven't been able to figure it out...
I'm trying to use PySerial to communicate with a microcontroller. I want to send an index location, but when I send it, it PySerial sends the ASCII of the number (so when I send a 0, it sends 48).
I know for Python26 and up, I would just ... | [
"chr is built-in which will you the character for the ordinal you send.\n",
"Serial communicates in ascii, so you want to use chr to convert numbers to their ascii character equivalents.\n",
"Have you tried the binascii module?\nhttp://docs.python.org/release/2.5.4/lib/module-binascii.html\n"
] | [
2,
1,
0
] | [] | [] | [
"python",
"python_2.5"
] | stackoverflow_0004832671_python_python_2.5.txt |
Q:
How does Blippy get its data
I was wondering how Blippy is able to get my data? It requires me to put in my bank name, bank card number and password, so is it doing a simple website scrape by logging in?
My bank, however also requires a seperate passphrase as well. How does it get around that?
Can urllib and such ... | How does Blippy get its data | I was wondering how Blippy is able to get my data? It requires me to put in my bank name, bank card number and password, so is it doing a simple website scrape by logging in?
My bank, however also requires a seperate passphrase as well. How does it get around that?
Can urllib and such libraries be used in Python to rep... | [
"Blippy probably uses a service like Yodlee to interface with the bank rather that simple screen scraping. Having said that it is possible to implement similar functionality by combining urllib, BeautifulSoup and Regex modules.\n"
] | [
0
] | [] | [] | [
"python",
"screen_scraping",
"web_applications"
] | stackoverflow_0002914731_python_screen_scraping_web_applications.txt |
Q:
Python: Metaclasses all the way down
I have an esoteric question involving Python metaclasses. I am creating a Python package for web-server-side code that will make it easy to access arbitrary Python classes via client-side proxies. My proxy-generating code needs a catalog of all of the Python classes that I wa... | Python: Metaclasses all the way down | I have an esoteric question involving Python metaclasses. I am creating a Python package for web-server-side code that will make it easy to access arbitrary Python classes via client-side proxies. My proxy-generating code needs a catalog of all of the Python classes that I want to include in my API. To create this c... | [
"\nShould my metaclass be a subclass of Enthought's metaclass?\n\nI believe that is in fact your only choice. If the metaclass of a derived class is not a subclass of the metaclasses of all of its bases then Python will throw a TypeError when you try to create the derived class. So your metaclass for PythonDirectPu... | [
5,
1
] | [] | [] | [
"metaclass",
"python",
"traits"
] | stackoverflow_0003346262_metaclass_python_traits.txt |
Q:
Read in tuple of lists from text file as tuple, not string - Python
I have a text file I would like to read in that contains rows of tuples. Each tuple/row in text is in the form of ('description string', [list of integers 1], [list of integers 2]). Where the text file might look something like:
('item 1', [1,2,3... | Read in tuple of lists from text file as tuple, not string - Python | I have a text file I would like to read in that contains rows of tuples. Each tuple/row in text is in the form of ('description string', [list of integers 1], [list of integers 2]). Where the text file might look something like:
('item 1', [1,2,3,4] , [4,3,2,1])
('item 2', [ ] , [4,3,2,1])
('item 3, [1,2] , [ ])
I wou... | [
"You're looking for ast.literal_eval().\n>>> ast.literal_eval(\"('item 1', [1,2,3,4] , [4,3,2,1])\")\n('item 1', [1, 2, 3, 4], [4, 3, 2, 1])\n\n",
"What about using eval? \nEDIT See @Ignacio's answer using ast.literal_eval.\n>>> c = eval(\"('item 1', [1,2,3,4] , [4,3,2,1])\")\n>>> c\n('item 1', [1, 2, 3, 4], [4... | [
20,
13,
1
] | [] | [] | [
"file",
"list",
"python",
"text",
"tuples"
] | stackoverflow_0004832789_file_list_python_text_tuples.txt |
Q:
the order in which result of a set is printed in Python
I do the following in the command prompt:
>>> a=set()
>>> for i in range(0,8):
... a.add((i,j))
...
the answer that I get when I print it is like this:
>>> a
set([(2, 7), (4, 7), (6, 7), (5, 7), (7, 7), (0, 7), (1, 7), (3, 7)])
I understand that its pr... | the order in which result of a set is printed in Python | I do the following in the command prompt:
>>> a=set()
>>> for i in range(0,8):
... a.add((i,j))
...
the answer that I get when I print it is like this:
>>> a
set([(2, 7), (4, 7), (6, 7), (5, 7), (7, 7), (0, 7), (1, 7), (3, 7)])
I understand that its printing out the results in the way its stored. But is there a ... | [
"You are right that a set doesn't store its elements in sorted order. If you want to get a list of the elements in the set in sorted order you can use the built-in function sorted:\n>>> a\nset([(2, 7), (4, 7), (6, 7), (5, 7), (7, 7), (0, 7), (1, 7), (3, 7)])\n>>> sorted(a)\n[(0, 7), (1, 7), (2, 7), (3, 7), (4, 7), ... | [
11,
2
] | [] | [] | [
"python"
] | stackoverflow_0004833297_python.txt |
Q:
Translate github flavored markdown regex from ruby to python
I'm trying to get an implementation of github flavored markdown working in python, with no luck... I don't have much in the way of regex skills.
Here's the ruby code from github:
# in very clear cases, let newlines become <br /> tags
text.gsub!(/(\A|^$\... | Translate github flavored markdown regex from ruby to python | I'm trying to get an implementation of github flavored markdown working in python, with no luck... I don't have much in the way of regex skills.
Here's the ruby code from github:
# in very clear cases, let newlines become <br /> tags
text.gsub!(/(\A|^$\n)(^\w[^\n]*\n)(^\w[^\n]*$)+/m) do |x|
x.gsub(/^(.+)$/, "\\1 ")... | [
"That Ruby version has multiline modifier in the regex, so you need to do the same in python:\ndef newline_callback(matchobj):\n return re.sub(re.compile(r'^(.+)$', re.M),r'\\1 ',matchobj.group(0)) \n\ntext = re.sub(re.compile(r'(\\A|^$\\n)(^\\w[^\\n]*\\n)(^\\w[^\\n]*$)+', re.M), newline_callback, text)\n\n... | [
1,
0
] | [] | [] | [
"markdown",
"python",
"regex",
"ruby"
] | stackoverflow_0004827244_markdown_python_regex_ruby.txt |
Q:
can load data(google app enngine) from http://localhost:8100/remote_api
i can download data from gae (http://zjm1126.appspot.com/remote_api), this is code:
appcfg.py download_data --application=zjm1126 --url=http://zjm1126.appspot.com/remote_api --filename=a.csv
and it successful :
D:\zjm_demo\app>appcfg.py dow... | can load data(google app enngine) from http://localhost:8100/remote_api | i can download data from gae (http://zjm1126.appspot.com/remote_api), this is code:
appcfg.py download_data --application=zjm1126 --url=http://zjm1126.appspot.com/remote_api --filename=a.csv
and it successful :
D:\zjm_demo\app>appcfg.py download_data --application=zjm1126 --url=http://zjm1
126.appspot.com/remote_api... | [
"The default port is 8080, not 8100. Using 8100 would give an Authentication Failed error.\nAlso, if your app.yaml did enable the remote api using:\nbuiltins:\n- remote_api: on\n\nthen you'll need to use a url of:\nhttp://localhost:8080/_ah/remote_api\n\nand not:\nhttp://localhost:8080/remote_api\n\nAlso, you will ... | [
2,
1,
1
] | [] | [] | [
"download",
"google_app_engine",
"localhost",
"python"
] | stackoverflow_0003068143_download_google_app_engine_localhost_python.txt |
Q:
Which GUI frameworks are best for a multi-threaded Python program?
I am writing a multi-threaded Python program with a GUI, with several modules that "touch" the GUI by changing text and background colors. I am currently using PyGTK and am finding that the GUI sometimes crashes "silently" (no error messages; the p... | Which GUI frameworks are best for a multi-threaded Python program? | I am writing a multi-threaded Python program with a GUI, with several modules that "touch" the GUI by changing text and background colors. I am currently using PyGTK and am finding that the GUI sometimes crashes "silently" (no error messages; the program just terminates), and sometimes encounters segmentation faults.
... | [
"Ohh, I definitely recommend PyQt4. At first, I didn't get all this SIGNAL and EMIT nonsense, but now that I've made a program with it, the QThread module is amazingly useful. \nAs for stability, I have never had a crash, ever. Even while I was debugging half-functional code, QT didn't have any problems. It just th... | [
4,
0
] | [] | [] | [
"multithreading",
"pygtk",
"python",
"user_interface"
] | stackoverflow_0004833768_multithreading_pygtk_python_user_interface.txt |
Q:
What are the various Python CMS's and their statuses?
I'm usually a PHP developer that has lots of experience with Drupal CMS & framework. And I realize Drupal is very mature, but I don't know much about the Python scene.
I've heard the following CMSs be mentioned:
Plone
Django (framework)
What other CMSs are t... | What are the various Python CMS's and their statuses? | I'm usually a PHP developer that has lots of experience with Drupal CMS & framework. And I realize Drupal is very mature, but I don't know much about the Python scene.
I've heard the following CMSs be mentioned:
Plone
Django (framework)
What other CMSs are there, and what do you think are some of the pros and cons? ... | [
"My vote is for Django CMS. Django itself is a development framework (but one that gives you a lot for free, including an excellent pluggable admin interface). DjangoCMS is an application that you can install into a Django application. I am using DjangoCMS and, as a Django user, I think it's perfect. I'm not what n... | [
3,
3,
2
] | [] | [] | [
"content_management_system",
"django",
"python"
] | stackoverflow_0004833590_content_management_system_django_python.txt |
Q:
Accessing Javascript Button with Mechanize
I'm trying to download the currency data from bloomberg website with mechanize/python.
http://www.bloomberg.com/markets/currencies/
I've managed to update the fields to the desired currencies, unfortunately, i'm having trouble "submitting" the convert button.
I don't th... | Accessing Javascript Button with Mechanize | I'm trying to download the currency data from bloomberg website with mechanize/python.
http://www.bloomberg.com/markets/currencies/
I've managed to update the fields to the desired currencies, unfortunately, i'm having trouble "submitting" the convert button.
I don't think br.submit() is working and when I try to use... | [
"This is a pure JavaScript form. Nothing is submitted at all so you cannot access/submit it using Mechanize.\n<form id=\"currcalc\" onsubmit=\"calculate(); return false;\" action=\"#\">\n\nhttp://www.bloomberg.com/javascripts/currencycalc_10.js is the JavaScript behind the calculator and you can find the conversion... | [
1
] | [] | [] | [
"button",
"mechanize",
"python",
"submit"
] | stackoverflow_0004833839_button_mechanize_python_submit.txt |
Q:
% confuses python raw sql query
Following this SO question, I'm trying to "truncate" all tables related to a certain django application using the following raw sql commands in python:
cursor.execute("set foreign_key_checks = 0")
cursor.execute("select concat('truncate table ',table_schema,'.',table_name,';') as sq... | % confuses python raw sql query | Following this SO question, I'm trying to "truncate" all tables related to a certain django application using the following raw sql commands in python:
cursor.execute("set foreign_key_checks = 0")
cursor.execute("select concat('truncate table ',table_schema,'.',table_name,';') as sql_stmt from information_schema.tables... | [
"Have you tried %%? That quotes a % in Python string-formatting.\n"
] | [
8
] | [] | [] | [
"python",
"rawsql",
"sql_like"
] | stackoverflow_0004833966_python_rawsql_sql_like.txt |
Q:
Ruby Equivalent of Python "_"
In Python, you can use the _ field to grab the last computed value. That's really useful in IDLE. Does Ruby have an equivalent for IRB?
An example from Python:
>>> 2 + 2
4
>>> _
4
>>> "Me " + "You"
'Me You'
>>> _
'Me You'
A:
_ isn't working?
host:~ user$ irb
irb(main):001:0> s = "te... | Ruby Equivalent of Python "_" | In Python, you can use the _ field to grab the last computed value. That's really useful in IDLE. Does Ruby have an equivalent for IRB?
An example from Python:
>>> 2 + 2
4
>>> _
4
>>> "Me " + "You"
'Me You'
>>> _
'Me You'
| [
"_ isn't working?\nhost:~ user$ irb\nirb(main):001:0> s = \"test\"\n=> \"test\"\nirb(main):002:0> puts _\ntest\n=> nil\n\n",
"In IRB you can use _ as well.\n"
] | [
11,
4
] | [] | [] | [
"irb",
"python",
"python_idle",
"ruby"
] | stackoverflow_0004834125_irb_python_python_idle_ruby.txt |
Q:
What is the best method to tranfer data to a server from code
I'm writing two Django applications: one that generates a lot of data in time, and another part that displays it. The app that generate it will run on a machine at my home and the one that displays the data will be a machine on the internet.
What do you... | What is the best method to tranfer data to a server from code | I'm writing two Django applications: one that generates a lot of data in time, and another part that displays it. The app that generate it will run on a machine at my home and the one that displays the data will be a machine on the internet.
What do you believe it will be the best way to transfer the data from the appl... | [
"Setup two databases - one master and one slave. Write on the master and make the slave to sync with the master. This way you will not need to worry when your connection is down.\n",
"This is what RESTful web services are all about.\nYour web server does two things.\n\n\"displays the data\". Presumably via HTML ... | [
0,
0
] | [] | [] | [
"django",
"python",
"web_services"
] | stackoverflow_0004833299_django_python_web_services.txt |
Q:
Python Multiprocessing respawn crashed processes
I want to create some worker processes and if they crash due to an exception, I would like them to respawn. Aside from the is_alive method in the multiprocessing module, I can't seem to find a way to do this.
This would require me to iterate over all the running pro... | Python Multiprocessing respawn crashed processes | I want to create some worker processes and if they crash due to an exception, I would like them to respawn. Aside from the is_alive method in the multiprocessing module, I can't seem to find a way to do this.
This would require me to iterate over all the running processes (after a sleep) and check if they are alive. Th... | [
"Polling to see if the child processes are alive should work fine, since it's a low-overhead check and you don't need to check that often.\nThe first answer to this (similar) question has a Python code example: Multi-server monitor/auto restarter in python\n",
"You can wrap your worker processes in try/except bl... | [
2,
1,
1
] | [] | [] | [
"exception",
"multiprocessing",
"python"
] | stackoverflow_0004833458_exception_multiprocessing_python.txt |
Q:
Python: Parsing a colon delimited file with various counts of fields
I'm trying to parse a a few files with the following format in 'clientname'.txt
hostname:comp1
time: Fri Jan 28 20:00:02 GMT 2011
ip:xxx.xxx.xx.xx
fs:good:45
memory:bad:78
swap:good:34
Mail:good
Each section is delimited by a : but where lines 0... | Python: Parsing a colon delimited file with various counts of fields | I'm trying to parse a a few files with the following format in 'clientname'.txt
hostname:comp1
time: Fri Jan 28 20:00:02 GMT 2011
ip:xxx.xxx.xx.xx
fs:good:45
memory:bad:78
swap:good:34
Mail:good
Each section is delimited by a : but where lines 0,2,6 have 2 fields... lines 1,3-5 have 3 or more fields. (A big issue I've... | [
"split method has the following syntax split( [sep [,maxsplit]]) and if the maxsplit is given, it will make maxsplit+1 parts. In you case, you just have give maxsplit as 1. Just split(':',1) would solve your problem.\n",
"If time is a special case, you could do:\n[...]\ns_line = line.rstrip()\nif line.startswit... | [
2,
1,
1,
0
] | [] | [] | [
"delimiter",
"file",
"parsing",
"python"
] | stackoverflow_0004833948_delimiter_file_parsing_python.txt |
Q:
Django: is the command line the only way to access the database API?
My Google-fu is failing me. I'm doing this tutorial and it wants me to define important-looking functions while using the command line shell. If this is the only way, I'll do it, but it seems inefficient (make one typo and you have to redefine th... | Django: is the command line the only way to access the database API? | My Google-fu is failing me. I'm doing this tutorial and it wants me to define important-looking functions while using the command line shell. If this is the only way, I'll do it, but it seems inefficient (make one typo and you have to redefine the whole thing). Also I thought that shell sessions were mostly for testing... | [
"Hmm, where are you getting this idea that the tutorial you linked to asks you to write functions in the shell?\nI just went through the tutorials again and the shell isn't even brought up in Tutorial 2, 3, and 4. It briefly appears in tutorial 1 but no functions are written.\nTutorial 3 goes through the process of... | [
3,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004831864_django_python.txt |
Q:
.net / python utility/library that will give a screenshot of a directory structure
does anyone know if there exists a library that will give a snapshot image of a directory structure ?
if not, is there an easy programming approach to creating this in c# or python?
A:
Like this?
import os, sys
for root, dirs, f... | .net / python utility/library that will give a screenshot of a directory structure | does anyone know if there exists a library that will give a snapshot image of a directory structure ?
if not, is there an easy programming approach to creating this in c# or python?
| [
"Like this?\nimport os, sys\n\nfor root, dirs, files in os.walk(sys.argv[1]):\n full_path = os.path.abspath(root)\n chunks = full_path.split(os.path.sep)\n depth = len(chunks) - 2\n indent = ' ' * depth\n print indent + full_path\n\n",
"I'm not sure what you mean by \"snapshot image\" of a directo... | [
1,
0
] | [] | [] | [
".net",
"c#",
"directory",
"python"
] | stackoverflow_0004834022_.net_c#_directory_python.txt |
Q:
Django: SyntaxError 'unexpected EOF' while saving a Form
I have a settings page which has two forms for handling the settings for two different Models. The Profile model form works. The Chef model form doesn't. The form fails gracefully, and isn't throwing a Django error page - so in using pdb, I found the form is... | Django: SyntaxError 'unexpected EOF' while saving a Form | I have a settings page which has two forms for handling the settings for two different Models. The Profile model form works. The Chef model form doesn't. The form fails gracefully, and isn't throwing a Django error page - so in using pdb, I found the form is not valid, and is throwing a Syntax Error.
I'm confused as to... | [
"EDIT: sorry I'm mistaken with my last reply. I was thinking of something else.\nreplace the %s with %d on this line:\nreturn HttpResponseRedirect('/users/%s' % request.user.id)\n\n",
"SyntaxError::SyntaxError comes from the Python parser itself. I don't think this has anything to do with your form data.\nI'd tr... | [
0,
0
] | [] | [] | [
"broken_pipe",
"django",
"django_forms",
"python",
"syntax_error"
] | stackoverflow_0004832741_broken_pipe_django_django_forms_python_syntax_error.txt |
Q:
Django ModelMultipleChoiceField : Iterating through the data
I am trying to display the data from a ModelMultipleChoiceField, and have tried to iterate for the objects, but I am getting funky results. Thanks for the help!
{{ chef.meal }}
Renders
[<Meal: Breakfast>, <Meal: Brunch>]
--
{% for i in chef.meal%} {{... | Django ModelMultipleChoiceField : Iterating through the data | I am trying to display the data from a ModelMultipleChoiceField, and have tried to iterate for the objects, but I am getting funky results. Thanks for the help!
{{ chef.meal }}
Renders
[<Meal: Breakfast>, <Meal: Brunch>]
--
{% for i in chef.meal%} {{i}} {% endfor %}
Renders
[ < M e a l : B r e a k f a s t > , < M ... | [
"You cannot use form fields inside a model. Instead make a foreign key from meal to Chef.\nclass Meal(models.Model):\n name = models.CharField(max_length=10)\n chef = models.ForeignKey(Chef)\n def __unicode__(self):\n return \"%s\" % self.name\n\nNow inside the template use\n{% for meal in chef.meal... | [
0
] | [] | [] | [
"django",
"django_forms",
"django_models",
"python"
] | stackoverflow_0004834391_django_django_forms_django_models_python.txt |
Q:
fpassthru in python?
I am trying to find a sample code for download a file in python. To be exact, I am trying to convert a php to python.
My php sameple code:
$http_request = "POST $path HTTP/1.0\r\n";
$http_request .= "Host: $host\r\n";
$http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
$ht... | fpassthru in python? | I am trying to find a sample code for download a file in python. To be exact, I am trying to convert a php to python.
My php sameple code:
$http_request = "POST $path HTTP/1.0\r\n";
$http_request .= "Host: $host\r\n";
$http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
$http_request .= "Content-Len... | [
"A translation of PHP's fpassthru to Python might be as simple as:\ndef fpassthru(fp):\n \"\"\" Reads to EOF on the given file object from the current position\n and writes the results to output. \"\"\"\n print fp.read()\n\nThe fp argument must be a \"file object\" returned by open (the standard method... | [
0
] | [] | [] | [
"download",
"php",
"python",
"urllib"
] | stackoverflow_0004112604_download_php_python_urllib.txt |
Q:
How come I'm getting this no import error in Django?
import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = "trade.settings"
from trade.turkey.models import *
d = DemoRecs.objects.all()
d.delete()
When I run this, it imports fine if I leave out the d.delete() line. It's erroring on that line. Why? If I co... | How come I'm getting this no import error in Django? | import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = "trade.settings"
from trade.turkey.models import *
d = DemoRecs.objects.all()
d.delete()
When I run this, it imports fine if I leave out the d.delete() line. It's erroring on that line. Why? If I comment that out, everything is cool. I can insert. I can u... | [
"The directory for the trade project is missing from sys.path.\n",
"Try adding \"trade\" to the pythonpath...\nimport os.path\n_pypath = os.path.realpath(os.path.dirname(__file__) + '/trade')\nsys.path.append(_pypath)\n\n"
] | [
4,
2
] | [] | [] | [
"database",
"django",
"mysql",
"python"
] | stackoverflow_0004834538_database_django_mysql_python.txt |
Q:
How do I run a bash script inside Python, but act as if it's running from another directory?
subprocess.call(["/home/blah/trunk/blah/run.sh", "/tmp/ad_xml", "/tmp/video_xml"])
I do this. However, inside my run.sh, I have "relative" paths.
So, I have to "cd" into that directory, and then run the shell script. How... | How do I run a bash script inside Python, but act as if it's running from another directory? | subprocess.call(["/home/blah/trunk/blah/run.sh", "/tmp/ad_xml", "/tmp/video_xml"])
I do this. However, inside my run.sh, I have "relative" paths.
So, I have to "cd" into that directory, and then run the shell script. How do I do that?
| [
"Use the cwd argument to subprocess.call()\nFrom the docs here: http://docs.python.org/library/subprocess.html\n\nIf cwd is not None, the child’s\n current directory will be changed to\n cwd before it is executed. Note that\n this directory is not considered when\n searching the executable, so you can’t\n spe... | [
12,
1,
1,
0
] | [] | [] | [
"bash",
"linux",
"python",
"shell",
"unix"
] | stackoverflow_0004834807_bash_linux_python_shell_unix.txt |
Q:
how to parse text
i have a question that i want to read a file, search for any line that has session ID (e.i. 12345), if matched then print all lines after that until encounter newline.
after that, how can i associate all these lines to the session ID if i need to further parse these lines.
And i want to do it in ... | how to parse text | i have a question that i want to read a file, search for any line that has session ID (e.i. 12345), if matched then print all lines after that until encounter newline.
after that, how can i associate all these lines to the session ID if i need to further parse these lines.
And i want to do it in Python.
Thanks
| [
"this answers the first part of your question:\nwith open('myfile.txt') as f:\n for line in f:\n if '12456' in line:\n print line\n\nI didn't understand what else you were asking for. can you translate : \"how can i associate all these lines to the session ID if i need to further parse these l... | [
3,
2
] | [] | [] | [
"file",
"python",
"string"
] | stackoverflow_0004834717_file_python_string.txt |
Q:
Including two things it will check for in one if statement in python
lets say I have a program that runs like this in python
x=raw_input("Please enter name: ")
if x=="David" and "Jonathon"
print "Whatever"
how do I get two things such as Jonathon and David so it excepts both of these scenarios and for both exe... | Including two things it will check for in one if statement in python | lets say I have a program that runs like this in python
x=raw_input("Please enter name: ")
if x=="David" and "Jonathon"
print "Whatever"
how do I get two things such as Jonathon and David so it excepts both of these scenarios and for both executes print "Whatever". I know that ["David" and "Jonathon"] isn't the pro... | [
"You can do:\nx=raw_input(\"Please enter name: \")\n\nif x==\"David\" or x==\"Jonathon\":\n\n print \"Whatever\"\n\nOr you can do:\nnames=[\"Bob\",\"Joe\"]\nx=raw_input(\"What is your name?\\n\")\nif x in names:\n print \"Whatever\"\n\nIf you are dealing with large data.\n",
"names = [\"David\", \"Jonathon... | [
3,
2,
0
] | [] | [] | [
"if_statement",
"python",
"variables"
] | stackoverflow_0004835064_if_statement_python_variables.txt |
Q:
Custom dictionary through **kw
I have a library function that makes use of **kw, but I want to pass a dictionary-like class so that I can override __getitem__ to track its accesses to data in the dictionary. For example, in the code below calling libfn does not print Accessed but libfn2 does.
class Dtracker(dict)... | Custom dictionary through **kw | I have a library function that makes use of **kw, but I want to pass a dictionary-like class so that I can override __getitem__ to track its accesses to data in the dictionary. For example, in the code below calling libfn does not print Accessed but libfn2 does.
class Dtracker(dict):
def __init__(self):
dict.__i... | [
"You can't, without changing Python itself. It's converted to a dict at a lower level.\n",
"Do this\nclass Dtracker(dict):\n def __init__(self,*arg,**kw):\n super(Dtracker,self).__init__(*arg,**kw)\n def __getitem__(self,item):\n print \"Accessed %s\" % str(item)\n return dict.__getitem... | [
5,
2
] | [] | [] | [
"python"
] | stackoverflow_0004835050_python.txt |
Q:
first order differences along a given axis in NumPy array
#compute first differences of 1d array
from numpy import *
x = arange(10)
y = zeros(len(x))
for i in range(1,len(x)):
y[i] = x[i] - x[i-1]
print y
The above code works but there must be at least one easy, pythonesque way to do this without having to ... | first order differences along a given axis in NumPy array | #compute first differences of 1d array
from numpy import *
x = arange(10)
y = zeros(len(x))
for i in range(1,len(x)):
y[i] = x[i] - x[i-1]
print y
The above code works but there must be at least one easy, pythonesque way to do this without having to use a for loop. Any suggestions?
| [
"What about:\ndiff(x)\n# array([1, 1, 1, 1, 1, 1, 1, 1, 1])\n\n",
"Yes, this exactly the kind of loop numpy elementwise operations is designed for. You just need to learn to take the right slices of the arrays.\nx = numpy.arange(10)\ny = numpy.zeros(x.shape)\n\ny[1:] = x[1:] - x[:-1]\n\nprint y\n\n",
"several ... | [
10,
6,
5,
2,
1
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0004835075_arrays_numpy_python.txt |
Q:
Numpy.genfromtxt method works in windows but not Linux
I am doing some data crunching and I have built a program for Python in Windows and now I want to run it on my Linux box so it can crunch while I go home to drink beer, etc.
One piece of the code (an important one) ingests some columnar values from a CSV file ... | Numpy.genfromtxt method works in windows but not Linux | I am doing some data crunching and I have built a program for Python in Windows and now I want to run it on my Linux box so it can crunch while I go home to drink beer, etc.
One piece of the code (an important one) ingests some columnar values from a CSV file via Numpy's genfromtxt method. the snippet of code in quest... | [
"You said you're actually using version 1.3 on Linux. That one has an argument skiprows which is the same as skip_header. Considering numpy.genfromtxt isn't even in documentation for 1.3, I would guess it was just being tested in 1.3, and the final signature wasn't quite set. That being said, there is a workarou... | [
4
] | [] | [] | [
"csv",
"linux",
"numpy",
"python"
] | stackoverflow_0004799773_csv_linux_numpy_python.txt |
Q:
Making a list comprehension, beginner
I'm new to Python and am trying to understand list comprehensions so I can use it in my code.
pricelist = {"jacket":15, "pants":10, "cap":5, "baseball":3, "gum":1}
products_sold = []
while True:
product_name = input("what is the name of the product")
product = {}
... | Making a list comprehension, beginner | I'm new to Python and am trying to understand list comprehensions so I can use it in my code.
pricelist = {"jacket":15, "pants":10, "cap":5, "baseball":3, "gum":1}
products_sold = []
while True:
product_name = input("what is the name of the product")
product = {}
customer_name = input("what is the name of... | [
"I'll answer what I think your real problem which is that you want to understand list comprehensions. IMO, the example that you posted to try to learn list comprehensions is not a good example. Here's a very trivial example I like to use since it should be easy to relate this to what you already know from another... | [
2
] | [] | [] | [
"list",
"list_comprehension",
"python"
] | stackoverflow_0004830052_list_list_comprehension_python.txt |
Q:
check for valid arguments
So let's define a few functions:
def x(a, b, c): pass
def y(a, b=1, c=2): pass
def z(a=1, b=2, c=3): pass
Now, what's the best way to, given a pointer to x, y, or z (p), a tuple of args (a) and a dictionary of kwargs (k), check to see if
p(*a, **kw)
would produce any exception regardin... | check for valid arguments | So let's define a few functions:
def x(a, b, c): pass
def y(a, b=1, c=2): pass
def z(a=1, b=2, c=3): pass
Now, what's the best way to, given a pointer to x, y, or z (p), a tuple of args (a) and a dictionary of kwargs (k), check to see if
p(*a, **kw)
would produce any exception regarding having not enough arguments o... | [
"You can use the inspect module's getargspec function to determine the functions of the arguments and their defaults, if any, as well as if the function accepts varargs or keywordargs. This should be enough information to determine if a given tuple will satisfy the argument requirements.\nHere's a start (have to ru... | [
5,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0004835171_python.txt |
Q:
Solving functional equations programmatically
Given:
F(F(n)) = n
F(F(n + 2) + 2) = n
F(0) = 1
where n is a non-negative integer. F(129) = ?
How can we solve such kind of functional equations programmatically? My programming language of choice is Python.
A:
Functional equations, in their most general terms, are r... | Solving functional equations programmatically | Given:
F(F(n)) = n
F(F(n + 2) + 2) = n
F(0) = 1
where n is a non-negative integer. F(129) = ?
How can we solve such kind of functional equations programmatically? My programming language of choice is Python.
| [
"Functional equations, in their most general terms, are really really hard. It is no coincidence that pretty much every international mathematics competition features one of them, usually looking about as innocent as the one you've written. The methods of solving them vary from plain induction to infinite-dimension... | [
6,
2
] | [] | [] | [
"function",
"math",
"python"
] | stackoverflow_0004835484_function_math_python.txt |
Q:
python's `with` statement target is unexpectedly None
seems like I do not understand something with---the python with statement.
Consider this class:
class test(object):
def __enter__(self): pass
def __exit__(self, *ignored): pass
now, when using it with with, like in
with test() as michael:
print rep... | python's `with` statement target is unexpectedly None | seems like I do not understand something with---the python with statement.
Consider this class:
class test(object):
def __enter__(self): pass
def __exit__(self, *ignored): pass
now, when using it with with, like in
with test() as michael:
print repr(michael)
I would expect some output like <test instance ... | [
"From the with documentation:\n\nIf a target was included in the with statement, the return value from __enter__() is assigned to it.\n\nIf you def __enter__(self): return self, then your expected output is produced.\n",
"From the docs:\n\nobject.__enter__(self)\nEnter the runtime context related to this object. ... | [
19,
2
] | [
"I get the same thing for repr(michael)\nTry this instead:\nm.__repr__()\n\nI'm not entirely sure, but I think it has something to do with the fact that you haven't defined the repr method in your test class\n"
] | [
-1
] | [
"as_keyword",
"contextmanager",
"python",
"with_statement"
] | stackoverflow_0004835611_as_keyword_contextmanager_python_with_statement.txt |
Q:
Override file operations in Python
Is there a way to override all file operations in Python? File operations such as 'open', 'os.rename' and 'os.unlink'.
I want to create a temporary, in-memory file system without rewriting a library. Does anyone know of a script or a library that has this feature? I want to run a... | Override file operations in Python | Is there a way to override all file operations in Python? File operations such as 'open', 'os.rename' and 'os.unlink'.
I want to create a temporary, in-memory file system without rewriting a library. Does anyone know of a script or a library that has this feature? I want to run a library on Google App Engine and it is ... | [
"If you just need file objects which do not have real files behind them, have a look at the StringIO module.\n",
"\"Override\"? That word doesn't really make any sense in that context. You can replace them in various ways, depending on what you want really.\nMaking a in memory file system can be done on most OS's... | [
2,
1,
0,
0
] | [] | [] | [
"filesystems",
"python"
] | stackoverflow_0004835603_filesystems_python.txt |
Q:
What's the most Pythonic way to refactor this list building code?
I have a list of results that I need to pull out various other lists from. For example, all owners that are male, all cars between 5 and 10 years old.
def get_male_owners(self):
results = []
for result in self.results:
if result.owne... | What's the most Pythonic way to refactor this list building code? | I have a list of results that I need to pull out various other lists from. For example, all owners that are male, all cars between 5 and 10 years old.
def get_male_owners(self):
results = []
for result in self.results:
if result.owner.sex.male:
results.append(result)
return results
def ... | [
"Use list comprehensions:\ndef get_male_owners(self):\n return [res for res in self.results if res.owner.sex.male]\n\ndef get_cards_5_to_10(self):\n return [res for res in self.results if res.car and self.is_5_to_10(res.car)]\n\ndef is_5_to_10(self, car):\n return 5 <= car.age <= 10\n\nIf you just need som... | [
3,
1
] | [] | [] | [
"dry",
"python"
] | stackoverflow_0004836055_dry_python.txt |
Q:
Python: urllib/urllib2/httplib confusion
I'm trying to test the functionality of a web app by scripting a login sequence in Python, but I'm having some troubles.
Here's what I need to do:
Do a POST with a few parameters and headers.
Follow a redirect
Retrieve the HTML body.
Now, I'm relatively new to python, but... | Python: urllib/urllib2/httplib confusion | I'm trying to test the functionality of a web app by scripting a login sequence in Python, but I'm having some troubles.
Here's what I need to do:
Do a POST with a few parameters and headers.
Follow a redirect
Retrieve the HTML body.
Now, I'm relatively new to python, but the two things I've tested so far haven't wor... | [
"Focus on urllib2 for this, it works quite well. Don't mess with httplib, it's not the top-level API.\nWhat you're noting is that urllib2 doesn't follow the redirect.\nYou need to fold in an instance of HTTPRedirectHandler that will catch and follow the redirects.\nFurther, you may want to subclass the default HTT... | [
31,
15,
13,
11,
8,
6,
0,
0
] | [] | [] | [
"http",
"python",
"urllib2"
] | stackoverflow_0000301924_http_python_urllib2.txt |
Q:
Python: How can I implement this in a DRY way using Jinja2?
I have lots of code like this in my template:
<h2>Owners of old cars</h2>
<table id="hor-minimalist-b" summary="Old Cars">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Age</th>
<th scope="col... | Python: How can I implement this in a DRY way using Jinja2? | I have lots of code like this in my template:
<h2>Owners of old cars</h2>
<table id="hor-minimalist-b" summary="Old Cars">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Age</th>
<th scope="col">Address</th>
</tr>
</thead>
<tbody>
{% for ... | [
"Surely what you want, ideally, is:\n{% for car in cars %}\n<h2>Owners of {{ car.manufacturer }}</h2>\n<table id=\"hor-minimalist-b\" summary=\"Old Cars\">\n<thead>\n <tr>\n <th scope=\"col\">Name</th>\n <th scope=\"col\">Age</th>\n <th scope=\"col\">Address</th>\n </tr>\n</thead>\n<tbody... | [
3,
0
] | [] | [] | [
"dry",
"jinja2",
"python"
] | stackoverflow_0004836265_dry_jinja2_python.txt |
Q:
Do I need to add a db_index to this Django model?
class Comments(models.Model):
content = models.ForeignKey(Content)
Do I need to add a db_index to "content"? Or would that automatically be indexed because it's a foreign key?
A:
Unless specified otherwise, an index will be created for a ForeignKey. Relevan... | Do I need to add a db_index to this Django model? | class Comments(models.Model):
content = models.ForeignKey(Content)
Do I need to add a db_index to "content"? Or would that automatically be indexed because it's a foreign key?
| [
"Unless specified otherwise, an index will be created for a ForeignKey. Relevant source code:\nclass ForeignKey(RelatedField, Field):\n # snip\n def __init__(self, to, to_field=None, rel_class=ManyToOneRel, **kwargs):\n # snip\n if 'db_index' not in kwargs:\n kwargs['db_index'] = Tru... | [
44
] | [] | [] | [
"database",
"django",
"indexing",
"mysql",
"python"
] | stackoverflow_0004836327_database_django_indexing_mysql_python.txt |
Q:
Incrementing sub-sets of matrices in Python
I want to increment a small subsection (variable) of an matrix [illustrative code below] - but running over them by loops seems sloppy and inelegant -- and I suspect is the slowest way to do this calc.
One of the ideas I had was to create another array of ones, of the d... | Incrementing sub-sets of matrices in Python | I want to increment a small subsection (variable) of an matrix [illustrative code below] - but running over them by loops seems sloppy and inelegant -- and I suspect is the slowest way to do this calc.
One of the ideas I had was to create another array of ones, of the dimensions that i want to increment (2x3 in exampl... | [
"You can do the same simply by:\n a[3:5,4:7] += 1\n\n",
"You can use also logical arrays for accessing individual elements of your subset. Especially handy when your subset has irregular shape.\nAlso they perform very well. For example\nIn []: M= randn(2000, 2000)\nIn []: timeit M[M< 0]+= 10\n1 loops, best of 3: ... | [
7,
1
] | [] | [] | [
"matrix",
"numpy",
"python"
] | stackoverflow_0004836048_matrix_numpy_python.txt |
Q:
In Python, what's the best way to log exceptions to a file?
Suppose I catch an exception, and I want to log it. How do I do that? Where do I specify where to log that to?
A:
virhilo tmp $ cat l.py
import logging
logging.basicConfig(filename='exceptions.log', level=logging.DEBUG)
try:
1/0
except ZeroDivis... | In Python, what's the best way to log exceptions to a file? | Suppose I catch an exception, and I want to log it. How do I do that? Where do I specify where to log that to?
| [
"virhilo tmp $ cat l.py \nimport logging\n\nlogging.basicConfig(filename='exceptions.log', level=logging.DEBUG)\n\ntry:\n 1/0\nexcept ZeroDivisionError as e:\n logging.debug(e)\nvirhilo tmp $ python2 l.py \nvirhilo tmp $ cat exceptions.log \nDEBUG:root:integer division or modulo by zero\nvirhilo tmp $ \n\nins... | [
4,
0
] | [] | [] | [
"django",
"exception",
"logging",
"python"
] | stackoverflow_0004836394_django_exception_logging_python.txt |
Q:
Parsing Information from redirect URL
I am working with the Hunch API and am trying to allow the user to OAuth with my system. I am directing them to
http://hunch.com/authorize/v1/?app_id=12345&next=http://hoosheer.appspot.com/get-recs
from this it allows the user to enter their details and redirects them to my... | Parsing Information from redirect URL | I am working with the Hunch API and am trying to allow the user to OAuth with my system. I am directing them to
http://hunch.com/authorize/v1/?app_id=12345&next=http://hoosheer.appspot.com/get-recs
from this it allows the user to enter their details and redirects them to my webpage. Once they are redirected to my pa... | [
"You need to grab the parsed querystring parameters out of the request object. You can do that with get() like this:\nauth_token_key = request.get('auth_token_key')\n\nYou can read up on this at the docs.\n",
">>> import urlparse\n>>> url = 'http://hoosheer.appspot.com/get-recs?auth_token_key=12345abc&user_id=hn_... | [
1,
0
] | [] | [] | [
"google_app_engine",
"oauth",
"python"
] | stackoverflow_0004836868_google_app_engine_oauth_python.txt |
Q:
Extract path and file name from tag
I have source code of some web page, I need to find all occurrences of tag and to extract name and location of that picture (example <img src="../images/test.jpg" /> I need
path="../images/" and file="test.jpg"). How can I do that with regular expressions ?
A:
you should us... | Extract path and file name from tag | I have source code of some web page, I need to find all occurrences of tag and to extract name and location of that picture (example <img src="../images/test.jpg" /> I need
path="../images/" and file="test.jpg"). How can I do that with regular expressions ?
| [
"you should use lxml.html\n>>> from urllib2 import urlopen\n>>> from lxml import html\n>>> page = urlopen('http://www.amazon.co.uk/')\n>>> page_source = html.parse(page)\n>>> from pprint import pprint\n>>> pprint(page_source.xpath('//img/@src'))\n['http://g-ecx.images-amazon.com/images/G/02/gno/images/orangeBlue/na... | [
4,
3,
0
] | [] | [] | [
"html",
"html_parsing",
"python"
] | stackoverflow_0004836947_html_html_parsing_python.txt |
Q:
Some basic clarifications about Python?
Last night I came across the term called Jython which was kind of new to me so I started reading about it only to add more to my confusion about Python in general. I have never really used Python either. So here is what I am confused about.
Python is implemented in C - Does... | Some basic clarifications about Python? | Last night I came across the term called Jython which was kind of new to me so I started reading about it only to add more to my confusion about Python in general. I have never really used Python either. So here is what I am confused about.
Python is implemented in C - Does that mean that the interpreter was written i... | [
"\"Python\" is the name of the language itself, not of a particular interpreter implementation, just as \"C\" is the name of a programming language and not of a particular compiler.\n\"CPython\" is an implementation of an interpreter of the Python language written in C. It compiles Python source code to byte code ... | [
11,
7,
3,
1
] | [] | [] | [
"jython",
"python"
] | stackoverflow_0004837218_jython_python.txt |
Q:
pythonrc.py is not loading in interactive mode
I've added a .pythonrc.py script to my home directory with the commands below:
import os
import sys
print 'Welcome'
I've confirmed that it is actually executable by running python .pythonrc.py and by loading the python interpreter and running execfile('.pythonrc.py')... | pythonrc.py is not loading in interactive mode | I've added a .pythonrc.py script to my home directory with the commands below:
import os
import sys
print 'Welcome'
I've confirmed that it is actually executable by running python .pythonrc.py and by loading the python interpreter and running execfile('.pythonrc.py'). However, when I start interactive mode, it seems ... | [
"You should set the Environment variable PYTHONSTARTUP to point to the start up script that you created.\nIn Ubuntu you can edit the ~/.bashrc file and add this line in the end: \nexport PYTHONSTARTUP=~/.pythonrc.py\n\nNow you should start a new shell and run python.\nHope it helps :)\n"
] | [
19
] | [] | [] | [
"python",
"shell",
"ubuntu"
] | stackoverflow_0004837237_python_shell_ubuntu.txt |
Q:
Why is else clause needed for try statement in python?
In Python the try statement supports an else clause, which executes if the code in try block does not raise an exception. For example:
try:
f = open('foo', 'r')
except IOError as e:
error_log.write('Unable to open foo : %s\n' % e)
else:
data = f.read()
... | Why is else clause needed for try statement in python? | In Python the try statement supports an else clause, which executes if the code in try block does not raise an exception. For example:
try:
f = open('foo', 'r')
except IOError as e:
error_log.write('Unable to open foo : %s\n' % e)
else:
data = f.read()
f.close()
Why is the else clause needed? Can't we write th... | [
"The difference is what happens if you get an error in the f.read() or f.close() code. In this case:\ntry:\n f = open('foo', 'r')\n data = f.read()\n f.close()\nexcept IOError as e:\n error_log.write('Unable to open foo : %s\\n' % e)\n\nAn error in f.read() or f.close() in this case would give you the log messa... | [
14,
3,
3,
0
] | [] | [] | [
"exception_handling",
"python"
] | stackoverflow_0004836139_exception_handling_python.txt |
Q:
Simple way to delete users account?
Is there a simple way or code to delete the account from a user? I want to delete the username, email address, first_name, last_name and the profile-data.
I do have two apps
Thanks!
A:
Are you looking to delete the user database record? If so, search for it then call delete:
... | Simple way to delete users account? | Is there a simple way or code to delete the account from a user? I want to delete the username, email address, first_name, last_name and the profile-data.
I do have two apps
Thanks!
| [
"Are you looking to delete the user database record? If so, search for it then call delete:\nuser = User.objects.get(username='their_username')\nuser.delete()\n\n",
"Can You Explain What kind of application you Use? If you use some kind of database with your application then simply run delete query with some spe... | [
4,
0
] | [] | [] | [
"django",
"python",
"web"
] | stackoverflow_0004837591_django_python_web.txt |
Q:
Passing Python list to C++ vector using Boost.python
How do I pass a Python list of my object type ClassName to a C++ function that accepts a vector<ClassName>?
The best I found is something like this: example. Unfortunately, the code crashes and I can't seem to figure out why. Here's what I used:
template<typ... | Passing Python list to C++ vector using Boost.python | How do I pass a Python list of my object type ClassName to a C++ function that accepts a vector<ClassName>?
The best I found is something like this: example. Unfortunately, the code crashes and I can't seem to figure out why. Here's what I used:
template<typename T>
void python_to_vector(boost::python::object o, ve... | [
"Assuming you have function that takes a std::vector<Foo> \nvoid bar (std::vector<Foo> arg)\n\nThe easiest way to handle this is to expose the vector to python.\nBOOST_PYTHON_MODULE(awesome_module)\n{\n class_<Foo>(\"Foo\")\n //methods and attrs here\n ;\n\n class_<std::vector<Foo> >(\"VectorOfFoo\"... | [
14,
3
] | [] | [] | [
"boost_python",
"python",
"vector"
] | stackoverflow_0004819707_boost_python_python_vector.txt |
Q:
How to slow down iteration of generator object fetching data from web service?
I'm using the Freebase-Python module to iterate through hundreds of results. Using:
results = freebase.mqlreaditer(query, extended=True)
I get a Python generator that I can iterate through like so:
for r in results:
#do stuff, like... | How to slow down iteration of generator object fetching data from web service? | I'm using the Freebase-Python module to iterate through hundreds of results. Using:
results = freebase.mqlreaditer(query, extended=True)
I get a Python generator that I can iterate through like so:
for r in results:
#do stuff, like create new object and save to datastore
mqlreaditer() fetches JSON results 100 at ... | [
"A generator is just a function that appears to look like a sequence but which retrieves the items one at a time for you instead of having the whole list of data up-front, which often requires a lot more memory. It's a \"just-in-time\" iterable, if you like. But, you have no guarantees as to how much data it is rea... | [
1
] | [] | [] | [
"freebase",
"generator",
"google_app_engine",
"python"
] | stackoverflow_0004837881_freebase_generator_google_app_engine_python.txt |
Q:
Cant compile uwsgi under centos (fc10) with python2.6
it`s normally build with python 2.5 BUT i need 2.6!
2.6 normally installed in /opt/python26 and successfully run as python2.6 in console.
but
python2.6 uwsgiconfig.py --build
give me
*** uWSGI linking ***
/usr/bin/ld: cannot find -lpython2.6
collect2: ld retu... | Cant compile uwsgi under centos (fc10) with python2.6 | it`s normally build with python 2.5 BUT i need 2.6!
2.6 normally installed in /opt/python26 and successfully run as python2.6 in console.
but
python2.6 uwsgiconfig.py --build
give me
*** uWSGI linking ***
/usr/bin/ld: cannot find -lpython2.6
collect2: ld returned 1 exit status
HELP!
| [
"Try:\nLD_LIBRARY_PATH=\"/somepath/\" python2.6 uwsgiconfig.py --build\n\nwhere somepath is the path to your libpython2.6.so.x file.\nRespectively update your /etc/ld.so.conf file and add the path to the libraries and run ldconfig.\n",
"Edit uwsgiconfig.py and set PYLIB_PATH to the path of the python lib director... | [
1,
0
] | [] | [] | [
"compilation",
"python",
"uwsgi",
"wsgi"
] | stackoverflow_0002590870_compilation_python_uwsgi_wsgi.txt |
Q:
Numpy.eig and the percentage of variance in PCA
Picking up from where we left...
So I can use linalg.eig or linalg.svd to compute the PCA. Each one returns different Principal Components/Eigenvectors and Eigenvalues when they're fed the same data (I'm currently using the Iris dataset).
Looking here or any other tu... | Numpy.eig and the percentage of variance in PCA | Picking up from where we left...
So I can use linalg.eig or linalg.svd to compute the PCA. Each one returns different Principal Components/Eigenvectors and Eigenvalues when they're fed the same data (I'm currently using the Iris dataset).
Looking here or any other tutorial with the PCA applied to the Iris dataset, I'll... | [
"Taking Doug's answer to your previous question and implementing the following two functions, I get the output shown below:\ndef pca_eig(orig_data):\n data = array(orig_data)\n data = (data - data.mean(axis=0)) / data.std(axis=0)\n C = corrcoef(data, rowvar=0)\n w, v = linalg.eig(C)\n print \"Using n... | [
4,
0,
0,
0
] | [] | [] | [
"math",
"numpy",
"pca",
"python"
] | stackoverflow_0004823223_math_numpy_pca_python.txt |
Q:
How can I delay execution until after os.system finishes?
I am using os.system to copy a file from a system to another. The logic of a very simple program is to execute another set of commands after this file gets copied.
The problem is that os.system does not actually wait for the file to be copied, and gets to ... | How can I delay execution until after os.system finishes? | I am using os.system to copy a file from a system to another. The logic of a very simple program is to execute another set of commands after this file gets copied.
The problem is that os.system does not actually wait for the file to be copied, and gets to executing the next line. This causes issues to the system. I co... | [
"The first thing I'd try is to use shutil.copyfile() instead of an external program to copy the file. If you have to use an external program, you should call it via subprocess.Popen(), not via os.system(). You can use the Popen.wait() to wait for the subprocess to finish.\n",
"I think you should rather use shut... | [
6,
1,
1
] | [] | [] | [
"file",
"os.system",
"python"
] | stackoverflow_0004837127_file_os.system_python.txt |
Q:
How to pass values from Python to flex
I am calling Python script from flex using HTTP service. How can I send back some values from python to flex app?
Thanks
A:
Using HTTPService, many people will send back XML. Sometimes they'll send back plain text. In your result handler, you should get the text returned f... | How to pass values from Python to flex | I am calling Python script from flex using HTTP service. How can I send back some values from python to flex app?
Thanks
| [
"Using HTTPService, many people will send back XML. Sometimes they'll send back plain text. In your result handler, you should get the text returned from the service call as event.result. \nYour result handler may look something like this, if you were to return XML:\npublic function onHTTPServiceResult(event:Resu... | [
0,
0,
0
] | [] | [] | [
"apache_flex",
"python",
"python_3.x"
] | stackoverflow_0004838113_apache_flex_python_python_3.x.txt |
Q:
Assigning to an instance's __class__ attribute in Python
Under what circumstances is it possible, and when is it impossible, to assign to an instance's __class__ attribute in Python?
Error messages such as TypeError: __class__ assignment: only for heap types don't really do it for me.
A:
You can only assign to t... | Assigning to an instance's __class__ attribute in Python | Under what circumstances is it possible, and when is it impossible, to assign to an instance's __class__ attribute in Python?
Error messages such as TypeError: __class__ assignment: only for heap types don't really do it for me.
| [
"You can only assign to the __class__ attribute of an instance of a user-defined class (i.e. defined using the class keyword), and the new value must also be a user-defined class. Whether the classes are new-style or old-style does not matter. (You can't mix them, though. You can't turn an old-style class instance... | [
17
] | [] | [] | [
"metaprogramming",
"python"
] | stackoverflow_0004838145_metaprogramming_python.txt |
Q:
How to represent a ListProperty(str) property with string formatting?
I have a ListProperty(str):
class Item(db.Model):
tags = db.ListProperty(str)
Sometimes I need to edit the tags already written to datastore, so I created an edit page:
class EditItem(webapp.RequestHandler):
def get(self):
self.... | How to represent a ListProperty(str) property with string formatting? | I have a ListProperty(str):
class Item(db.Model):
tags = db.ListProperty(str)
Sometimes I need to edit the tags already written to datastore, so I created an edit page:
class EditItem(webapp.RequestHandler):
def get(self):
self.response.out.write("""<div>
<form name="submit_form" action="/editi... | [
"tag_list = [u'formal', u'flag', u'photo']\nprint \", \".join(tag_list)\n>> formal, flag, photo\n\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"python",
"string_formatting"
] | stackoverflow_0004837733_google_app_engine_python_string_formatting.txt |
Q:
Why does calling kernel32.GetModuleHandleA() for msvcr100 fail in Python?
I am having a problem with calling GetModuleHandleA() using Python. I have a module that attaches as debugger to the process. I'm working on a function that would return address of the function in the specific DLL module. GetModuleHandleA("... | Why does calling kernel32.GetModuleHandleA() for msvcr100 fail in Python? | I am having a problem with calling GetModuleHandleA() using Python. I have a module that attaches as debugger to the process. I'm working on a function that would return address of the function in the specific DLL module. GetModuleHandleA("msvcr100") fails all of the time.
from ctypes import *
kernel32 = windll.kerne... | [
"You've found the solution to your problem, but I'm answering anyway to explain why your original effort failed (and why your fix worked).\nFirst, msvcrt/msvcr100 are two different versions of Microsoft's C runtime library. There are other versions as well, and all of them contain their own definitions for printf()... | [
5,
1,
0,
0
] | [] | [] | [
"python",
"winapi"
] | stackoverflow_0004834762_python_winapi.txt |
Q:
How to make Python knows the path to look for .py files?
Just started trying to learn Python and Django today. Following their documentations I was able to install Python and Django and got them up and running. I'm running Apache 2.2 on on Windows 7 by the way.
I got to the part in the official tutorial that tells... | How to make Python knows the path to look for .py files? | Just started trying to learn Python and Django today. Following their documentations I was able to install Python and Django and got them up and running. I'm running Apache 2.2 on on Windows 7 by the way.
I got to the part in the official tutorial that tells me to cd to the directory I want for my project and run this ... | [
"If you want to just be able to type django-admin.py, two things need to be set up:\n\nThe directory containing it needs to be in your PATH.\nYou need to make sure that the .py extension is associated with the Python interpreter. This is normally done during the installation of Python.\n\nHow to set the PATH on Wi... | [
5,
0
] | [] | [] | [
"cmd",
"django",
"python"
] | stackoverflow_0004838645_cmd_django_python.txt |
Q:
Runtime variable creation Python 3.1.2
How would i go about making a function to create a certain number of uniquely named variables at runtime, based on initial user input? For instance, user enters dimensions 400 x 400, (x and y), so i would want the function to create 1600 (400 * 400) variables, each to represe... | Runtime variable creation Python 3.1.2 | How would i go about making a function to create a certain number of uniquely named variables at runtime, based on initial user input? For instance, user enters dimensions 400 x 400, (x and y), so i would want the function to create 1600 (400 * 400) variables, each to represent every different point on a grid 400 by 40... | [
"What you really want is an array, a list or a tuple of 400*400 points.\nSo create a class that stores the information you want at each point, and then create a list of size 400*400 of those class objects.\nYou can do it this way:\nwidth = 400\nheight = 400\nm = [[0]*width for i in range(height)]\n\nAnd then access... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0004833901_python.txt |
Q:
Google App Engine: How to use the task queue for this processing?
I'm using the Python GAE SDK.
I have some processing that needs to be done on 6000+ instances of MyKind. It is too slow to be done in a single request, so I'm using the task queue. If I make a single task process only one entity, then it should tak... | Google App Engine: How to use the task queue for this processing? | I'm using the Python GAE SDK.
I have some processing that needs to be done on 6000+ instances of MyKind. It is too slow to be done in a single request, so I'm using the task queue. If I make a single task process only one entity, then it should take only a few seconds.
The documentation says that only 100 tasks can be... | [
"When you run code like taskqueue.add(url='/worker', params={'cursor': cursor}) you are enqueueing a task; scheduling a request to execute out of band using the parameters you provide. You can apparently schedule up to 100 of these in one operation.\nI don't think you want to, though. Task chaining would make this ... | [
9,
0
] | [] | [] | [
"google_app_engine",
"python",
"task_queue"
] | stackoverflow_0003225470_google_app_engine_python_task_queue.txt |
Q:
Python webbrowser.open() fails on Debian
When i run webbrowser.open() method, as in
python -c "import webbrowser; webbrowser.open_new_tab('http://www.google.it')"
The command open me a tab in the correct browser (chromium) but load a local copy of the file, in this case file:///var/tmp/kdecache-norby/krun/6225.0... | Python webbrowser.open() fails on Debian | When i run webbrowser.open() method, as in
python -c "import webbrowser; webbrowser.open_new_tab('http://www.google.it')"
The command open me a tab in the correct browser (chromium) but load a local copy of the file, in this case file:///var/tmp/kdecache-norby/krun/6225.0. that contains html but obviusly doesn't work... | [
"The problem is about kfmclient used by webbrowser module in KDE context. It wrongly openes remote files as local, as explained in http://portland.freedesktop.org/wiki/TaskOpenURL\n"
] | [
1
] | [] | [] | [
"browser",
"debian",
"python"
] | stackoverflow_0004838502_browser_debian_python.txt |
Q:
Does mod_pywebsocket have a non-blocking version of receive_message?
request.ws_stream.receive_message() blocks. Is there an equivalent that doesn't? Can it be used with select?
A:
It looks like the MessageReceiver class may provide asynchronous receiving and sending:
http://code.google.com/p/pywebsocket/source... | Does mod_pywebsocket have a non-blocking version of receive_message? | request.ws_stream.receive_message() blocks. Is there an equivalent that doesn't? Can it be used with select?
| [
"It looks like the MessageReceiver class may provide asynchronous receiving and sending: \nhttp://code.google.com/p/pywebsocket/source/browse/trunk/src/mod_pywebsocket/msgutil.py\n"
] | [
2
] | [] | [] | [
"html",
"mod_pywebsocket",
"python",
"websocket"
] | stackoverflow_0004832909_html_mod_pywebsocket_python_websocket.txt |
Q:
STDIN or file as mapper input in Hadoop environment?
As we need to read in bunch of files to mapper, in non-Hadoop
environment, I use os.walk(dir) and file=open(path, mode) to read in
each file.
However, in Hadoop environment, as I read that HadoopStreaming convert
file input to stdin of mapper and conver stdo... | STDIN or file as mapper input in Hadoop environment? | As we need to read in bunch of files to mapper, in non-Hadoop
environment, I use os.walk(dir) and file=open(path, mode) to read in
each file.
However, in Hadoop environment, as I read that HadoopStreaming convert
file input to stdin of mapper and conver stdout of reducer to file
output, I have a few questions abou... | [
"Hadoop streaming has to take input from STDIN. I think the confusion you're having is you're trying to write code to do some of the things that Hadoop Streaming is doing for you. I did that when I first started Hadooping. \nHadoop streaming can read in multiple files and even multiple zipped files which it then pa... | [
1
] | [] | [] | [
"hadoop",
"mapreduce",
"python"
] | stackoverflow_0004838074_hadoop_mapreduce_python.txt |
Q:
Python: PyQt Popup Window
So I've been creating my GUI with Qt for my Python application. I've now come to a situation where after a button has been pushed the appropriate deferred gets executed, we perform some tasks then I need to open up a separate window that contains one or two things. But I can't seem to fig... | Python: PyQt Popup Window | So I've been creating my GUI with Qt for my Python application. I've now come to a situation where after a button has been pushed the appropriate deferred gets executed, we perform some tasks then I need to open up a separate window that contains one or two things. But I can't seem to figure out how to create this new ... | [
"A common error that can drive you crazy is forgetting to store the handle of the popup window you create in some python variable that will remain alive (e.g. in a data member of the main window).\nThe following is a simple program that creates a main window with a button where pressing the button opens a popup\n#!... | [
54,
4
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0004838890_pyqt_python.txt |
Q:
Looking for a C# or Java or Python or C++ example to control Windows Remote Desktop
We have a hard policy that all computers must lock after 15 minutes of inactivity.
FOR GUI testing using CodedUI library, it is important that the connection is on, and that the screen is not locked. So, to circumvent the checks, I... | Looking for a C# or Java or Python or C++ example to control Windows Remote Desktop | We have a hard policy that all computers must lock after 15 minutes of inactivity.
FOR GUI testing using CodedUI library, it is important that the connection is on, and that the screen is not locked. So, to circumvent the checks, I was thinking of writing a script in Python, etc. which would make the connection alive b... | [
"Does it have to be remote? Whatever your solution you need some sort of service/daemon running on the target machine. Since you need that anyway, why not create a small app that simply emulates user interaction locally by moving a window or just sends a click to the desktop?\nHere's an MSDN article that describes ... | [
1
] | [] | [] | [
"api",
"c#",
"python",
"remote_desktop",
"windows"
] | stackoverflow_0004839234_api_c#_python_remote_desktop_windows.txt |
Q:
Generating py objects via python
I was wondering if there was a rendering library that would take a dictionary object and render a file into py-object syntax. Similar to the django_extensions command dump_script. I've looked around for an hour but have got no success as of yet. I know it wouldn't take me long to c... | Generating py objects via python | I was wondering if there was a rendering library that would take a dictionary object and render a file into py-object syntax. Similar to the django_extensions command dump_script. I've looked around for an hour but have got no success as of yet. I know it wouldn't take me long to create, but I want to see if there is a... | [
"You want to generate code from objects? This is possible for some built-in types so if you restrict yourself to them it works, and it's done with the repr() function.\n>>> dictionary = {'foo': 3, u'bar': [6.7]}\n>>> str = repr(dictionary)\n>>> str\n\"{'foo': 3, u'bar': [6.7000000000000002]}\"\n>>> exec(\"adict = \... | [
3
] | [] | [] | [
"dynamic_data",
"object",
"python"
] | stackoverflow_0004839258_dynamic_data_object_python.txt |
Q:
Why can't I have a varargs constructor and another constructor with fixed arguments?
Here is what I have so far:
class Die (object):
def __init__(self,sides):
self.sides = sides
def roll(self):
return random.randint(1,self.sides)
def __add__(self,other):
return Dice(self,othe... | Why can't I have a varargs constructor and another constructor with fixed arguments? | Here is what I have so far:
class Die (object):
def __init__(self,sides):
self.sides = sides
def roll(self):
return random.randint(1,self.sides)
def __add__(self,other):
return Dice(self,other)
def __unicode__(self):
return "1d%d" % (self.sides)
def __str__(self)... | [
"As you observed in your question, the varargs constructor is being invoked. This is because the second definition of Dice.__init__ is overriding, not overloading, the first.\nPython doesn't support method overloading, so you have at least two choices at hand.\n\nDefine only the varargs constructor. Inspect the len... | [
4,
1
] | [] | [] | [
"constructor",
"python"
] | stackoverflow_0004839200_constructor_python.txt |
Q:
Why is Pydev in Eclipse claiming errors on a working program?
Possible Duplicate:
Eclipse PyDev now shows all references to Tkinter as errors
I have the very simple test project:
from Tkinter import *
win = Tk()
l = Label(win, text="Hello, TKInter")
l.pack()
win.mainloop()
It runs fine, but in Eclipse, I get ... | Why is Pydev in Eclipse claiming errors on a working program? |
Possible Duplicate:
Eclipse PyDev now shows all references to Tkinter as errors
I have the very simple test project:
from Tkinter import *
win = Tk()
l = Label(win, text="Hello, TKInter")
l.pack()
win.mainloop()
It runs fine, but in Eclipse, I get the following two errors:
Undefined variable: Label line 3
Undefin... | [
"Because you import *. Eclipse hence don't know that Tk and Label is imported. Use from Tkinter import Tk, Label instead.\n"
] | [
1
] | [] | [] | [
"eclipse",
"pydev",
"python",
"tkinter"
] | stackoverflow_0004839308_eclipse_pydev_python_tkinter.txt |
Q:
How can I send/receive IM Messages using python?
How can I send/receive IM Messages using python? I want to send AOL Instant Messenger messages and receive them using python. I basically want to take in input from the chat, process it and then send the processed input back.
A:
Here is some sample code: http://co... | How can I send/receive IM Messages using python? | How can I send/receive IM Messages using python? I want to send AOL Instant Messenger messages and receive them using python. I basically want to take in input from the chat, process it and then send the processed input back.
| [
"Here is some sample code: http://code.google.com/p/madcow/source/browse/trunk/madcow/protocol/aim.py\nAlso:\nhttp://www.gilesgoatboy.org/python/skippy.html\nGenerally, lots of examples can be found using a google search for: python aim\n"
] | [
1
] | [] | [] | [
"instant_messaging",
"python"
] | stackoverflow_0004839341_instant_messaging_python.txt |
Q:
How to access HttpRequest from urls.py in Django
Basically I want to use a generic view that lists objects based on a username. Now, the question is, how do I do something like:
(r'^resources/$',
ListView.as_view(
queryset=Resources.objects.filter(user=request.user.username),
...
)
)
I couldn't find a... | How to access HttpRequest from urls.py in Django | Basically I want to use a generic view that lists objects based on a username. Now, the question is, how do I do something like:
(r'^resources/$',
ListView.as_view(
queryset=Resources.objects.filter(user=request.user.username),
...
)
)
I couldn't find a way to access the HttpRequest (request) object though... | [
"You could try subclassing the generic view:\nclass PublisherListView(ListView):\n def get_queryset(self):\n return Resources.objects.filter(user=self.request.user.username)\n\nThen your urls entry would look like:\n(r'^resources/$',\n PublisherListView.as_view(\n ...\n )\n)\n\nMore information on dy... | [
4,
3
] | [] | [] | [
"django",
"django_urls",
"python"
] | stackoverflow_0004838480_django_django_urls_python.txt |
Q:
How to use Google Acounts API in App Engine?
I have a Python based webapp, in wich one, I would like to use Google Accounts to let the users log in. it is simple, let's say my app is on:
http://myapp.appspot.com/
What I want to do is to "greet" the users with the Google Accounts Auth Screen when they navigate to... | How to use Google Acounts API in App Engine? | I have a Python based webapp, in wich one, I would like to use Google Accounts to let the users log in. it is simple, let's say my app is on:
http://myapp.appspot.com/
What I want to do is to "greet" the users with the Google Accounts Auth Screen when they navigate to the app, and only after logged in, let them see t... | [
"The app.yaml solution should work. But you also asked how to do it in python. Either will work. Both is unnecessary. Here it is:\nfrom google.appengine.api import users\n\nclass Premium(webapp.RequestHandler):\n def get(self):\n user = users.get_current_user()\n if not user:\n this.redirect(users.c... | [
1
] | [] | [] | [
"authentication",
"google_app_engine",
"python"
] | stackoverflow_0004788606_authentication_google_app_engine_python.txt |
Q:
Get a reference to Quality Center API Interface ISupportCopyPaste using QuickTest Pro
Quality Center OTA API provides interfaces like ISupportCopyPaste (copy/paste data using clipboard). The documented way to get a reference to an implemented interface is:
'Declare a variable to hold the reference for the interfac... | Get a reference to Quality Center API Interface ISupportCopyPaste using QuickTest Pro | Quality Center OTA API provides interfaces like ISupportCopyPaste (copy/paste data using clipboard). The documented way to get a reference to an implemented interface is:
'Declare a variable to hold the reference for the interface
Dim bf As IBaseFactory2
' By assigning the implementing object reference to the
' IBas... | [
"The reason QTP \"doesn't allow As in Dim statement\" is that QTP scripts are based on VBScript not VB, and As is VB only (VBScript is dynamically typed). \nIf you want to use OTA in QTP you can try using the QCUtil object that QTP exposes (see QTP's help for more information).\nIf QCUtil doesn't give you the objec... | [
2,
0
] | [] | [] | [
"api",
"hp_quality_center",
"python",
"qtp",
"vbscript"
] | stackoverflow_0004756342_api_hp_quality_center_python_qtp_vbscript.txt |
Q:
Last.fm api invalid method
I am trying to write a python script to do a query to Last.fm, but I keep getting an invalid method error returned.
I don't want links to pre-written last.fm python libraries, I am trying to do this as a "test what I know" kind of project. Thanks in advance!
import urllib
import httplib
... | Last.fm api invalid method | I am trying to write a python script to do a query to Last.fm, but I keep getting an invalid method error returned.
I don't want links to pre-written last.fm python libraries, I am trying to do this as a "test what I know" kind of project. Thanks in advance!
import urllib
import httplib
params = urllib.urlencode({'met... | [
"You lack Content-type for your request: \"application/x-www-form-urlencoded\". This works:\nimport urllib\nimport httplib\n\nparams = urllib.urlencode({'method' : 'artist.getsimilar',\n 'artist' : 'band',\n 'limit' : '5',\n 'api_key' : '#API key goes here'})\n\nheader = {\... | [
2,
0
] | [] | [] | [
"api",
"last.fm",
"python"
] | stackoverflow_0004362900_api_last.fm_python.txt |
Q:
update a currently displayed variable
I am writing some Python code, which will in the end will display something which looks like:
Volt1: 3.1V
Volt2: 2.6V
Volt3: 5.6V
I am constantly monitoring some register values which will give me the current values of Volt1,Volt2,Volt3. As I read in the new values ... | update a currently displayed variable | I am writing some Python code, which will in the end will display something which looks like:
Volt1: 3.1V
Volt2: 2.6V
Volt3: 5.6V
I am constantly monitoring some register values which will give me the current values of Volt1,Volt2,Volt3. As I read in the new values I want to update the field next to the vari... | [
"This kind of thing is best handled using a library such as curses.\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0004839605_python.txt |
Q:
string.replace('the','') is leaving white space
I have a string that is the name of an artist that I get from the MP3 ID3 tag
sArtist = "The Beatles"
What I want is to change it to
sArtist = "Beatles, the"
I have running into 2 different problems. My first problem is that I seem to be trading 'The' for ''.
if ... | string.replace('the','') is leaving white space | I have a string that is the name of an artist that I get from the MP3 ID3 tag
sArtist = "The Beatles"
What I want is to change it to
sArtist = "Beatles, the"
I have running into 2 different problems. My first problem is that I seem to be trading 'The' for ''.
if sArtist.lower().find('the') == 0:
sArtist = sArti... | [
"Using \nsArtist.replace('The','')\n\nis dangerous. What happens if the artist's name is Theodore?\nPerhaps use regex instead:\nIn [11]: import re\nIn [13]: re.sub(r'^(?i)(a|an|the) (.*)',r'\\2, \\1','The Beatles')\nOut[13]: 'Beatles, The'\n\n",
"One way:\n>>> def reformat(artist,beg):\n... if artist.startswith... | [
8,
2
] | [] | [] | [
"id3",
"mp3",
"python",
"string"
] | stackoverflow_0004839806_id3_mp3_python_string.txt |
Q:
Using a file watch to refresh a log viewer using PyQt4
I've implemented a very simple log viewer in Python using PyQt4.
I am interested in using it to follow the execution of a program, so the list view has to be refreshed when a new line is appended to the log file.
Here is my implementation (without the watch):
... | Using a file watch to refresh a log viewer using PyQt4 | I've implemented a very simple log viewer in Python using PyQt4.
I am interested in using it to follow the execution of a program, so the list view has to be refreshed when a new line is appended to the log file.
Here is my implementation (without the watch):
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui impor... | [
"I am quite new to python and pyqt, but this \"works\" here:\nimport sys\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\n\nclass LogEntryModel(QAbstractListModel):\n def __init__(self, logfile, parent=None):\n super(LogEntryModel, self).__init__(parent)\n self.slurp(logfile)\n self.l... | [
0
] | [] | [] | [
"pyqt4",
"python",
"qabstractlistmodel",
"qlistview"
] | stackoverflow_0004785588_pyqt4_python_qabstractlistmodel_qlistview.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.