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:
In Django Admin, how do you have cascaded InlineModelAdmin
Hi I have a list of restaurants (e.g. McDonalds, etc), with menus (e.g Lunch Menu, Dinner Menu), submenus (e.g. Appetizers, Sandwidches, etc.) and dishes (Angus Burger, Chicken Burger, etc.)
They are all linked by foreign keys.
Is there a way, so that in t... | In Django Admin, how do you have cascaded InlineModelAdmin | Hi I have a list of restaurants (e.g. McDonalds, etc), with menus (e.g Lunch Menu, Dinner Menu), submenus (e.g. Appetizers, Sandwidches, etc.) and dishes (Angus Burger, Chicken Burger, etc.)
They are all linked by foreign keys.
Is there a way, so that in the Restaurant admin, I have Menu as a tabular inline, with a lin... | [
"If you just want to append some links like in the Restaurant change view, you don't really need to use an inline as this provides a form for changing data. I would probably override change_view in RestaurantAdmin to get a list of the related menus and pass it as an extra_context. And then override the model specif... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005819205_django_python.txt |
Q:
MySQL -- Joins Between Databases On Different Servers Using Python?
In MySQL, I have two different databases -- let's call them A and B.
Database A resides on server server1, while database B resides on server server2.
Both servers {A, B} are physically close to each other, but are on different machines and have d... | MySQL -- Joins Between Databases On Different Servers Using Python? | In MySQL, I have two different databases -- let's call them A and B.
Database A resides on server server1, while database B resides on server server2.
Both servers {A, B} are physically close to each other, but are on different machines and have different connection parameters (different username, different password et... | [
"Try to use FEDERATED Storage Engine.\nWorkaround: it is possible to use another DBMS to retrieve data between two databases, for example you could do it using linked servers in MS SQL Server (see sp_addlinkedserver stored procedure). From the documentation:\n\nA linked server allows for access to distributed, hete... | [
22,
4,
3
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0005832787_mysql_python.txt |
Q:
why do i keep getting a IndexError: list index out of range error
if i use 0 instead of x ( in the while loop) the program works and i get the 1st photo from someone's favorite list from flickr but if i want more than or other than the 1st photo i get this error
import flickrlib
import webbrowser
FLICKR_API_KEY = ... | why do i keep getting a IndexError: list index out of range error | if i use 0 instead of x ( in the while loop) the program works and i get the 1st photo from someone's favorite list from flickr but if i want more than or other than the 1st photo i get this error
import flickrlib
import webbrowser
FLICKR_API_KEY = "f86203e922041a6a999fd4a59f19b1e6"
FLICKR_API_SSECRET = "b286bcaddafb0... | [
"I don't know Flickr's API, but it looks like you're only asking for 1 photo in getPublicList. Either way, you're not checking to make sure that total is less than the number of pictures returned from getPublicList.\n",
"Because you use per_page=1 here:\nphotos = client.flickr.favorites.getPublicList(user_id= use... | [
5,
3
] | [] | [] | [
"python",
"python_2.7"
] | stackoverflow_0005832963_python_python_2.7.txt |
Q:
Why does my image not appear?
Hi I wonder why my image doesn't appear. I think it is stored both as a blobproperty and in the blobstore since it appears like a thumbnail on the list page. The address to the page where the image doesn't appear is http://www.koolbusiness.com/servead/4125209
And the thumbnail from th... | Why does my image not appear? | Hi I wonder why my image doesn't appear. I think it is stored both as a blobproperty and in the blobstore since it appears like a thumbnail on the list page. The address to the page where the image doesn't appear is http://www.koolbusiness.com/servead/4125209
And the thumbnail from the same image appears in the list ht... | [
"I would guess that one of these two if statements is evaluating to false:\n if image:\n if image.primary_image:\n url = images.get_serving_url(str(image.primary_image.key()))\n\nIf you were actually calling get_serving_url, you would either get a valid serving URL or an exception. Instead, url... | [
4
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0005833246_google_app_engine_python.txt |
Q:
Is there a pure Python library for parsing a Windows Registry file?
Is there a pure Python (ie. fully cross-platform) library for parsing Windows Registry files (NTUSER.DAT)? Read-only access is acceptable.
If there is not, what resources exist that document the reverse-engineered structure of the Registry files?... | Is there a pure Python library for parsing a Windows Registry file? | Is there a pure Python (ie. fully cross-platform) library for parsing Windows Registry files (NTUSER.DAT)? Read-only access is acceptable.
If there is not, what resources exist that document the reverse-engineered structure of the Registry files?
Thanks!
Update
Since it seemed that a pure Python solution did not exist... | [
"winreg is obviously Windows only, and does not read registry hive files (NTUSER.DAT, etc.), but rather accesses the registry directly.\nWhat you're looking for is a library for parsing hive files, and it seems like this one might work:\nhttp://rwmj.wordpress.com/2010/11/28/use-hivex-from-python-to-read-and-write-w... | [
12,
2,
2,
2,
1
] | [] | [] | [
"python",
"registry"
] | stackoverflow_0005833441_python_registry.txt |
Q:
Problem with using socket to connect with PC
I'm trying to connect my phone with my notebook using WiFi. Both devices are connected to one network. Notebook has IP 192.168.1.35 so i tried to connect with that IP through smart phone (firewall is off). Here's the code:
package org.me.androidapp;
import android.app.... | Problem with using socket to connect with PC | I'm trying to connect my phone with my notebook using WiFi. Both devices are connected to one network. Notebook has IP 192.168.1.35 so i tried to connect with that IP through smart phone (firewall is off). Here's the code:
package org.me.androidapp;
import android.app.Activity;
import android.os.Bundle;
import android... | [
"your python code is binding to localhost which means it's not listening on the network but only on loopback thus you should change it to have it listen on the network address (i.e. 192.168.1.35) of the computer rather than on 127.0.0.1\n"
] | [
5
] | [] | [] | [
"android",
"java",
"python"
] | stackoverflow_0005833622_android_java_python.txt |
Q:
3D formats: obj and duplicate vertices
I am writing a python converter that takes in an .obj file and outputs it in another format. I've noticed that .obj files have a lot of duplicate vertices, and a lot of the faces refer to these duplicates.
So I wrote the script to only add a vertex once and ignore any duplica... | 3D formats: obj and duplicate vertices | I am writing a python converter that takes in an .obj file and outputs it in another format. I've noticed that .obj files have a lot of duplicate vertices, and a lot of the faces refer to these duplicates.
So I wrote the script to only add a vertex once and ignore any duplicates, and if any face references a duplicate ... | [
"You should use a set() instead of a dictionnary to store your unique vertices, you won't need anymore to use a dummy value for it.\nAbout duplicated vertices, it seems to be a \"bug\" of the model maker software or a \"bug\" of the software developper (have a look here)\n",
"Most likely it's because of how objec... | [
2,
2
] | [] | [] | [
"3d",
"python"
] | stackoverflow_0005833717_3d_python.txt |
Q:
Running a Python Script to read info. from a new .txt file being generated at a known location every 1 sec
My Scenario: I have a known location(directory/path) where a .txt file is going to be generated every 1 sec, I just need to copy its content (contents are in a format which can be used directly to put in a My... | Running a Python Script to read info. from a new .txt file being generated at a known location every 1 sec | My Scenario: I have a known location(directory/path) where a .txt file is going to be generated every 1 sec, I just need to copy its content (contents are in a format which can be used directly to put in a MySQL query) and put it in a MySQL query in my Python script. I need to keep doing this continuously, i.e.,non-sto... | [
"import MySQLdb\nimport os\nimport time\nfrom stat import ST_MTIME\n\nTIME_TO_SLEEP = 1 # to avoid CPU burning\n\nmydb = MySQLdb.connect(host=\"IP_add\", user=\"uname\", passwd=\"pass\", db=\"DB_name\")\ncursor = mydb.cursor()\nlast_date = 0\nwhile True: # or what you want as stop co... | [
4,
2
] | [] | [] | [
"mysql",
"python",
"scripting"
] | stackoverflow_0005833793_mysql_python_scripting.txt |
Q:
Remove whitespace from a regex search in a file
I'm attempting to remove all whitespace from a selected string search using regexp. The code works but it continues to return an error that I'm not sure how to resolve ...?
elif searchType =='2':
print " Directory to be searched: c:\Python27 "
directory ... | Remove whitespace from a regex search in a file | I'm attempting to remove all whitespace from a selected string search using regexp. The code works but it continues to return an error that I'm not sure how to resolve ...?
elif searchType =='2':
print " Directory to be searched: c:\Python27 "
directory = os.path.join("c:\\","SQA_log")
userstring = r... | [
"It appears that regex.search fails on line with whitespaces stripped, but succeeds when whitespaces are there. You haven't given regex's definition, so I can't tell you why that happens, but if you replace if regex.search(line) with if result: you shouldn't get that error.\nThe reason for the error is that re.sear... | [
2,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0005834180_python_regex.txt |
Q:
huffman algorithm in python
HI!
Could anybody say how to fix the problem in the Huffman algorthm (if put together all the parts) from this Internet site:
http://www.builderau.com.au/program/python/soa/Huffman-coding-in-Python/0,2000064084,339283616,00.htm
Error:
itemqueue = [Node(a, len(list(b))) for a, b in gr... | huffman algorithm in python | HI!
Could anybody say how to fix the problem in the Huffman algorthm (if put together all the parts) from this Internet site:
http://www.builderau.com.au/program/python/soa/Huffman-coding-in-Python/0,2000064084,339283616,00.htm
Error:
itemqueue = [Node(a, len(list(b))) for a, b in groupby(sorted(input))]
TypeError: ... | [
"I think you forgot to declare input.\nIt should work fine otherwise.\n"
] | [
4
] | [] | [] | [
"huffman_code",
"python"
] | stackoverflow_0005834054_huffman_code_python.txt |
Q:
Best way (threads/event-driven) of fetching data from many web pages
I don't want to make holywar on any reason, just to get advice and continue development.
I need to write something like crawler,
it must be able to fetch some data from list of URLs and parse it.
I am going to use Ruby (mechanize + nokogiri) or ... | Best way (threads/event-driven) of fetching data from many web pages | I don't want to make holywar on any reason, just to get advice and continue development.
I need to write something like crawler,
it must be able to fetch some data from list of URLs and parse it.
I am going to use Ruby (mechanize + nokogiri) or Python (mechanize + beautifulsoup).
But I need to do parallel data handlin... | [
"I've been using Scrapy with great success. It's quite straightforward and allows for multiple crawlers at once. Outputs to json, xml, etc or directly to a database. It's worth a look for sure.\n"
] | [
2
] | [] | [] | [
"events",
"multithreading",
"python",
"ruby",
"thread_safety"
] | stackoverflow_0005834698_events_multithreading_python_ruby_thread_safety.txt |
Q:
Repeatedly appending to a large list (Python 2.6.6)
I have a project where I am reading in ASCII values from a microcontroller through a serial port (looks like this : AA FF BA 11 43 CF etc)
The input is coming in quickly (38 two character sets / second).
I'm taking this input and appending it to a running list of... | Repeatedly appending to a large list (Python 2.6.6) | I have a project where I am reading in ASCII values from a microcontroller through a serial port (looks like this : AA FF BA 11 43 CF etc)
The input is coming in quickly (38 two character sets / second).
I'm taking this input and appending it to a running list of all measurements.
After about 5 hours, my list has grown... | [
"\nI'm given to understand that the larger a list becomes, the slower list operations become.\n\nThat's not true in general. Lists in Python are, despite the name, not linked lists but arrays. There are operations that are O(n) on arrays (copying and searching, for instance), but you don't seem to use any of these.... | [
44,
16,
2,
0,
0
] | [] | [] | [
"append",
"list",
"performance",
"python"
] | stackoverflow_0005833907_append_list_performance_python.txt |
Q:
How to check class equality in Python 2.5?
I've looked through Python 2.5 documentation and I couldn't find an answer to this: How do I check if an object is the same class as another object?
def IsClass(obj1, obj2):
return obj1.class == obj2.class #doesn't work
A:
You can use
type(obj1) is type(obj2)
Note... | How to check class equality in Python 2.5? | I've looked through Python 2.5 documentation and I couldn't find an answer to this: How do I check if an object is the same class as another object?
def IsClass(obj1, obj2):
return obj1.class == obj2.class #doesn't work
| [
"You can use\ntype(obj1) is type(obj2)\n\nNote that you usually try to avoid type checking in Python, but rather rely on duck typing.\n"
] | [
12
] | [
"I think what you want to do is use type(obj). :)\n-EDIT- Looks like he beat me to it. And he's right about the Duck Typing. \n"
] | [
-1
] | [
"class",
"equality",
"python",
"python_2.5"
] | stackoverflow_0005834829_class_equality_python_python_2.5.txt |
Q:
Cron job calling bash script and python scripts
Okay so I have a bash script that simply downloads a web page, and then I use python to pulls some data out of the downloaded page.
So my bash script is along the lines of
#!/bin/bash
html_file="web_page.html"
wget -O /home/michael/Documents/CS288/homework7/web_page... | Cron job calling bash script and python scripts | Okay so I have a bash script that simply downloads a web page, and then I use python to pulls some data out of the downloaded page.
So my bash script is along the lines of
#!/bin/bash
html_file="web_page.html"
wget -O /home/michael/Documents/CS288/homework7/web_page.html http://markets.usatoday.com/custom/usatoday-com... | [
"try to replace the cron line with : \n* * * * * michael /home/michael/Documents/CS288/homework7/usatoday_runner.sh > /tmp/why_is_this_failing.log 2>&1\n\nthe answer may be in the /tmp/why_is_this_failing.log\n",
"It's possible that your script doesn't have some environment variables set. When a cron job runs it... | [
2,
1,
1
] | [] | [] | [
"bash",
"crontab",
"linux",
"python"
] | stackoverflow_0005834739_bash_crontab_linux_python.txt |
Q:
How can I customize python unitest.py --help?
I know this is possible, I'm a newbie on Python. Looked at nose. But nose is not what we require. There should be some way to customize when I run python unittest.py --help on my own. Can any python people throw some light on this on how or where we can change. I'm usi... | How can I customize python unitest.py --help? | I know this is possible, I'm a newbie on Python. Looked at nose. But nose is not what we require. There should be some way to customize when I run python unittest.py --help on my own. Can any python people throw some light on this on how or where we can change. I'm using python 2.6.6
| [
"Alright, you're looking at customizing unittest.TestProgram. You'll want to create something like myunittest.py and in that module you'll do something like:\n# myunittest.py\nfrom unittest import TestProgram\n\nclass MyTestProgram(TestProgram):\n USAGE = \"\"\"\\\nUsage: %(progName)s [options] [test] [...]\n\n... | [
1
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0005786942_python_unit_testing.txt |
Q:
translating a ruby script to python
my problem is the following
i have a ruby script looking like this
module parent
module son_1
... some code here
end
module son_2
... some code here
end
class one
... some code here
end
class two
... some code here
... | translating a ruby script to python | my problem is the following
i have a ruby script looking like this
module parent
module son_1
... some code here
end
module son_2
... some code here
end
class one
... some code here
end
class two
... some code here
end
end
and i need this script to b... | [
"It should look like this on the file system :\n- parent/\n ------- __init__.py << empty file or can have classes if you need, that way python will treat parent as a package\n ------- son_1.py\n ------- son_2.py\n- test.py\n\nthen in actual code in test.py :\nfrom parent import son_1, son_2, one, two\nc = one('s... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0005835245_python.txt |
Q:
Python matrix, any solution?
MY input(just for example):
from numpy import *
x=[['1' '7']
['1.5' '8']
['2' '5.5']
['2' '9']]
I want to make next thing on random matrix:
1. for each row calculate:
> for example first row: [1;7]*[1,7] = [[1, 7]; #value * value.transpose
... | Python matrix, any solution? | MY input(just for example):
from numpy import *
x=[['1' '7']
['1.5' '8']
['2' '5.5']
['2' '9']]
I want to make next thing on random matrix:
1. for each row calculate:
> for example first row: [1;7]*[1,7] = [[1, 7]; #value * value.transpose
[7, 49]]
> for examp... | [
"How about the following:\nIn [1]: import numpy as np\n\nIn [2]: x=np.array([[1, 7],[1.5, 8],[2, 5.5],[2, 9]])\n\nIn [3]: np.sum(np.outer(row,row) for row in x)\nOut[3]: \narray([[ 11.25, 48. ],\n [ 48. , 224.25]])\n\n",
"First, you should create the matrix containing floating point numbers instead o... | [
0,
0
] | [] | [] | [
"matrix",
"numpy",
"python",
"sum"
] | stackoverflow_0005835583_matrix_numpy_python_sum.txt |
Q:
Boost.Python + OpenGL segmentation faults
I have a (almost) perfectly working C++ code written with Boost.Python. It wraps a shared pointer based structure hierarchy of 3 or 4 classes, nothing terribly complex (i.e. class A has a std::vector of class B instance pointers, etc.), top level package called, say, foo.
... | Boost.Python + OpenGL segmentation faults | I have a (almost) perfectly working C++ code written with Boost.Python. It wraps a shared pointer based structure hierarchy of 3 or 4 classes, nothing terribly complex (i.e. class A has a std::vector of class B instance pointers, etc.), top level package called, say, foo.
Some time ago I decided to add visualization to... | [
"If your OS is linux, you might be running into this bug: https://bugs.launchpad.net/ubuntu/+source/mesa/+bug/259219.\nIf calling\nexport LD_PRELOAD=<path-to-libstdc++>\nbefore starting your program fixes it, this is it. You need to replace with the actual path on your machine. Something like /usr/lib/gcc/i686-pc-... | [
2
] | [] | [] | [
"boost",
"memory",
"opengl",
"python",
"segmentation_fault"
] | stackoverflow_0001751408_boost_memory_opengl_python_segmentation_fault.txt |
Q:
Integrating python webapp with some jar files
Hi I have few jar files which are few calculations compiled into jar files. I have a python web app which is supposed to interact with these jar files and get me the data. I have heard that it can be done using the java bridge. Can someone let me know how this could be... | Integrating python webapp with some jar files | Hi I have few jar files which are few calculations compiled into jar files. I have a python web app which is supposed to interact with these jar files and get me the data. I have heard that it can be done using the java bridge. Can someone let me know how this could be done or at least point me to the right link.
| [
"I think what you are looking for is jython.You can interact back and forth between python and java using jython.\n",
"You could always run the jar files in a subprocess and use PIPE for IO (or temp files). This works pretty well for us (we are generating PDF from our Django app with flying saucer and iText)\n"
] | [
1,
0
] | [] | [] | [
"java",
"python"
] | stackoverflow_0005830706_java_python.txt |
Q:
Performance comparison: insert vs build Python set operations
In python, is it faster to
a) Build a set from a list of n items
b) Insert n items into a set?
I found this page (http://wiki.python.org/moin/TimeComplexity) but it did not have enough information to conclude which was faster.
It seems, inserting ite... | Performance comparison: insert vs build Python set operations | In python, is it faster to
a) Build a set from a list of n items
b) Insert n items into a set?
I found this page (http://wiki.python.org/moin/TimeComplexity) but it did not have enough information to conclude which was faster.
It seems, inserting items one at a time could in the worst case take O(n*n) time (given it ... | [
"In terms of O() complexity - it's definitely the same, because both approaches do exactly the same - insert n items into a set.\nThe difference comes from implementation: One clear advantage of initialization from an iterable is that you save a lot of Python-level function calls - the initialization from a iterabl... | [
22,
2,
0,
0
] | [] | [] | [
"python",
"set",
"time_complexity"
] | stackoverflow_0005835657_python_set_time_complexity.txt |
Q:
Python extension for Upskirt: garbage at end of string
I've been trying to make a Python extension for Upskirt. I though it would not be too hard for a first C project since there are examples (example program in the Upskirt code and the Ruby extension).
The extension works, it converts the Markdown I throw at it,... | Python extension for Upskirt: garbage at end of string | I've been trying to make a Python extension for Upskirt. I though it would not be too hard for a first C project since there are examples (example program in the Upskirt code and the Ruby extension).
The extension works, it converts the Markdown I throw at it, but sometimes the output has some garbage at the end of the... | [
"You are doing a strdup in pantyshot_render:\noutput_text = strdup(ob->data); /* ob is a \"struct buf *\" */\n\nBut I don't think ob->data is a nul-terminated C string. You'll find this inside upskirt/buffer.c:\n/* bufnullterm • NUL-termination of the string array (making a C-string) */\nvoid\nbufnullterm(struct bu... | [
3
] | [] | [] | [
"c",
"python",
"python_extensions"
] | stackoverflow_0005835302_c_python_python_extensions.txt |
Q:
How to use Google Users API with Google App Engine and Android
Server is on Google App Engine, and the client is an Android mobile app. I want to use the Users API to log users in from Android via a REST API on GAE.
In the Users API documentation it looks like the key (to construct a User object on the server) is... | How to use Google Users API with Google App Engine and Android | Server is on Google App Engine, and the client is an Android mobile app. I want to use the Users API to log users in from Android via a REST API on GAE.
In the Users API documentation it looks like the key (to construct a User object on the server) is the email. But I'm told there's a way to get the User Object via a... | [
"From the OAuth API docs:\nfrom google.appengine.api import oauth\n\nuser = oauth.get_current_user()\n\nWith a valid OAuth request, this will return a db.User object just like users.get_current_user().\nOAuth endpoint URLs for your app are detailed on the same page.\n"
] | [
3
] | [] | [] | [
"android",
"google_app_engine",
"oauth",
"python"
] | stackoverflow_0005835651_android_google_app_engine_oauth_python.txt |
Q:
What does "self.default = default if default else type()" mean?
I have always been a .NET guy since I started working (~6 years). Recently, I am working on a project using Django, which requires me to learn Python in parallel. A lot of times I bumped into Python code that looked simple but I just couldn't understa... | What does "self.default = default if default else type()" mean? | I have always been a .NET guy since I started working (~6 years). Recently, I am working on a project using Django, which requires me to learn Python in parallel. A lot of times I bumped into Python code that looked simple but I just couldn't understand. And here is one of them.
class TypedProperty(object):
def __i... | [
"a if b else c is a conditional expression that evaluates to a if b evaluates to True, and to c otherwise. In the given context, this checks if default is \"trucy\", in which case it is stored in self.default. Otherwise, a new instance of type is created and stroed in self.default.\nNote that this implementation ... | [
6,
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0005835784_python.txt |
Q:
remove all values from multiple lists at same index position with some logic
I'm a beginner in programming and also a beginner in Python. Below are the details for a better understanding of my issue.
Rooms = ['BlueRoom', 'RedRoom', 'GreenRoom', 'BlueRoom']
Availability = [5, 7, 3, 5]
Description = ['Blue', 'Red', ... | remove all values from multiple lists at same index position with some logic | I'm a beginner in programming and also a beginner in Python. Below are the details for a better understanding of my issue.
Rooms = ['BlueRoom', 'RedRoom', 'GreenRoom', 'BlueRoom']
Availability = [5, 7, 3, 5]
Description = ['Blue', 'Red', 'Green', 'Blue']
Price = [120, 90, 150, 115]
What I need to have is, the same lis... | [
"Rooms = ['BlueRoom', 'RedRoom', 'GreenRoom', 'BlueRoom']\nAvailability = [5, 7, 3, 5]\nDescription = ['Blue', 'Red', 'Green', 'Blue']\nPrice = [120, 90, 150, 115]\n\nhighest_price = max(Price)\nx = Price.index(highest_price)\nlist = [Rooms,Availability,Description,Price]\n\nfor item in list:\n del item[x]\n\npr... | [
1,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005835609_python.txt |
Q:
Feeling stupid while trying to implement lazy partitioning in Python
I am trying to implement lazy partitioning of an iterator object that yields slices of the iterator when a function on an element of the iterator changes values. This would mimick the behavior of Clojure's partition-by (although the semantics of ... | Feeling stupid while trying to implement lazy partitioning in Python | I am trying to implement lazy partitioning of an iterator object that yields slices of the iterator when a function on an element of the iterator changes values. This would mimick the behavior of Clojure's partition-by (although the semantics of the output would be different, since Python would genuinely "consume" the ... | [
"Why not reuse groupby? I think it is O(1).\ndef partitionby(f, iterable):\n return (g[1] for g in groupby(iterable, f))\n\nThe difference of groupby's implementation with yours is that the partition is a specialized iterator object, instead of a chain of chain of chain ...\n",
"it was bugging me that partitio... | [
3,
0
] | [] | [] | [
"iterator",
"lazy_evaluation",
"python"
] | stackoverflow_0005835685_iterator_lazy_evaluation_python.txt |
Q:
Yet another QuerySet custom ordering problem
Lots of searching, found nothing so far.
In my django app, Model_X is rated by my users using a very standard ratings model. I have a standalone function that processes a LOT of data and when given a user instance, returns a list of tuples. The first value corresponds... | Yet another QuerySet custom ordering problem | Lots of searching, found nothing so far.
In my django app, Model_X is rated by my users using a very standard ratings model. I have a standalone function that processes a LOT of data and when given a user instance, returns a list of tuples. The first value corresponds to the primary key for an instance of Model_X, an... | [
"If your list of rating tuples is already ordered you might be able to use something from Ordering by the order of values in a SQL IN() clause. \nIf you're using MySQL then the field() function should work for you. Pull all the ids from your sorted rating tuples, [x[0] for x in sorted_tuples] and then use that li... | [
1,
0
] | [] | [] | [
"django",
"django_queryset",
"python"
] | stackoverflow_0005827665_django_django_queryset_python.txt |
Q:
Install and configure Rpy2 on opensuse
I'm try to install R module for python(rpy) on opensuse, however after execute command "sudo easy_install rpy2, I get this error msgs:
"Setup script exited with Error: Tried to guess R's HOME but no R command in the PATH."
Someone could help?
thanks
jayron
A:
If you use Ub... | Install and configure Rpy2 on opensuse | I'm try to install R module for python(rpy) on opensuse, however after execute command "sudo easy_install rpy2, I get this error msgs:
"Setup script exited with Error: Tried to guess R's HOME but no R command in the PATH."
Someone could help?
thanks
jayron
| [
"If you use Ubuntu's package management, it should pull in all the dependencies, including R:\nsudo apt-get install python-rpy2\n\n"
] | [
3
] | [] | [] | [
"opensuse",
"python",
"r",
"rpy2"
] | stackoverflow_0005835932_opensuse_python_r_rpy2.txt |
Q:
Pinax over google app engine
I am building web application using Django-nonrel over google app engine.I want to add social networking type of application to my web application. I come to know that Pinax is something that I can use. But is this supported over google app engine ? If no, what is the alternative appro... | Pinax over google app engine | I am building web application using Django-nonrel over google app engine.I want to add social networking type of application to my web application. I come to know that Pinax is something that I can use. But is this supported over google app engine ? If no, what is the alternative approach I can take ?
Thank you,
Sunil ... | [
"It looks like Pinax will not run on App Engine out of the box due to underlying incompatibility with the datastore. There is a project to add support on Bitbucket. Related discussions here, here, and here.\n"
] | [
2
] | [] | [] | [
"django_nonrel",
"google_app_engine",
"python"
] | stackoverflow_0005835942_django_nonrel_google_app_engine_python.txt |
Q:
Send emails from the user that is logged in in my GAE application
Let's assume I have users registered in my GAE application with their Google accounts that they use to access GMail, Calendar, Contacts etc. They confirm that my app can send email messages from their GMail account and when they click some link, lik... | Send emails from the user that is logged in in my GAE application | Let's assume I have users registered in my GAE application with their Google accounts that they use to access GMail, Calendar, Contacts etc. They confirm that my app can send email messages from their GMail account and when they click some link, like "Send a notification to all my friends", the message goes where it's ... | [
"From the GAE Mail API docs:\n\nThe email address of the sender, the From address. The sender address must be one of the following types:\n\nThe address of a registered\n administrator for the application.\n You can add administrators to an\n application using the Administration\n Console.\nThe address of the u... | [
2
] | [] | [] | [
"gmail",
"google_app_engine",
"python"
] | stackoverflow_0005836036_gmail_google_app_engine_python.txt |
Q:
How to automatically escape special characters in python but not the alphabetical ones?
I'm writing with python, and I have a unicode containing special characters, such as double quotes and non english characters.
I want to automatically escape the special characters, but when I use re.escape it escapes all non e... | How to automatically escape special characters in python but not the alphabetical ones? | I'm writing with python, and I have a unicode containing special characters, such as double quotes and non english characters.
I want to automatically escape the special characters, but when I use re.escape it escapes all non english characters as well. I'm not sure that's supposed to happen.
Anyway this is problematic... | [
"Ended up using this:\njson.dumps(myString, ensure_ascii=False)\nWorks pretty well so far. The added parameter leaves it in unicode.\n(but it adds additional quotes before and after parts that have unicode alphabetical characters, so I used myString = myString[1:-1]. That's a little ugly, maybe there is a better so... | [
2,
0,
0
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0005835891_javascript_python.txt |
Q:
Avoiding the use of type() comparisons where polymorphism won't work
I came across the following in How to Think Like a Computer Scientist (here):
def recursive_sum(nested_num_list):
sum = 0
for element in nested_num_list:
if type(element) == type([]):
sum = sum + recursive_sum(element... | Avoiding the use of type() comparisons where polymorphism won't work | I came across the following in How to Think Like a Computer Scientist (here):
def recursive_sum(nested_num_list):
sum = 0
for element in nested_num_list:
if type(element) == type([]):
sum = sum + recursive_sum(element)
else:
sum = sum + element
return sum
I was shoc... | [
"You can check if an element is a sequence by using isinstance(element, collections.Sequence).\n",
"\"sum\" functions takes an iterable, so I would check the element implements the __iter__ method or not,using \"hasattr\" builtin function.\nLike this:\ndef recursive_sum(nested_num_list):\n sum = 0\n for ele... | [
3,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"python",
"types"
] | stackoverflow_0005836177_python_types.txt |
Q:
How do I access form fields in a template in Django?
I am using a model-based form to create a form based off a data model. The insert part works fine, but I am now trying to do the "edit" page. my problem is I need the ID/primary key of the original model for the post action and documentation (and a previous thre... | How do I access form fields in a template in Django? | I am using a model-based form to create a form based off a data model. The insert part works fine, but I am now trying to do the "edit" page. my problem is I need the ID/primary key of the original model for the post action and documentation (and a previous thread here) seems to have told me to try both form.id and for... | [
"The Athlete instance will be stored on the ModelForm, so you can do:\n{{ form.instance.id }}\n\nAlso, you want to pass your Athlete instance in the POST case you you'll actually update the instance (rather than create a new one).\n",
"If you are staying on the same page during the edit process(for example http:/... | [
3,
2,
0
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0005835975_django_django_forms_python.txt |
Q:
How do I 'fake' a form POST request on the commandline in ssh with python?
I have a small question about a problem I encountered writing my first python web application.
I have a form on my site which action is a python file. The forms posts the values of 2 inputboxes in a post request and my pythonfile will catc... | How do I 'fake' a form POST request on the commandline in ssh with python? | I have a small question about a problem I encountered writing my first python web application.
I have a form on my site which action is a python file. The forms posts the values of 2 inputboxes in a post request and my pythonfile will catch those and do something with them. When testing my program I'd like to be able ... | [
"You can use httplib2 to POST requests to a server. For file uploading (multipart requests) you should use Poster.\nYou might need to GET the form before you can POST it your server checks for security tokens (hidden fields or cookies)\n"
] | [
1
] | [] | [] | [
"command_line_arguments",
"python",
"ssh"
] | stackoverflow_0005835983_command_line_arguments_python_ssh.txt |
Q:
amfast installation error on Ubuntu
I tried to install amfast on Ubuntu 10.10 but when i run the setup.py i get the following after the installation runs for a little time, how do i fix this?
Processing dependencies for AmFast==0.5.1
Searching for uuid
Reading http://pypi.python.org/simple/uuid/
Download error: [E... | amfast installation error on Ubuntu | I tried to install amfast on Ubuntu 10.10 but when i run the setup.py i get the following after the installation runs for a little time, how do i fix this?
Processing dependencies for AmFast==0.5.1
Searching for uuid
Reading http://pypi.python.org/simple/uuid/
Download error: [Errno 101] Network is unreachable -- Some ... | [
"Hm.. it looks like there was some kind of remote server problem. \nHave you tried to open http://pypi.python.org/simple/uuid/ in a browser? \n(P.S. the installation works fine for me on Ubuntu 10.10)\n"
] | [
0
] | [] | [] | [
"amf",
"python"
] | stackoverflow_0005836026_amf_python.txt |
Q:
Python, last element cut
Well problem was that my original input is:
x=[['1', '7', 'gg'], ['1.5', '8', 'as']...]
I need just cut last element in every row.
I try to cut last element in matrix with that:
hl=x[:,:-1]
BUT THIS IS NOT WORKING, so I try in this way:
kl=array(x)
hl=x[:,:-1]
Now I get:
[['1' '7']
['... | Python, last element cut | Well problem was that my original input is:
x=[['1', '7', 'gg'], ['1.5', '8', 'as']...]
I need just cut last element in every row.
I try to cut last element in matrix with that:
hl=x[:,:-1]
BUT THIS IS NOT WORKING, so I try in this way:
kl=array(x)
hl=x[:,:-1]
Now I get:
[['1' '7']
['1.5' '8']]
Instead of:
[['1' ... | [
">>> x=[['1', '7', 'gg'], ['1.5', '8', 'as']]\n>>> [s[:-1] for s in x]\n[['1', '7'], ['1.5', '8']]\n\n",
"Try this:\nfor row in x:\n del row[-1]\n\n",
"Try:\nh1 = [el[:-1] for el in x]\nprint h1\n\nOutput:\n\n[['1', '7'], ['1.5', '8']]\n\n",
"x = [['1', '7', 'gg'], ['1.5', '8', 'as']]\n\nfor y in x:\n y... | [
9,
5,
2,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0005836572_python.txt |
Q:
Python os.rename if file system is full
I'm asking this beacause there's no way to try it myself (if there's one share it please (:).
I'm doing some file handling with Python os library, specifically file moving/renaming with os.rename().
Python docs explains some of the exceptions this function might raise here, ... | Python os.rename if file system is full | I'm asking this beacause there's no way to try it myself (if there's one share it please (:).
I'm doing some file handling with Python os library, specifically file moving/renaming with os.rename().
Python docs explains some of the exceptions this function might raise here, but do not say anything about a full file sys... | [
"In practice this should rarely come up, but if you want to test I'd recommend creating a small file system (I don't know what OS you are on, but this could be on a virtual partition, a RAM disk, a flash drive, etc.) and loading it up with garbage files to see what happens. Something like this maybe:\naBigNumber =... | [
3,
1
] | [] | [] | [
"file_io",
"filesystems",
"operating_system",
"python"
] | stackoverflow_0005836776_file_io_filesystems_operating_system_python.txt |
Q:
Python matrix problems
This is continued from this thread: Python matrix, any solution?
Input
from numpy import *
import numpy
x=[['1','7'],
['1.5', '8'],
['2', '5.5'],
['2','9']]
Code
y = x[:, :, None] * x[:, None]
print y.sum(axis=0)
I received error:
"list indices must be integers, not
tuple"
But i... | Python matrix problems | This is continued from this thread: Python matrix, any solution?
Input
from numpy import *
import numpy
x=[['1','7'],
['1.5', '8'],
['2', '5.5'],
['2','9']]
Code
y = x[:, :, None] * x[:, None]
print y.sum(axis=0)
I received error:
"list indices must be integers, not
tuple"
But if x is
x = numpy.array([[1,... | [
"Edit:\nIt's not 100% clear to me what you're asking/trying to achieve here. In response to the comment about having [['1','7'] ...]: Currently you have string elements in your list; you can easily enough convert to numeric elements with:\nxf = [[float(el) for el in m] for m in x]\n\nOriginal post:\nDefine your l... | [
2,
1
] | [] | [] | [
"matrix",
"numpy",
"python"
] | stackoverflow_0005836817_matrix_numpy_python.txt |
Q:
Python: Converting GIF frames to PNG
I'm very new to python, trying to use it to split the frames of a GIF into PNG images.
# Using this GIF: http://www.videogamesprites.net/FinalFantasy1/Party/Before/Fighter-Front.gif
from PIL import Image
im = Image.open('Fighter-Front.gif')
transparency = im.info['transparen... | Python: Converting GIF frames to PNG | I'm very new to python, trying to use it to split the frames of a GIF into PNG images.
# Using this GIF: http://www.videogamesprites.net/FinalFantasy1/Party/Before/Fighter-Front.gif
from PIL import Image
im = Image.open('Fighter-Front.gif')
transparency = im.info['transparency']
im.save('test1.png', transparency=tr... | [
"I don't think you're doing anything wrong. See a similar issue here: animated GIF problem. It appears as if the palette information isn't correctly treated for later frames. The following works for me:\ndef iter_frames(im):\n try:\n i= 0\n while 1:\n im.seek(i)\n imframe =... | [
18,
6
] | [] | [] | [
"animated_gif",
"png",
"python",
"python_imaging_library"
] | stackoverflow_0004904940_animated_gif_png_python_python_imaging_library.txt |
Q:
Python line is too long, how can i make it more readable?
for pic,fn,xoff in [(self.PNew,self.New,0),(self.POpen,self.Open,0),(self.PSave,self.Save,0),(self.POrigin,self.SetOrigin,20),(self.PFiducial,self.SetFiducial,0),(self.PLine,self.AddLine,20),(self.PPoint,self.AddPoint,0),(self.PMove,self.AddMove,0),(self.PC... | Python line is too long, how can i make it more readable? | for pic,fn,xoff in [(self.PNew,self.New,0),(self.POpen,self.Open,0),(self.PSave,self.Save,0),(self.POrigin,self.SetOrigin,20),(self.PFiducial,self.SetFiducial,0),(self.PLine,self.AddLine,20),(self.PPoint,self.AddPoint,0),(self.PMove,self.AddMove,0),(self.PCircle,self.AddCircle,0),(self.PCall,self.AddCall,0)]: Button(Bu... | [
"items = [\n (self.PNew, self.New, 0),\n (self.POpen, self.Open, 0),\n (self.PSave, self.Save, 0),\n (self.POrigin, self.SetOrigin, 20),\n (self.PFiducial, self.SetFiducial, 0),\n (self.PLine, self.AddLine, 20),\n (self.PPoint, self.AddPoint, 0),\n (self.PMove, self.AddMove, 0),\n (self.P... | [
14,
3
] | [] | [] | [
"button",
"python",
"readability",
"tkinter"
] | stackoverflow_0005836976_button_python_readability_tkinter.txt |
Q:
Python - Ignore FIRST character (tab) every line when reading
This is a continuation of my former questions (check them if you are curious).
I can already see the light at the end of the tunnel, but I've got a last problem.
For some reason, every line starts with a TAB character.
How can I ignore that first char... | Python - Ignore FIRST character (tab) every line when reading | This is a continuation of my former questions (check them if you are curious).
I can already see the light at the end of the tunnel, but I've got a last problem.
For some reason, every line starts with a TAB character.
How can I ignore that first character ("tab" (\t) in my case)?
filename = "terem.txt"
OraRend = ... | [
"You could do line = line[1:] to just strip the first character. But if you do this, you should add an assertion that the first character is indeed a tab, to avoid mangling data without leading tab.\nThere is an easier alternative that also handles several other cases and doesn't break things if the things to be re... | [
5,
2,
1,
0
] | [] | [] | [
"file_io",
"python",
"strip"
] | stackoverflow_0005837794_file_io_python_strip.txt |
Q:
Unbound local variable problem in Python
I've got a following code snippet:
def isolation_level(level):
def decorator(fn):
def recur(level, *args, **kwargs):
if connection.inside_block:
if connection.isolation_level < level:
raise IsolationLevelError(conn... | Unbound local variable problem in Python | I've got a following code snippet:
def isolation_level(level):
def decorator(fn):
def recur(level, *args, **kwargs):
if connection.inside_block:
if connection.isolation_level < level:
raise IsolationLevelError(connection)
else:
... | [
"Local variables are determined at compile time: the assignments to the variable level a few lines below the line the error occurs in make that variable local to the inner function. So the line\nif level is None:\n\nactually tries to access a variable level in the innermost scope, but such a variable does not exis... | [
9
] | [] | [] | [
"bug_tracking",
"exception",
"function",
"local_variables",
"python"
] | stackoverflow_0005838034_bug_tracking_exception_function_local_variables_python.txt |
Q:
Question about reversed lists in Python
I am very new to python, as you will be able to tell.
If I have a list:
a = [1,2,3,2,1]
This evaluates to true:
a == a[::-1]
...but this evaluates to false:
a == a.reverse()
Why is that the case?
A:
because .reverse() reverses the list in-place and returns none:
>>> pri... | Question about reversed lists in Python | I am very new to python, as you will be able to tell.
If I have a list:
a = [1,2,3,2,1]
This evaluates to true:
a == a[::-1]
...but this evaluates to false:
a == a.reverse()
Why is that the case?
| [
"because .reverse() reverses the list in-place and returns none:\n>>> print a.reverse()\nNone\n\nand a == None evaluates to False.\n",
"a.reverse() has no return value, so the comparison is\na==None\nwhich is false\nyou can check with:\n>>> str(a.reversed())\n'None'\n\neven better:\n>>> (id(a.reverse()), id(None)... | [
8,
4,
3
] | [] | [] | [
"equivalence",
"list",
"python"
] | stackoverflow_0005837990_equivalence_list_python.txt |
Q:
IO within the Program Files Directory
I made a program that both gathers data from a .txt file by reading it, and writes data to a different .txt file. However, there is a problem. When I run the program in a normal directory It runs perfectly fine. A problem arises when I place it in the C:\Program Files director... | IO within the Program Files Directory | I made a program that both gathers data from a .txt file by reading it, and writes data to a different .txt file. However, there is a problem. When I run the program in a normal directory It runs perfectly fine. A problem arises when I place it in the C:\Program Files directory. When I run it I get IOERROR: [Errno 13] ... | [
"All directories under \\Program Files and \\Windows, as well as the root of C:\\, require administrator privileges in Windows Vista and 7 (and XP, when running as a non-administrative user, which is not the default). You shouldn't be trying to write there in the first place. This is a security measure to help prev... | [
3,
2,
2,
0
] | [] | [] | [
"io",
"python",
"uac",
"windows_7"
] | stackoverflow_0005838025_io_python_uac_windows_7.txt |
Q:
Practical Django Projects - Page 168
On page 168, there are two pieces of code :
def clean_password2(self):
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError("You must type the same password each time")
return self.cleaned_data['password2']
def clean(self... | Practical Django Projects - Page 168 | On page 168, there are two pieces of code :
def clean_password2(self):
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError("You must type the same password each time")
return self.cleaned_data['password2']
def clean(self):
if 'password1' in self.cleaned_data ... | [
"the clean_password2 method is doing a clean on a field, in this case the password2 field. (docs)\nthe clean method is called after the individual field validations. This is a good spot to do multi field validations according to the docs. \nRead more here.\n",
"In clean_password2 you are validating the password2 ... | [
1,
1
] | [] | [] | [
"django",
"project",
"python"
] | stackoverflow_0005838078_django_project_python.txt |
Q:
How to skip .hg / .git / .svn directories while recursing tree in python
I have a python script which I have been piecing together (one of my first python forays).
The script recurses a folder looking for XCode project files; the script works fine, but I would like to adapt it to skip any .svn (or .hg or .git) fol... | How to skip .hg / .git / .svn directories while recursing tree in python | I have a python script which I have been piecing together (one of my first python forays).
The script recurses a folder looking for XCode project files; the script works fine, but I would like to adapt it to skip any .svn (or .hg or .git) folders so that it isn't trying to modify source repositories.
Here is the script... | [
"As S.Lott says in his comment, this is mentioned in the documentation for os.walk. The following should work fine:\nfor root, dirs, files in os.walk(\".\"):\n if \".hg\" in dirs:\n dirs.remove(\".hg\")\n for f in files:\n print os.path.join(root, f)\n\n",
"Before handling the file, you can ch... | [
6,
0
] | [] | [] | [
"directory",
"os.walk",
"python"
] | stackoverflow_0005837948_directory_os.walk_python.txt |
Q:
Python - Import file into multiple arrays, dicts, tuples
How do you create a new array/tuple every new line?
Like I have this loop to read the file:
for line in csv.reader(f, delimiter='\t', lineterminator='\t\t', doublequote=False, skipinitialspace=True):
orar = OraRend._make(line[1:])
How can I create a... | Python - Import file into multiple arrays, dicts, tuples | How do you create a new array/tuple every new line?
Like I have this loop to read the file:
for line in csv.reader(f, delimiter='\t', lineterminator='\t\t', doublequote=False, skipinitialspace=True):
orar = OraRend._make(line[1:])
How can I create a tuple for every line?
(Since now, it'll run line by line, and... | [
"orar = [] \nfor line in csv.reader(f, delimiter='\\t', lineterminator='\\t\\t', doublequote=False, skipinitialspace=True):\n orar.append(OraRend._make(line[1:]))\n\n"
] | [
1
] | [] | [] | [
"arrays",
"iteration",
"loops",
"python",
"tuples"
] | stackoverflow_0005838206_arrays_iteration_loops_python_tuples.txt |
Q:
QGraphicsView error - Trying to show a jpg with Python
I'm using Python 3.2 with Eric5 and QTDesigner to try and display a jpg in a QGraphicsView scene. The following code gives me a
The file could not be opened. Reason: [Errno 22] Invalid argument: "
error on the first pass and then ends with a
The debugged p... | QGraphicsView error - Trying to show a jpg with Python | I'm using Python 3.2 with Eric5 and QTDesigner to try and display a jpg in a QGraphicsView scene. The following code gives me a
The file could not be opened. Reason: [Errno 22] Invalid argument: "
error on the first pass and then ends with a
The debugged program raised the exception unhandled AttributeError
"'MyFor... | [
"Looks like I needed to move my scene up to the class and then reference the name of the QGraphicsView object. I also added the ctypes for use in Windows. Here's the working code:\n#UIGraphicTest.py\n\nimport sys, ctypes\n#from PyQt4 import QtCore\nfrom PyQt4 import QtGui\nfrom screentest import Ui_MainWindow\n\n... | [
0
] | [] | [] | [
"python",
"qgraphicsview",
"qt_designer"
] | stackoverflow_0005810659_python_qgraphicsview_qt_designer.txt |
Q:
Hook into adding / removing items from list in python
I'd like to create a drop-in replacement for python's list, that will allow me to know when an item is added or removed. A subclass of list, or something that implements the list interface will do equally well. I'd prefer a solution where I don't have to reimpl... | Hook into adding / removing items from list in python | I'd like to create a drop-in replacement for python's list, that will allow me to know when an item is added or removed. A subclass of list, or something that implements the list interface will do equally well. I'd prefer a solution where I don't have to reimplement all of list's functionality though. Is there a easy +... | [
"To see what functions are defined in list, you can do\n>>> dir(list)\n\nThen you will see what you can override, try for instance this:\nclass MyList(list):\n def __iadd__(self, *arg, **kwargs):\n print \"Adding\"\n return list.__iadd__(self, *arg, **kwargs)\n\nYou probably need to do a few more o... | [
5,
2
] | [] | [] | [
"list",
"python"
] | stackoverflow_0005838307_list_python.txt |
Q:
Twisted reactor starting multiple times in a single program?
Is it possible to start the reactor more than once in the same program? Suppose you wanted to encapsulate twisted functionality inside a method, for API purposes.
For example, mymodule.py looks like this:
1 from twisted.web.client import getPage
2 f... | Twisted reactor starting multiple times in a single program? | Is it possible to start the reactor more than once in the same program? Suppose you wanted to encapsulate twisted functionality inside a method, for API purposes.
For example, mymodule.py looks like this:
1 from twisted.web.client import getPage
2 from twisted.internet import reactor
3
4 def _result(r):
5 ... | [
"Here's another way to organize your code, exploiting the single-threaded nature of Twisted: queue up all the urls you want to process, kick off the reactor, and decrement a counter when each request completes. When the counter reaches zero, stop the reactor which will return the results:\nfrom twisted.web.client ... | [
8,
6
] | [] | [] | [
"python",
"reactor",
"twisted"
] | stackoverflow_0005827304_python_reactor_twisted.txt |
Q:
Is there some django app to manage followers and followings?
I would like to manage users connections by followers and followings like twitter and other social media sites. Is there some app which already do this?
A:
Perhaps django-relationships is the one you are looking for.
| Is there some django app to manage followers and followings? | I would like to manage users connections by followers and followings like twitter and other social media sites. Is there some app which already do this?
| [
"Perhaps django-relationships is the one you are looking for.\n"
] | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005838372_django_python.txt |
Q:
What is the best way to end this thread when a function is called?
I'm having a bit of trouble with this queue:
import Queue
import threading
class test(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.request_queue = Queue.Queue()
def addtoqueue(self, item):
... | What is the best way to end this thread when a function is called? | I'm having a bit of trouble with this queue:
import Queue
import threading
class test(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.request_queue = Queue.Queue()
def addtoqueue(self, item):
self.request_queue.put(item)
def run(self):
while Tr... | [
"I'd alter the condition in your while loop so that it checked for a local variable. Add add a kill-switch to allow an external process to shut the thread down. You should probably extend kill_me to dispose of the object and its Queue in a nice way (eg if you want to store the Queue for the next time it's run).\nEd... | [
1,
1,
1
] | [] | [] | [
"multithreading",
"python",
"queue",
"terminate"
] | stackoverflow_0005838479_multithreading_python_queue_terminate.txt |
Q:
Open file in Python
My cwd is ~/Desktop/Development/Python/djcode/mysite, and I want to open a file on my Desktop. What is the syntax to open files in a different directory? (for example, if the file was in the cwd I would use open('file'). Thank you.
A:
Try this:
>>> import os
>>> path = os.path.expanduser('~/D... | Open file in Python | My cwd is ~/Desktop/Development/Python/djcode/mysite, and I want to open a file on my Desktop. What is the syntax to open files in a different directory? (for example, if the file was in the cwd I would use open('file'). Thank you.
| [
"Try this:\n>>> import os\n>>> path = os.path.expanduser('~/Desktop/foo.txt')\n>>> open(path, 'r')\n<open file '/home/pat/Desktop/foo.txt', mode 'r' at 0x7f0455af0db0>\n\n",
"Use the path to it, either absolute:\nmyfile = open('/path/to/myfile.ext')\n\nor relative:\nmyfile = open('../../../../myfile.ext')\n\ndepe... | [
9,
3,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005838735_django_python.txt |
Q:
Variables in Django
I am trying to create a basic template which displays the emails and corresponding domains from a CSV file.
My emails.html file is:
<html>
<head>Emails</head>
<body>
<ul>
{% for email in email_list %}
<li> {{email}} </li>
<li> {{domain}} </li>
{% endfor %}
... | Variables in Django | I am trying to create a basic template which displays the emails and corresponding domains from a CSV file.
My emails.html file is:
<html>
<head>Emails</head>
<body>
<ul>
{% for email in email_list %}
<li> {{email}} </li>
<li> {{domain}} </li>
{% endfor %}
</ul>
</body>
And my ... | [
"Create a custom filter as described here\nE.g.,:\nfrom django import template\nfrom django.template.defaultfilters import stringfilter\n\nregister = template.Library()\n\n@register.filter(name='domain')\n@stringfilter\ndef domain(value):\n if '@' in value:\n return value.split('@')[1]\n\nUsage (assuming ... | [
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005838848_django_python.txt |
Q:
Django theme/skin repository
Is there some place of freely available themes/skins for standard Django apps? I mean the typical stuff containing footer, header, etc.
A:
If your question refers to django-admin app, you could try Grappeli.
If not, you may like to get familiar with CSS Frameworks. Useful resources c... | Django theme/skin repository | Is there some place of freely available themes/skins for standard Django apps? I mean the typical stuff containing footer, header, etc.
| [
"If your question refers to django-admin app, you could try Grappeli.\nIf not, you may like to get familiar with CSS Frameworks. Useful resources can be found here or here. I would personally recommend 960.gs, but it's a matter of taste.\n",
"Take a look at djangoslingshot.com (full disclosure, it's my site).\nOn... | [
17,
9
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0000833799_django_django_admin_python.txt |
Q:
Adding a library to C
I'm working with python, but I have a basic understanding of packaging with C. However I don't know how to build the c 'path.' Also, my google searches seem to be failing me returning results on c++. Or is that my solution?
The objective is to include qrencode.h, I can surly put it in the sam... | Adding a library to C | I'm working with python, but I have a basic understanding of packaging with C. However I don't know how to build the c 'path.' Also, my google searches seem to be failing me returning results on c++. Or is that my solution?
The objective is to include qrencode.h, I can surly put it in the same folder but I'd like to kn... | [
"You use an include directive to include the *.h file in your C/C++ code:\n#include \"qrencode.h\"\n\nAs @Ignacio Vazquez-Abrams says, though, that's just a header, which declares functions; you need the actual functions, and they'll be in a *.dylib or *.so file, which needs to be linked into an executable. Compili... | [
1
] | [] | [] | [
"c",
"macos",
"python",
"qr_code",
"setuptools"
] | stackoverflow_0005839240_c_macos_python_qr_code_setuptools.txt |
Q:
pysqlite insert unicode data 8-bit bytestring error
I know similar permutations of this question have been asked before, but the answers don't seem to shed light on what I am doing wrong here.
I am trying to insert this row:
(Pdb) print row
['886', '39', '83474', '0', '0', '0', '0', '0', '1.00', 'D', '20070813... | pysqlite insert unicode data 8-bit bytestring error | I know similar permutations of this question have been asked before, but the answers don't seem to shed light on what I am doing wrong here.
I am trying to insert this row:
(Pdb) print row
['886', '39', '83474', '0', '0', '0', '0', '0', '1.00', 'D', '20070813', 'R', 'C', 'B', "SOCK 4PK", '\xe9\x9e\x8b\xe5\xad\x90\x... | [
"That is one of the most helpful error messages that I've ever seen. Just do what it says. Feed it unicode objects, not UTF-8-encoded str objects. In other words, lose the .encode('utf-8') or maybe follow that later by decode('utf-8') ...what exactly is csvdata?\nIf you ever get a UnicodeDecodeError in your existin... | [
4
] | [] | [] | [
"python",
"sqlite",
"unicode"
] | stackoverflow_0005839335_python_sqlite_unicode.txt |
Q:
counting a set dictionary of words in a specific html tag
I am trying to parse a document and if there is a name associated with a specific docno, count the total number of names. After the for loop ends for that docno, I want to store names[docno]= word count. Therefore, if namedict={'henry':'','joe':'') and he... | counting a set dictionary of words in a specific html tag | I am trying to parse a document and if there is a name associated with a specific docno, count the total number of names. After the for loop ends for that docno, I want to store names[docno]= word count. Therefore, if namedict={'henry':'','joe':'') and henry is in docno=doc 1 -4 times and joe 6 that the dictionary wo... | [
"I've cleaned up your code a bit to make it easier to follow. Here are a few comments and suggestions:\n\nTo answer the key question: you should be storing the count in names[docno] = names.get(docno, 0) + 1.\nUse a defaultdict(int) instead of names.get(aword, 0) + 1 to accumlate the count.\nUse set() for the namel... | [
0
] | [] | [] | [
"count",
"parsing",
"python",
"xml"
] | stackoverflow_0005839148_count_parsing_python_xml.txt |
Q:
Fastest way to filter the A010784 sequence
The A010784 sequence at OEIS is the sequence containing only numbers with distinct digits. This is a finite amount.
What I've been trying to do is find several numbers in this sequence with certain attributes.
E.g: 6 is a distinct number of magnitude 10. This can be found... | Fastest way to filter the A010784 sequence | The A010784 sequence at OEIS is the sequence containing only numbers with distinct digits. This is a finite amount.
What I've been trying to do is find several numbers in this sequence with certain attributes.
E.g: 6 is a distinct number of magnitude 10. This can be found as follows:
6 x 1 = 6
6 x 2 = 12
6 x 3 = 18
6 ... | [
"Isn't this just a permutation problem? For a given magnitude M do you do 10cM. \nFor instance, of magnitude 2, how many ways are there to choose 2 digits from 0..9? (Actually, it should be one from 1..9 and one from 0..9 where the second digit doesn't match the first.) \nYou certainly don't need to run through the... | [
1,
1,
1,
0
] | [] | [] | [
"algorithm",
"filter",
"oeis",
"python"
] | stackoverflow_0005838716_algorithm_filter_oeis_python.txt |
Q:
Listbox updating
When I run this it only displays the percent after it's done downloading so is there a way to make it display as it downloads it?
listbox = Listbox(Admin)
listbox.grid(row=19, column=9)
def download0(runums, song):
chunks = 10000
dat = ''
runum = runums.replace(' ', '%20')
url ... | Listbox updating | When I run this it only displays the percent after it's done downloading so is there a way to make it display as it downloads it?
listbox = Listbox(Admin)
listbox.grid(row=19, column=9)
def download0(runums, song):
chunks = 10000
dat = ''
runum = runums.replace(' ', '%20')
url = runum
down = url... | [
"The Tkinter event loop (started by mainloop()) runs on a single thread. It spins, reacting to events (e.g. mouse clicks), repainting widgets, and so on. When a button is clicked to start the download, control is passed to your download0() function. Until control returns to the event loop, no widgets will redraw... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0005838613_python_tkinter.txt |
Q:
Can someone help me with hangman?
I'm using python 2.7.1 to make a hangman game. I am trying to let the user choose whether to replay before the game finishes. I am trying to use a variable keep_playing, but it doesn't work.
Also, in guesses=word_len * ['_'], I want to have a space between the underscores because,... | Can someone help me with hangman? | I'm using python 2.7.1 to make a hangman game. I am trying to let the user choose whether to replay before the game finishes. I am trying to use a variable keep_playing, but it doesn't work.
Also, in guesses=word_len * ['_'], I want to have a space between the underscores because, if they stick together, I can't see ho... | [
"print ''.join(guesses) can be turned into print ' '.join(guesses) giving spaces between the letters\nyou need to do keep_playing = False before while keep_playing == False: and the main game loop should be in a function that gets called from this loop if keep_playing == True:\n",
"The following will do what you ... | [
3,
1
] | [] | [] | [
"console",
"python"
] | stackoverflow_0005838986_console_python.txt |
Q:
Send a file between 2 mobile phones via bluetooth using Python
I am trying to send a file between two mobile phones using Python language
for the phone that will send i used this code:
import socket,e32socket,appuifw
socket=e32socket.socket(e32socket.AF_BT,e32socket.SOCK_STREAM,e32socket.BTPROTO_RFCOMM,e32socket.O... | Send a file between 2 mobile phones via bluetooth using Python | I am trying to send a file between two mobile phones using Python language
for the phone that will send i used this code:
import socket,e32socket,appuifw
socket=e32socket.socket(e32socket.AF_BT,e32socket.SOCK_STREAM,e32socket.BTPROTO_RFCOMM,e32socket.OBEX)
device =e32socket.bt_obex_discover()
print device
address=devic... | [
"For one, \"E:23.txt\" is not a valid path to a file. Always remember your slashes, they are very important! Thus, you would change it from:\ne32socket.bt_obex_send_file(address,channel,u\"E:23.txt\")\n\nto\ne32socket.bt_obex_send_file(address,channel,u\"E:\\\\23.txt\")\n\nAlso, I am not quite familiar with bt_obex... | [
0
] | [] | [] | [
"bluetooth",
"mobile_phones",
"python"
] | stackoverflow_0005743098_bluetooth_mobile_phones_python.txt |
Q:
how can I make a list of callable commands python?
I was wondering how you go about making a list of commands the user can enter. Like for example, user types in "who" to get a list of who is on in a MUD. Is it all done using if, elif and else in pythons?
I am using Python 3.1 btw.
A:
Nope. Dispatch dictionary.... | how can I make a list of callable commands python? | I was wondering how you go about making a list of commands the user can enter. Like for example, user types in "who" to get a list of who is on in a MUD. Is it all done using if, elif and else in pythons?
I am using Python 3.1 btw.
| [
"Nope. Dispatch dictionary.\ndef who(*args, **kwargs):\n ...\n\ncommands = {\n 'who': who,\n ...\n}\n\n...\nif command in commands:\n commands[command](*args, **kwargs)\nelse:\n print('Bad command or file name')\n\n",
"The cmd module is made for this. Just subclass cmd.Cmd(), including a set of methods tha... | [
11,
4,
0,
0
] | [] | [] | [
"command",
"python",
"python_3.x"
] | stackoverflow_0005839727_command_python_python_3.x.txt |
Q:
How to create a RESTful Handler that accepts both POST and GET?
I want API support for:
GET /api/spam/{id}
POST /api/spam
body: {'name': 'green spam'}
I would normally route to a Handler by:
webapp.WSGIApplication([r'/api/spam/(.*)', APISpam])
class APISpam(RequestHandler):
def get(self, id):
# do st... | How to create a RESTful Handler that accepts both POST and GET? | I want API support for:
GET /api/spam/{id}
POST /api/spam
body: {'name': 'green spam'}
I would normally route to a Handler by:
webapp.WSGIApplication([r'/api/spam/(.*)', APISpam])
class APISpam(RequestHandler):
def get(self, id):
# do stuff
def post(self):
# do stuff
But the post fails becaus... | [
"Normally you'd simply make them separate handlers: As Sebastian points out, they're different resources - the collection itself, vs one element of the collection.\nIf you must use the same handler, though, you can supply a default argument:\nclass APISpam(RequestHandler):\n def get(self, id=None):\n # do stuff... | [
2
] | [] | [] | [
"google_app_engine",
"python",
"requesthandler",
"rest"
] | stackoverflow_0005839670_google_app_engine_python_requesthandler_rest.txt |
Q:
Django Templates urls not updating
I have been changing some of my views templates urls lately,
and switched from:
(r'^(?P<slug>[^\.]+)/view_post/$', 'view_post'),
to :
(r'^(?P<slug>[^\.]+)/post/$', 'post'),
in my blog application urls.py. And, though I did a syncdb and migrated
my blog application with south, ... | Django Templates urls not updating | I have been changing some of my views templates urls lately,
and switched from:
(r'^(?P<slug>[^\.]+)/view_post/$', 'view_post'),
to :
(r'^(?P<slug>[^\.]+)/post/$', 'post'),
in my blog application urls.py. And, though I did a syncdb and migrated
my blog application with south, the new url doesn't seem to be considere... | [
"If this is running under Apache, you would have to force-reload or restart apache for your changes to be applied. \nAlso, you don't have to syncdb or migrate your app when changing your urls.py map (unless you are running a custom add-on I don't know about).\n",
"How are you restarting Gunicorn? with -HUP? Sound... | [
2,
1,
0
] | [] | [] | [
"django",
"django_urls",
"django_views",
"python"
] | stackoverflow_0005834109_django_django_urls_django_views_python.txt |
Q:
Tell a friend in django
I am looking for a generic Tell a Friend application in django which will allow my website users to invite and tell about website features to one's mail or social networking friends by sending invitation email to join the website....
Any suggestion will help...
Thanks in advance...
A:
Th... | Tell a friend in django | I am looking for a generic Tell a Friend application in django which will allow my website users to invite and tell about website features to one's mail or social networking friends by sending invitation email to join the website....
Any suggestion will help...
Thanks in advance...
| [
"This isn't Django, but you might consider a remotely-hosted application like ShareThis. \nOtherwise, you could make use of this code, and add parameters (such as name and email address) into the URL where possible / necessary. In any case, I'm not aware of a Django-specific solution that integrates with the CMS ou... | [
2,
2
] | [] | [] | [
"contacts",
"django",
"email",
"python",
"social_networking"
] | stackoverflow_0005839987_contacts_django_email_python_social_networking.txt |
Q:
Which is the better way to pass data into Python Unittest Redirected STDIN or Pickle?
Short Question
What is the best way to get data into a Python unittest case ?
Background
My project is using Python's unittest module as an automated way execute a series of tests that will need to run on many of the same type of... | Which is the better way to pass data into Python Unittest Redirected STDIN or Pickle? | Short Question
What is the best way to get data into a Python unittest case ?
Background
My project is using Python's unittest module as an automated way execute a series of tests that will need to run on many of the same type of boards. So far this is a good fit to what the unittest module was designed for; the twist... | [
"I have created unittests which test against a third party service (Zoho CRM). To test the service API, you need to store username and password crendetials.\nSince this is premium service and you are creating open source software, naturally you cannot hardcode your login credentials to the source code itself.\nSo I... | [
2
] | [] | [] | [
"pickle",
"python",
"redirect",
"stdin",
"unit_testing"
] | stackoverflow_0005834872_pickle_python_redirect_stdin_unit_testing.txt |
Q:
run a process in another terminal
I'm actually running a subprocess from a python program using Popen
proc= subprocess.Popen("xterm -e python script.py", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
And when this process is running on xterm, we can kill it using Ctrl+C, is there a way to send other... | run a process in another terminal | I'm actually running a subprocess from a python program using Popen
proc= subprocess.Popen("xterm -e python script.py", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
And when this process is running on xterm, we can kill it using Ctrl+C, is there a way to send other signals using (Ctrl+Z and fg,...) to r... | [
"You could do it programatically in psutil\nimport psutil\np = psutil.Pocesss(proc.pid)\np.suspend()\np.resume()\n\n",
"With Python2.6+\n# send ctrl+c\npopen.send_signal(signal.SIGINT)\n\n"
] | [
1,
0
] | [] | [] | [
"python",
"signals",
"subprocess",
"xterm"
] | stackoverflow_0005842223_python_signals_subprocess_xterm.txt |
Q:
PyQt Paint Custom Date Format
I'm displaying some information from a sql server in a qtableview using a sqlmodel.
I have set up a custom delegate to deal with the editing of the data.
I would like to display my dates in a specific format, when they table is first loaded the dates are displayed as such:
20011-04-30... | PyQt Paint Custom Date Format | I'm displaying some information from a sql server in a qtableview using a sqlmodel.
I have set up a custom delegate to deal with the editing of the data.
I would like to display my dates in a specific format, when they table is first loaded the dates are displayed as such:
20011-04-30
But when I edit the date and click... | [
"Why is editor.setDisplayFormat(\"yyyy/MM/dd\") commented out? Shouldn't that take care of the formatting?\n"
] | [
1
] | [] | [] | [
"delegates",
"pyqt",
"python"
] | stackoverflow_0005840895_delegates_pyqt_python.txt |
Q:
Files form .py not reading into C
Lets say I have float x from main
import progC
def main():
x = 3
y=progC(x)
print y
if __name__ == __main__
main()
#include <Python.h>
static PyObject* py_bracket(PyObject* self, float x){
x = x+5;
return Py_BuildValue("d",x);
}
ok problem is my flo... | Files form .py not reading into C | Lets say I have float x from main
import progC
def main():
x = 3
y=progC(x)
print y
if __name__ == __main__
main()
#include <Python.h>
static PyObject* py_bracket(PyObject* self, float x){
x = x+5;
return Py_BuildValue("d",x);
}
ok problem is my float x in my C program receiving 0 not t... | [
"In my opinion, the problem could be solved by using int instead of float. Python variables hold 12-bytes of memory by default and \"C float\" only hold 4. The second option is using the PyTypeObject PyFloat_Type that specifies that float type is required.\n",
"Try this:\nstatic PyObject* py_bracket(PyObject* sel... | [
0,
0
] | [] | [] | [
"c",
"python",
"python_c_api"
] | stackoverflow_0005842342_c_python_python_c_api.txt |
Q:
What is the easiest way in python to modify linux config file?
I have some python scripts that configure linux computers. One of the tasks is to modify a configuration file for subversion. This file, ~/.subversion/servers is very simple and looks like this:
# store-passwords = no
# store-plaintext-passwords = no
#... | What is the easiest way in python to modify linux config file? | I have some python scripts that configure linux computers. One of the tasks is to modify a configuration file for subversion. This file, ~/.subversion/servers is very simple and looks like this:
# store-passwords = no
# store-plaintext-passwords = no
# store-ssl-client-cert-pp = no
# store-ssl-client-cert-pp-plaintext ... | [
"The ~/.subversion/servers file is in INI format.\nSo you can use the ConfigParser for implementing whatever you need.\nhttp://docs.python.org/library/configparser.html\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0005842459_python.txt |
Q:
converting/mapping linux reference path without altering the file?
Currently on a project that my client needs the reference file path to
remain in linux format. For example
A.ma , referencing objects from --> //linux/project/scene/B.ma
B.ma , referencing objects from --> //linux/project/scene/C.ma
Most of our Ma... | converting/mapping linux reference path without altering the file? | Currently on a project that my client needs the reference file path to
remain in linux format. For example
A.ma , referencing objects from --> //linux/project/scene/B.ma
B.ma , referencing objects from --> //linux/project/scene/C.ma
Most of our Maya license here however are on Windows. I can run a
Python script that c... | [
"Here is a solution. First step is to create a dict that keeps track of linux/windows references (don't forget to import the re module for regexp):\n>>> def windows_path(path):\n return path.replace('//linux', 'Z:').replace('/', '\\\\')\n\n>>> reg = re.compile('(\\w+\\.ma) , referencing objects from --> (.*)')\n... | [
1,
0,
0,
0
] | [] | [] | [
"maya",
"python"
] | stackoverflow_0004884306_maya_python.txt |
Q:
dictionary key-call
im building a test program. its essentially a database of bugs and bug fixes. it may end up being an entire database for all my time working in python.
i want to create an effect of layers by using a dictionary.
here is the code as of april 29 2011:
modules=['pass']
syntax={'PRINT':''' in eclip... | dictionary key-call | im building a test program. its essentially a database of bugs and bug fixes. it may end up being an entire database for all my time working in python.
i want to create an effect of layers by using a dictionary.
here is the code as of april 29 2011:
modules=['pass']
syntax={'PRINT':''' in eclipse anthing which
you "PR... | [
"I'm not quite sure what you want, but to print the content of a single key of dictionary you index it:\nsyntax['PRINT']\n\nMaybe this help a bit:\nmodules=['pass']\nsyntax={\n 'PRINT':''' in eclipse anthing which \nyou \"PRINT\" needs to be within a set of paranthesis''',\n 'STRRET':'anytime you need to use ... | [
0
] | [] | [] | [
"dictionary",
"eclipse",
"pydev",
"python"
] | stackoverflow_0005842756_dictionary_eclipse_pydev_python.txt |
Q:
Faster Port Forwarding
I wrote an application in Pyhon that needs to ocmmunicate with a server for almost everything. The problem is, when the request is sent to the server, and the response sent back, it takes way too long. I think it is because of all of the port forwarding. My question is, is there a way I can ... | Faster Port Forwarding | I wrote an application in Pyhon that needs to ocmmunicate with a server for almost everything. The problem is, when the request is sent to the server, and the response sent back, it takes way too long. I think it is because of all of the port forwarding. My question is, is there a way I can make this faster from a soft... | [
"The question does not make much sense and seems just a weird assumption without further evidence. Port forwarding should not have any measurable impact on the throughput - specially there is nothing to do on the application level.\n"
] | [
0
] | [] | [] | [
"communication",
"performance",
"portforwarding",
"python"
] | stackoverflow_0005842870_communication_performance_portforwarding_python.txt |
Q:
converting a string which contains both utf-8 encoded bytestrings and codepoints to utf-8 encoded string
I' m getting a JSON response from an API which looks like this:
{"excerpt":"...where we\u00e2\u0080\u0099ll just have to wait and see, I\u00e2\u0080\u0099m sure official announcements with start flowing in the ... | converting a string which contains both utf-8 encoded bytestrings and codepoints to utf-8 encoded string | I' m getting a JSON response from an API which looks like this:
{"excerpt":"...where we\u00e2\u0080\u0099ll just have to wait and see, I\u00e2\u0080\u0099m sure official announcements with start flowing in the coming months \u2013special\u2013..."}
This is the raw JSON response returning from the API call. Now, as you... | [
"You could use a regular expression to identify \"UTF-8-like\" Unicode sequences and process them into the correct Unicode character:\nimport re\nD = {\"excerpt\":\"...where we\\u00e2\\u0080\\u0099ll just have to wait and see, I\\u00e2\\u0080\\u0099m sure official announcements with start flowing in the coming mont... | [
6
] | [] | [] | [
"encoding",
"python",
"unicode",
"utf_8"
] | stackoverflow_0005842115_encoding_python_unicode_utf_8.txt |
Q:
Django SMTP and secure password authentication
I have an SMTP server that requires secure password authentication (e.g. Outlook requires to check SPA). Is there a way to deal with it with Django SMTPConnection?
Or maybe ideas about any python solution to deal SPA?
Honestly, I couldn't find enough about SPA, to und... | Django SMTP and secure password authentication | I have an SMTP server that requires secure password authentication (e.g. Outlook requires to check SPA). Is there a way to deal with it with Django SMTPConnection?
Or maybe ideas about any python solution to deal SPA?
Honestly, I couldn't find enough about SPA, to understand what is it exactly:
en.wikipedia:Secure_Pas... | [
"After googling for it I found the same question asked on Google Groups:\nhttp://groups.google.com/group/django-users/browse_thread/thread/fc7f77e2f796e6a4/90ae093cbb2863b8?pli=1\n\nSPA is a proprietary MS protocol for\n which there is no documentation. I\n don't think you will find a non MS\n implementation of... | [
0,
0
] | [] | [] | [
"django",
"ntlm",
"python",
"smtp"
] | stackoverflow_0002629889_django_ntlm_python_smtp.txt |
Q:
Pylons & Beaker: JSON Encoded Sessions
Need to read Pylons session data (just read, not write to) in node.js
Once I decode the base64, I'm left with a string containing a serialized Python object which, is a pain to parse in node.js
How can I get Beaker to serialize to JSON instead? For it is far easier for node.j... | Pylons & Beaker: JSON Encoded Sessions | Need to read Pylons session data (just read, not write to) in node.js
Once I decode the base64, I'm left with a string containing a serialized Python object which, is a pain to parse in node.js
How can I get Beaker to serialize to JSON instead? For it is far easier for node.js to handle.
| [
"i had to look inside beaker to find what you call \"Python serialized strings\" are python pickles.\ni don't think it would be more than a few lines to change it get it to use json to store the dict.\nhere is a patch against https://bitbucket.org/bbangert/beaker/src/257f147861c8:\ndiff -r 257f147861c8 beaker/sessi... | [
10
] | [] | [] | [
"beaker",
"node.js",
"pylons",
"python"
] | stackoverflow_0005842738_beaker_node.js_pylons_python.txt |
Q:
Limiting one Content item per Member in a Folder on Plone 4
I have created a custom Archetypes content type called "Résumé" and would like to enforce a limitation that lets a Member add only one item of this type inside a folder. Even better would be redirecting the member to the edit page of his or her item, if i... | Limiting one Content item per Member in a Folder on Plone 4 | I have created a custom Archetypes content type called "Résumé" and would like to enforce a limitation that lets a Member add only one item of this type inside a folder. Even better would be redirecting the member to the edit page of his or her item, if it already exists in that folder.
How can I enforce this limitatio... | [
"A solution to a similar usecase for Plone 3 can be found in the eestec.base. We did it by overriding the createObject.cpy and adding a special check for this.\nCode is in the collective SVN, at http://dev.plone.org/collective/browser/eestec.base/trunk/eestec/base/skins/eestec_base_templates/createObject.cpy, lines... | [
5,
2,
1
] | [] | [] | [
"archetypes",
"permissions",
"plone",
"python",
"zope"
] | stackoverflow_0005832899_archetypes_permissions_plone_python_zope.txt |
Q:
Python dumps variable from loop
Total bottles variable in the getBottles module resets to 0 upon exiting the while counter <8 loop. I've also tried using return statements but to no avail. How do I get the value from totalBottles variable to pass to my other module.
global totalBottles, totalPayout, todayBottles
t... | Python dumps variable from loop | Total bottles variable in the getBottles module resets to 0 upon exiting the while counter <8 loop. I've also tried using return statements but to no avail. How do I get the value from totalBottles variable to pass to my other module.
global totalBottles, totalPayout, todayBottles
totalBottles=0 #store the accumulated ... | [
"i can't resist... (although there are still issues with this at least it might work where the other won't)\nclass Bottles:\n def __init__(self):\n self.totalBottles=0 #store the accumulated bottle values\n self.counter=1 #will control the loop\n self.todayBottles=0 #store the number of bottles... | [
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005843709_python.txt |
Q:
SQLAlchemy circular dependency - how to solve it?
I have two tables, News and Files:
# unrelated columns removed
class News(db.Model):
id = db.Column(db.Integer, primary_key=True)
file_id_logo = db.Column(db.Integer, db.ForeignKey('files.id'))
logo = db.relationship('File', lazy=False)
class File(db.... | SQLAlchemy circular dependency - how to solve it? | I have two tables, News and Files:
# unrelated columns removed
class News(db.Model):
id = db.Column(db.Integer, primary_key=True)
file_id_logo = db.Column(db.Integer, db.ForeignKey('files.id'))
logo = db.relationship('File', lazy=False)
class File(db.Model):
id = db.Column(db.Integer, primary_key=True... | [
"use_alter – passed to the underlying ForeignKeyConstraint to indicate the constraint should be generated/dropped externally from the CREATE TABLE/ DROP TABLE statement. See that classes’ constructor for details.\nhttps://docs.sqlalchemy.org/en/13/core/constraints.html#sqlalchemy.schema.ForeignKeyConstraint.params.... | [
24
] | [] | [] | [
"circular_dependency",
"python",
"sqlalchemy"
] | stackoverflow_0005843704_circular_dependency_python_sqlalchemy.txt |
Q:
Using a single telnet session in two different methods
I need to use a telnet session like in this code below :
class ModTelnet(MXComm):
def __init__(self):
MXComm.__init__(self)
def _connect(self):
#connect to telnet session @ localhost port 4444
try:
HOST = "localhost"
port = "4444"
... | Using a single telnet session in two different methods | I need to use a telnet session like in this code below :
class ModTelnet(MXComm):
def __init__(self):
MXComm.__init__(self)
def _connect(self):
#connect to telnet session @ localhost port 4444
try:
HOST = "localhost"
port = "4444"
# tn = telnetlib.Telnet(HOST, port)
tn.open(H... | [
"tn should be self.tn so that the other methods can access it\n"
] | [
2
] | [] | [] | [
"python",
"telnet",
"telnetlib"
] | stackoverflow_0005843998_python_telnet_telnetlib.txt |
Q:
Fourier Series from Discrete Fourier Transform
I'm trying to recreate a function from a discrete fourier transform. In Matlab it would be done like this:
function [y] = Fourier(dft,x)
n = length(dft);
y = cos(pi*(x+1)'*(0:n-1))*real(dft)+sin(pi*(x+1)'*(0:n-1))*imag(dft)
end
My attempt in Python is falling flat be... | Fourier Series from Discrete Fourier Transform | I'm trying to recreate a function from a discrete fourier transform. In Matlab it would be done like this:
function [y] = Fourier(dft,x)
n = length(dft);
y = cos(pi*(x+1)'*(0:n-1))*real(dft)+sin(pi*(x+1)'*(0:n-1))*imag(dft)
end
My attempt in Python is falling flat because I don't know how to add up all the coefficient... | [
"You were running two nested loops instead of one. Try this:\ny = ([(dft[nn].real)*np.cos(np.pi*x*nn) + (dft[nn].imag)*np.cos(np.pi*x*nn) for nn in range(0,n)])\n\n",
"You actually should not use a Python loop at all. You get more readable and much more efficient code if you vectorise the expression. Assuming d... | [
5,
5
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0005838994_numpy_python.txt |
Q:
How to constantly send STDOUT to my python TCP server?
i have simple python echo server which uses sockets , and echoes random numbers to clients .
i have another program which prints every 2 second values to stdout.
If it was just a script i could have redirected like this 'stdout' | python script.py , and fet... | How to constantly send STDOUT to my python TCP server? |
i have simple python echo server which uses sockets , and echoes random numbers to clients .
i have another program which prints every 2 second values to stdout.
If it was just a script i could have redirected like this 'stdout' | python script.py , and fetch it in the script like this data = sys.stdin.read(). But ... | [
"I think you need something similar to Python subprocess. In that example, consider dmesg as your number generator, and the grep as your socket server; however, you will just open a PIPE in the socket server instead of spawning a shell command.\nAssume you have two processes, the talker and server (in Python 2.x).... | [
4
] | [] | [] | [
"python",
"stdout"
] | stackoverflow_0005844650_python_stdout.txt |
Q:
Moving files by starting letter in powershell, python or other scripting language running windows
I need a script than can recursively traverse c:\somedir\ and move files to c:\someotherdir\x\ - where x is the starting letter of the file.
Can anyone help?
Ended up with this one:
import os
from shutil import copy... | Moving files by starting letter in powershell, python or other scripting language running windows | I need a script than can recursively traverse c:\somedir\ and move files to c:\someotherdir\x\ - where x is the starting letter of the file.
Can anyone help?
Ended up with this one:
import os
from shutil import copy2
import uuid
import random
SOURCE = ".\\pictures\\"
DEST = ".\\pictures_ordered\\"
for path, dirs, f... | [
"I suspect this will work in PowerShell.\ngci -path c:\\somedir -filter * -recurse |\n where { -not ($_.PSIsContainer) } |\n foreach { move-item -path $_.FullName -destination $_.Substring(0, 1) }\n\n",
"Here's a simple script that does what you want. It doesn't tell you anything about what it's doing, and ... | [
3,
3,
2,
1,
0
] | [] | [] | [
"directory",
"file",
"powershell",
"python",
"sorting"
] | stackoverflow_0005844149_directory_file_powershell_python_sorting.txt |
Q:
General method for unpacking and combining nested tuples
I've generated the cartesian product of three dicts thus:
import itertools
combined = list(itertools.product(foo, bar, baz))
So my list now looks like:
[(('text a', 'value a'), ('text b', 'value b'), ('text c', 'value c')), … ]
What I want to do is unp... | General method for unpacking and combining nested tuples | I've generated the cartesian product of three dicts thus:
import itertools
combined = list(itertools.product(foo, bar, baz))
So my list now looks like:
[(('text a', 'value a'), ('text b', 'value b'), ('text c', 'value c')), … ]
What I want to do is unpack this list such that I end up with a list of lists containi... | [
"map(lambda v: map(' '.join, zip(*v)), combined)\n\n",
"You don't have to cram everything on one line:\ndef combine(items):\n for tuples in items:\n text, numbers = zip(*tuples)\n yield ' '.join(text), sum(numbers)\n\nprint list(combine(product( ... )))\n\n",
"Here's a generalization:\ndef comb... | [
4,
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0005844236_python.txt |
Q:
Parsing lines from a live streaming website in Python
I'm trying to read in info that is constantly changing from a website.
For example, say I wanted to read in the artist name that is playing on an online radio site.
I can grab the current artist's name but when the song changes, the HTML updates itself and I've... | Parsing lines from a live streaming website in Python | I'm trying to read in info that is constantly changing from a website.
For example, say I wanted to read in the artist name that is playing on an online radio site.
I can grab the current artist's name but when the song changes, the HTML updates itself and I've already opened the file via:
f = urllib.urlopen("SITE")
S... | [
"You'll have to periodically re-download the website. Don't do it constantly because that will be too hard on the server.\nThis is because HTTP, by nature, is not a streaming protocol. Once you connect to the server, it expects you to throw an HTTP request at it, then it will throw an HTTP response back at you cont... | [
1,
1,
0
] | [] | [] | [
"live",
"python",
"stream",
"urllib"
] | stackoverflow_0005844870_live_python_stream_urllib.txt |
Q:
Calculate frequency of function words
I would like to calculate the frequency of function words in Python/NLTK. I see two ways to go about it :
Use Part-Of-Speech tagger and sum up on POS tags which constitute to function words
Create a list of function words and perform a simple look up
The catch in the first ... | Calculate frequency of function words | I would like to calculate the frequency of function words in Python/NLTK. I see two ways to go about it :
Use Part-Of-Speech tagger and sum up on POS tags which constitute to function words
Create a list of function words and perform a simple look up
The catch in the first case is that, my data is noisy and I don't ... | [
"I just used the LIWC English 2007 dictionary ( I paid for the same) and performed a simple lookup as of now. Any other answers are most welcome.\nI must say I am a little surprised by the impulsiveness of a couple of answers here. Since, someone asked for code. Here's what I did :\n''' Returns frequency of functio... | [
6,
0
] | [] | [] | [
"nlp",
"nltk",
"part_of_speech",
"python",
"word_frequency"
] | stackoverflow_0005819840_nlp_nltk_part_of_speech_python_word_frequency.txt |
Q:
is it possible to write python scripts which can do router configuration without telnetting into the router?
i want to do router configuration using python , but dont want to use any application level protocol to configure it . Is it possible to deal it on a hardware level ? Please do tell if the question is vague... | is it possible to write python scripts which can do router configuration without telnetting into the router? | i want to do router configuration using python , but dont want to use any application level protocol to configure it . Is it possible to deal it on a hardware level ? Please do tell if the question is vague or if it needs more explanation , then I would put more details on as to what I have my doubt in
| [
"The title of your question by itself makes some sense.\nThe body of your question doesn't make sense.\n\nis it possible to write python scripts which can do router configuration without telnetting into the router?\nYes, depending on the platform. You maybe able to use a variety of other methods to configure the ro... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003555485_python.txt |
Q:
Using Python list to query Google App Engine datastore
I have created a form in my Google App Engine application for users to select items from a list, the specific details of which (ex. name, other properties) will then be pulled from a datastore table called Item and displayed in a table once the user submits th... | Using Python list to query Google App Engine datastore | I have created a form in my Google App Engine application for users to select items from a list, the specific details of which (ex. name, other properties) will then be pulled from a datastore table called Item and displayed in a table once the user submits the form.
I have a Python list that contains the keys for the ... | [
"db.get(list_of_keys)\nhttp://code.google.com/appengine/docs/python/datastore/functions.html\n"
] | [
5
] | [] | [] | [
"django",
"google_app_engine",
"gql",
"python"
] | stackoverflow_0005845395_django_google_app_engine_gql_python.txt |
Q:
Error when trying to subclass gdb.Breakpoint while writing PythonGDB extension
I'm trying to write a simple python extension for GDB that outputs to a file whenever a breakpoint is hit. According to the documentation, "The gdb.Breakpoint class can be sub-classed" (see http://sourceware.org/gdb/onlinedocs/gdb/Break... | Error when trying to subclass gdb.Breakpoint while writing PythonGDB extension | I'm trying to write a simple python extension for GDB that outputs to a file whenever a breakpoint is hit. According to the documentation, "The gdb.Breakpoint class can be sub-classed" (see http://sourceware.org/gdb/onlinedocs/gdb/Breakpoints-In-Python.html)
However when I try the following code I get the error "TypeEr... | [
"The appropriate gdb 7.2 documentation is here:\nhttp://sourceware.org/gdb/download/onlinedocs/gdb/Breakpoints-In-Python.html#Breakpoints-In-Python\nI'm assuming EmployedRussian is using a relatively recent gdb 7.2 (7.2.90 or something equivalent which seems to contain these patches)\nthis is not really an official... | [
5,
3
] | [] | [] | [
"extending",
"gdb",
"python",
"scripting"
] | stackoverflow_0005840147_extending_gdb_python_scripting.txt |
Q:
How do you Identify the interface of a packet while listening to network traffic on all devices?
I am writing a python program that needs to listening to traffic on all networking devices and identify packets based on their incoming interface. To listen on all interfaces I started my capture without specify a dev... | How do you Identify the interface of a packet while listening to network traffic on all devices? | I am writing a python program that needs to listening to traffic on all networking devices and identify packets based on their incoming interface. To listen on all interfaces I started my capture without specify a device, but I am unable to denote the interface of a particular packet. How is this done?
| [
"I assume that the MAC address is sufficient information for you.\n\nThe first 6 octets of a packet is the destination MAC address, which is immediately followed by the 6 octets of source MAC address.\n\nSource\n\n"
] | [
2
] | [] | [] | [
"libpcap",
"pcap",
"python",
"scapy",
"tcpdump"
] | stackoverflow_0005845719_libpcap_pcap_python_scapy_tcpdump.txt |
Q:
Google app engine python timeout sending email
My script grabs the content of an rss page gets the urls in that page saves them to a list then it grabs the content of each url and it emails the contents of the page to me. Everything is working very well accept I can't send every link in the list. Typically about 2... | Google app engine python timeout sending email | My script grabs the content of an rss page gets the urls in that page saves them to a list then it grabs the content of each url and it emails the contents of the page to me. Everything is working very well accept I can't send every link in the list. Typically about 22 links in the list. I don't want to combine the co... | [
"Welcome to Stack Overflow!\nThe task queue is built to solve this problem. You can leverage it with minimal change to your existing code using the deferred library:\nInstead of calling message.send(), do something like this:\ndef send_email(message): \n message.send()\n\ndeferred.defer(send_email, message)\n\nTh... | [
6
] | [] | [] | [
"deadlines",
"google_app_engine",
"python",
"quota",
"timeout"
] | stackoverflow_0005845623_deadlines_google_app_engine_python_quota_timeout.txt |
Q:
More Pythonic Way to Merge a list of dictionaries into one?
Is there a more Pythonic way to do this? I know there must be.
for form in forms:
d[form.keys()[0]] = form.values()[0]
Thanks!
A:
If you want d to have all the key-value pairs of the dictionaries in forms:
for form in forms:
d.update(form)
A:
... | More Pythonic Way to Merge a list of dictionaries into one? | Is there a more Pythonic way to do this? I know there must be.
for form in forms:
d[form.keys()[0]] = form.values()[0]
Thanks!
| [
"If you want d to have all the key-value pairs of the dictionaries in forms:\nfor form in forms:\n d.update(form)\n\n",
"reduce(lambda acc,form: dict(acc,**form),forms)\n\nPS: I generally use dict(x,**y) to merge to dictionaries than x.update(y) since most of the time I don't want the changes to be inplace. Th... | [
6,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005845676_django_python.txt |
Q:
Python - Instance Variable Access
I am currently making a game. I have 2 classes and I want one to access the others instance variables. I'm not sure how to do this or if it is possible.
Both Classes at some point inherits to the class gameEngine
gameEngine <- Game
gameEngine <- SuperSprite <- Character <- Enemy
g... | Python - Instance Variable Access | I am currently making a game. I have 2 classes and I want one to access the others instance variables. I'm not sure how to do this or if it is possible.
Both Classes at some point inherits to the class gameEngine
gameEngine <- Game
gameEngine <- SuperSprite <- Character <- Enemy
gameEngine <- SuperSprite <- Character <... | [
"If i understand you correctly, You want to have the Enermy instances get access to of the Player instance\nThere are 2 ways to accomplish it. I'm using the second method atm in my programs and plans to add the first method.\nFirst way involves getting the class to have an instance, and calling a class method allow... | [
1,
0
] | [] | [] | [
"instance",
"object",
"python",
"variables"
] | stackoverflow_0005845690_instance_object_python_variables.txt |
Q:
Logging into a server and parsing files on that server with Python
I would like to be able to use a Python script that I wrote to search files to login to an Ubuntu server that's password protected (which I have credentials ), and search files on that server.. Is there a straight forward way to accomplish this?
A... | Logging into a server and parsing files on that server with Python | I would like to be able to use a Python script that I wrote to search files to login to an Ubuntu server that's password protected (which I have credentials ), and search files on that server.. Is there a straight forward way to accomplish this?
| [
"To login and run remote terminal commands through python, you should use either paramiko or pexpect. Pexpect is not touched very much by noah these days... I'm starting to wonder whether he is abandoning it.\nThe other way is to sftp the files from the remote server to your local machine... paramiko is useful for... | [
1
] | [] | [] | [
"http",
"python",
"session"
] | stackoverflow_0005845861_http_python_session.txt |
Q:
python for-loop slower each iteration
I am trying to optimize some python code (to speed up some matrix operations), my code is something similar to this one (my real dataset is also similar to 'gps'),
import numpy as np
gps = [np.random.rand(50,50) for i in xrange(1000)]
ips = np.zeros( (len(gps),len(gps)), dtype... | python for-loop slower each iteration | I am trying to optimize some python code (to speed up some matrix operations), my code is something similar to this one (my real dataset is also similar to 'gps'),
import numpy as np
gps = [np.random.rand(50,50) for i in xrange(1000)]
ips = np.zeros( (len(gps),len(gps)), dtype='float32')
for i in xrange(len(gps)):
f... | [
"At the risk of stating the obvious, the number of executions of the inner loop will grow each time you complete an execution of the outer loop. When i is 0, the inner loop will only be executed once, but when i is 100, it will be executed 101 times. Could this explain your observations, or do you mean that each ... | [
4,
2
] | [] | [] | [
"for_loop",
"memory_bandwidth",
"performance",
"python"
] | stackoverflow_0005845826_for_loop_memory_bandwidth_performance_python.txt |
Q:
get the list of metadata associated to a file using python in Ubuntu
I'm trying to get the list of meta-data associated to a file, using python in Ubuntu.
Without using python, the command "extract" works very well but I don't know how to use it with python, I always get a message saying that "extract" is not def... | get the list of metadata associated to a file using python in Ubuntu | I'm trying to get the list of meta-data associated to a file, using python in Ubuntu.
Without using python, the command "extract" works very well but I don't know how to use it with python, I always get a message saying that "extract" is not defined.
| [
"I assume you're asking about the metadata that appears in the Windows \"Properties\" dialogue under the \"Summary\" tab. (If not, just disregard this.) Here's how I managed it.\n\nDownload and install Python win32 extensions. This will put win32, win32com, etc. into your Python[ver]/Lib/site-packages folder. T... | [
3,
1,
0
] | [] | [] | [
"python",
"ubuntu"
] | stackoverflow_0004584038_python_ubuntu.txt |
Q:
python variables
I have a simple question. i read a string from file and stored in in a list (named:formula). Then i stored (formula) in another variable (fstore = formula) to keep it for later. Then i made changes to formula, and as it turns out, fstore is changing as well. Why does this keep happening? I want fs... | python variables | I have a simple question. i read a string from file and stored in in a list (named:formula). Then i stored (formula) in another variable (fstore = formula) to keep it for later. Then i made changes to formula, and as it turns out, fstore is changing as well. Why does this keep happening? I want fstore to remain constan... | [
"The important distinction here is between mutable and immutable data types. In python, a list is mutable, while a tuple is immutable. This means that when you \"change\" the value of a tuple like this:\nt1 = (1, 2, 3) # t1 points to (1, 2, 3)\nt2 = t1 # t2 points to the same tuple as t1\nt1 = (2, 3,... | [
5,
4
] | [] | [] | [
"python",
"variable_assignment",
"variables"
] | stackoverflow_0005845935_python_variable_assignment_variables.txt |
Q:
What happens when when the start value of a python substring command is negative?
Example:
mystring = " ... some string ... "
mystring[-50:40] # <--- what does this mean?
A:
Negative indexes in a slice count from the right. Yes, even for the start value.
>>> '12345'[-4:4]
'234'
A:
Negative indexes in general ... | What happens when when the start value of a python substring command is negative? | Example:
mystring = " ... some string ... "
mystring[-50:40] # <--- what does this mean?
| [
"Negative indexes in a slice count from the right. Yes, even for the start value.\n>>> '12345'[-4:4]\n'234'\n\n",
"Negative indexes in general have an implied len(of_this_object) added to the negative index. Doesn't matter if they are start, end or plain indexes.\nExample:\nsome_object[10:-20]\n\nis interpreted a... | [
7,
1
] | [] | [] | [
"python"
] | stackoverflow_0005815296_python.txt |
Q:
Random Walk Problem(Escape Recursion)
As practice, and as a precursor to a more complex, larger project I have in mind, I have created a random walk script using the Turtle module. I realize that there are simpler ways to do the random walk without having to find the neighboring coordinates, but as far as I can te... | Random Walk Problem(Escape Recursion) | As practice, and as a precursor to a more complex, larger project I have in mind, I have created a random walk script using the Turtle module. I realize that there are simpler ways to do the random walk without having to find the neighboring coordinates, but as far as I can tell this is necessary for the larger impleme... | [
"If your random walk finds that it has visited every adjacent cell, it would loop forever. Since you're using recursion it quickly exceeds the maximum recursion limit. \nI'm sure this could be written in an OOP way, but the problems are more in your use of recursion than whether the cell class is useful. For exam... | [
2
] | [] | [] | [
"oop",
"python",
"random",
"recursion"
] | stackoverflow_0005845925_oop_python_random_recursion.txt |
Q:
How to get gobject.idle_add() to pass a parameter by reference?
I have two threads in my PyGTK app:
the main thread which runs the GTK loop and does all the GUI stuff
another thread which handles network requests, etc.
I need to have the second thread get some information from the first thread, so I call:
variab... | How to get gobject.idle_add() to pass a parameter by reference? | I have two threads in my PyGTK app:
the main thread which runs the GTK loop and does all the GUI stuff
another thread which handles network requests, etc.
I need to have the second thread get some information from the first thread, so I call:
variable = None
gobject.idle_add( function_in_main_thread, variable )
In t... | [
"In Python, assignment always creates the name in the current scope. The name you pass is indeed a reference to the variable you've created, but the assignment operator will try to find it in the current scope and, if it's not there, create it. \n>>> def assign_to(name, value):\n... name = value\n...\n>>> name ... | [
3
] | [] | [] | [
"multithreading",
"pygtk",
"python",
"variables"
] | stackoverflow_0005845896_multithreading_pygtk_python_variables.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.