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:
Python: Lazy String Decoding
I'm writing a parser, and there is LOTS of text to decode but most of my users will only care about a few fields from all the data. So I only want to do the decoding when a user actually uses some of the data. Is this a good way to do it?
class LazyString(str):
def __init__(self, v... | Python: Lazy String Decoding | I'm writing a parser, and there is LOTS of text to decode but most of my users will only care about a few fields from all the data. So I only want to do the decoding when a user actually uses some of the data. Is this a good way to do it?
class LazyString(str):
def __init__(self, v) :
self.value = v
def... | [
"I'm not sure how implementing a string subclass is of much benefit here. It seems to me that if you're processing a stream containing petabytes of data, whenever you've created an object that you don't need to you've already lost the game. Your first priority should be to ignore as much input as you possibly can... | [
3,
1,
0,
0,
0
] | [] | [] | [
"lazy_evaluation",
"python"
] | stackoverflow_0001656048_lazy_evaluation_python.txt |
Q:
web2py - display a SQL query in a form
i have a SQL query
family_members = db(\
db.member.parent_membership_id==parent_id.membership_id\
).select(\
db.member.first_name, db.member.parent_membership_id)
I want to display "family_members" as a table in my form.
How can i do this?
A:
In view:
{{=family... | web2py - display a SQL query in a form | i have a SQL query
family_members = db(\
db.member.parent_membership_id==parent_id.membership_id\
).select(\
db.member.first_name, db.member.parent_membership_id)
I want to display "family_members" as a table in my form.
How can i do this?
| [
"In view:\n{{=family_members}}\n\n",
"You can follow the example I've shown you in a previous question.\nMake sure to also check the documentation on the web2py website, seeing the work you are doing with this framework I would recommend to buy the web2py official manual which is really not expensive and will sav... | [
3,
2
] | [] | [] | [
"python",
"web2py"
] | stackoverflow_0001657480_python_web2py.txt |
Q:
A case of outwardly equal lists of sets behaving differently under Python 2.5 (I think ...)
Four years ago I wrote a Sudoku puzzle solver, and now I'm trying to understand how it works so that I can reuse parts of it for a KenKen puzzle solver. I thought I'd better compactify loops into list comprehensions and pi... | A case of outwardly equal lists of sets behaving differently under Python 2.5 (I think ...) | Four years ago I wrote a Sudoku puzzle solver, and now I'm trying to understand how it works so that I can reuse parts of it for a KenKen puzzle solver. I thought I'd better compactify loops into list comprehensions and pick more self-explanatory names for variables.
There's a class Puz which contains the input puzz... | [
"self.W3 as you've coded it contains many references to the same set object -- as soon as you call any mutating method on one of those references, you've changed all the others. You need to ensure W3_fill_func returns independent copies of the set of interest, just like all others do, e.g. by changing its return t... | [
2
] | [] | [] | [
"python",
"python_2.5",
"set"
] | stackoverflow_0001659039_python_python_2.5_set.txt |
Q:
Django unique_together and flagging objects as "deleted"
I'm implementing the first option discussed in "Marking for deletion in Django", that is, when an object is no longer active, I set a boolean to mark it as inactive.
The specific reason I'm using this method is that although the object is no longer in active... | Django unique_together and flagging objects as "deleted" | I'm implementing the first option discussed in "Marking for deletion in Django", that is, when an object is no longer active, I set a boolean to mark it as inactive.
The specific reason I'm using this method is that although the object is no longer in active use, it may still be referenced and displayed in various reco... | [
"You could have a unique constraint:\nclass Meta:\n unique_together = ( ('name', 'active'),)\n\nHowever, that means you can only have one active and one inactive object with the same name.\nIf you make active a NullBooleanField, then you can have NULL for active, and have (IIRC) a limitless number of objects th... | [
4,
0
] | [] | [] | [
"database_design",
"django",
"django_models",
"python"
] | stackoverflow_0001658945_database_design_django_django_models_python.txt |
Q:
How to run code on Pylons startup
I have a Python 2.6 web app built on Pylons 0.9.7. The code in my controller only runs the first time a client requests it, which is fair enough, but is there any way I can run some code as soon as the server starts and is ready to accept requests, without waiting until a request ... | How to run code on Pylons startup | I have a Python 2.6 web app built on Pylons 0.9.7. The code in my controller only runs the first time a client requests it, which is fair enough, but is there any way I can run some code as soon as the server starts and is ready to accept requests, without waiting until a request is actually received?
| [
"It's an environment setting, if that's what you're asking.\nSpecifically: lib/app_globals, modify _ _ init _ _ (). (Ignore the spaces there, silly emboldening function!)\nSee: http://pylonshq.com/docs/en/0.9.7/configuration/#environment\nAlternative methods are getting your helper script (that which is launching ... | [
2
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0001658986_pylons_python.txt |
Q:
sqlalchemy: AttributeError: 'tuple' object has no attribute 'insert'
I was playing around making a simple haiku site using sqlalchemy and pylons. It basically takes a haiku, writes it to a database, and displays the haiku. The problem appears when I get the data from the form and try and write it to a database, Py... | sqlalchemy: AttributeError: 'tuple' object has no attribute 'insert' | I was playing around making a simple haiku site using sqlalchemy and pylons. It basically takes a haiku, writes it to a database, and displays the haiku. The problem appears when I get the data from the form and try and write it to a database, Pylons give me this error: AttributeError: 'tuple' object has no attribute '... | [
"Well, it looks like you're creating haiku_table and not doing anything else to it before trying to use the .insert function which obviously is not part of a tuple\nLooks like when you create a table with SQLAlchemy, you want the format:\nhaiku_table = Table('haiku', metadata,\n schema.Column('title', typ... | [
1
] | [] | [] | [
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0001659160_pylons_python_sqlalchemy.txt |
Q:
MacPython: programmatically finding all serial ports
I am looking for a solution to programmatically return all available serial ports with python.
At the moment I am entering ls /dev/tty.* or ls /dev/cu.* into the terminal to list ports and hardcoding them into the pyserial class.
A:
You could do something like... | MacPython: programmatically finding all serial ports | I am looking for a solution to programmatically return all available serial ports with python.
At the moment I am entering ls /dev/tty.* or ls /dev/cu.* into the terminal to list ports and hardcoding them into the pyserial class.
| [
"You could do something like this:\nimport glob\ndef scan():\n return glob.glob('/dev/tty*') + glob.glob('/dev/cu*')\n\nfor port in scan():\n # do something to check this port is open.\n\nThen, take a look at pyserial for some good utility functions to check if a port is open and so forth.\n",
"What about ju... | [
6,
1
] | [] | [] | [
"macos",
"python",
"serial_port"
] | stackoverflow_0001659283_macos_python_serial_port.txt |
Q:
Creating a shared library in MATLAB
A researcher has created a small simulation in MATLAB and we want to make it accessible to others. My plan is to take the simulation, clean up a few things and turn it into a set of functions. Then I plan to compile it into a C library and use SWIG to create a Python wrapper. At... | Creating a shared library in MATLAB | A researcher has created a small simulation in MATLAB and we want to make it accessible to others. My plan is to take the simulation, clean up a few things and turn it into a set of functions. Then I plan to compile it into a C library and use SWIG to create a Python wrapper. At that point, I should be able to call the... | [
"One thing to remember is that the MATLAB compiler does not actually compile the MATLAB code into native machine instructions. It simply wraps it into a stand-alone executable or a library with its own runtime engine that runs it. You would be able to run your code without MATLAB installed, and you would be able ... | [
5,
3,
2,
1
] | [] | [] | [
"c",
"matlab",
"python"
] | stackoverflow_0000005136_c_matlab_python.txt |
Q:
Inheriting directly from a built-in type versus its wrapper class in Python
I'm currently reading Dive Into Python by Mark Pilgrim, and have gotten to the section on inheritance. In section 5.5, Pilgrim mentions the differences between inheriting from the wrapper class UserDict vs inheriting from the built-in dic... | Inheriting directly from a built-in type versus its wrapper class in Python | I'm currently reading Dive Into Python by Mark Pilgrim, and have gotten to the section on inheritance. In section 5.5, Pilgrim mentions the differences between inheriting from the wrapper class UserDict vs inheriting from the built-in dict type.
I'm having trouble understanding why anyone would even bother with the wr... | [
"You're right:\n\nThe need for this class has been\n largely supplanted by the ability to\n subclass directly from dict (a feature\n that became available starting with\n Python version 2.2). Prior to the\n introduction of dict, the UserDict\n class was used to create\n dictionary-like sub-classes that\n ob... | [
3,
3,
1
] | [] | [] | [
"built_in",
"inheritance",
"python",
"types",
"wrapper"
] | stackoverflow_0001659337_built_in_inheritance_python_types_wrapper.txt |
Q:
**kwargs search mechanism in an object (python)
Want to be able to provide a search interface for a collection of objects to be used by passing a list of keyword arguments like so:
playerID = players.search(nameFirst='ichiro', nameLast='suzuki')
Where players.search is defined like so:
def search(self, **args):
... | **kwargs search mechanism in an object (python) | Want to be able to provide a search interface for a collection of objects to be used by passing a list of keyword arguments like so:
playerID = players.search(nameFirst='ichiro', nameLast='suzuki')
Where players.search is defined like so:
def search(self, **args):
ret = []
for playerID, player in self.iteritem... | [
"You should be able to change it to a list comprehension with the all builtin, which returns True iff all the elements in its argument are true (or if the iterable is empty). Something like this should do the trick:\nfor playerID, player in self.iteritems():\n if all(getattr(player, key) == value for key, value... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0001659418_python.txt |
Q:
python executing existent (&big) c++ code
I have a program in C++ that uses the cryptopp library to decrypt/encrypt messages.
It offers two interface methods encrypt & decrypt that receive a string and operate on it through cryptopp methods.
Is there some way to use both methods in Python without manually wrapping... | python executing existent (&big) c++ code | I have a program in C++ that uses the cryptopp library to decrypt/encrypt messages.
It offers two interface methods encrypt & decrypt that receive a string and operate on it through cryptopp methods.
Is there some way to use both methods in Python without manually wrapping all the cryptopp & files included?
Example:
im... | [
"If you can make a DLL from that C++ code, exposing those two methods (ideally as \"extern C\", that makes all interfacing tasks so much simpler), ctypes can be the answer, not requiring any third party tool or extension. Otherwise, it's your choice between cython, good old SWIG, SIP, Boost, ... -- many, many such... | [
6,
4
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0001659159_c++_python.txt |
Q:
Python base class method call: unexpected behavior
Why does str(A()) seemingly call A.__repr__() and not dict.__str__() in the example below?
class A(dict):
def __repr__(self):
return 'repr(A)'
def __str__(self):
return dict.__str__(self)
class B(dict):
def __str__(self):
retur... | Python base class method call: unexpected behavior | Why does str(A()) seemingly call A.__repr__() and not dict.__str__() in the example below?
class A(dict):
def __repr__(self):
return 'repr(A)'
def __str__(self):
return dict.__str__(self)
class B(dict):
def __str__(self):
return dict.__str__(self)
print 'call: repr(A) expect: repr... | [
"str(A()) does call __str__, in turn calling dict.__str__(). \nIt is dict.__str__() that returns the value repr(A).\n",
"I have modified the code to clear things out:\nclass A(dict):\n def __repr__(self):\n print \"repr of A called\",\n return 'repr(A)'\n def __str__(self):\n print \"str of A c... | [
9,
3,
2
] | [] | [] | [
"dictionary",
"inheritance",
"python"
] | stackoverflow_0000780670_dictionary_inheritance_python.txt |
Q:
Why is Python a favourite among people working in animation industry?
What is that needs to be coded in Python instead of C/C++ etc? I know its advantages etc. I want to know why exactly makes Python The language for people in this industry?
A:
Perhaps that's because it's a scripting language for Blender?
A:
I... | Why is Python a favourite among people working in animation industry? | What is that needs to be coded in Python instead of C/C++ etc? I know its advantages etc. I want to know why exactly makes Python The language for people in this industry?
| [
"Perhaps that's because it's a scripting language for Blender?\n",
"I work in this industry, and here's what I've observed:\n\nIt's a nice, tidy language that's not hard to pick up. You don't have to be a language guru to use it.\nIt embeds nicely in C/C++ applications.\nIt has data types, so numeric operations ... | [
6,
6,
4,
3,
2,
1,
1
] | [] | [] | [
"animation",
"oop",
"python"
] | stackoverflow_0001659620_animation_oop_python.txt |
Q:
Python socket client to a Java socket server
I have a Java socket server that is expecting exactly n bytes from some port. I want to write a Python clients that just sends bytes on some port to the Java server.
Since Python does not have primitives, I'm not sure to send exactly n bytes. Any suggestions?
More detai... | Python socket client to a Java socket server | I have a Java socket server that is expecting exactly n bytes from some port. I want to write a Python clients that just sends bytes on some port to the Java server.
Since Python does not have primitives, I'm not sure to send exactly n bytes. Any suggestions?
More details:
I have a Java DatagramSocket that takes in n b... | [
"somesocket.send takes a byte-string argument s -- just ensure that len(s) == n, and you will be sending exacty n bytes. What do \"primitives\" have to do with it?!\nTo turn arbitrary bunches of data into byte strings (and back), see the struct module in Python's standard library (for the specific but frequent cas... | [
1,
1,
0
] | [] | [] | [
"client",
"java",
"python",
"sockets"
] | stackoverflow_0001659584_client_java_python_sockets.txt |
Q:
What is the difference between BaseHTTPServer and SimpleHTTPServer? When and where to use them?
What is the difference between BaseHTTPServer and SimpleHTTPServer?
When and where should I use these?
A:
BaseHTTPServer is a HTTP server library. It understands the HTTP protocol and let your code handle requests. It... | What is the difference between BaseHTTPServer and SimpleHTTPServer? When and where to use them? | What is the difference between BaseHTTPServer and SimpleHTTPServer?
When and where should I use these?
| [
"BaseHTTPServer is a HTTP server library. It understands the HTTP protocol and let your code handle requests. It doesn't have any \"logic\" on it's own. SimpleHTTPServer is built on top of BaseHTTPServer and handles requests in a similar way normal HTTP servers do, i.e. serve files from the file-system. In most cas... | [
17
] | [] | [] | [
"basehttpserver",
"http",
"python",
"simplehttpserver"
] | stackoverflow_0001660045_basehttpserver_http_python_simplehttpserver.txt |
Q:
How to write a memory efficient Python program?
It's said that Python automatically manages memory. I'm confused because I have a Python program consistently uses more than 2GB of memory.
It's a simple multi-thread binary data downloader and unpacker.
def GetData(url):
req = urllib2.Request(url)
response =... | How to write a memory efficient Python program? | It's said that Python automatically manages memory. I'm confused because I have a Python program consistently uses more than 2GB of memory.
It's a simple multi-thread binary data downloader and unpacker.
def GetData(url):
req = urllib2.Request(url)
response = urllib2.urlopen(req)
data = response.read() // d... | [
"Like others have said, you need at least the following two changes:\n\nDo not create a huge list of integers with range\n# use xrange\nfor i in xrange(0, count):\n # UNPACK FIXED LENGTH OF BINARY DATA HERE\n yield (field1, field2, field3)\n\ndo not create a huge string as the full file body to be written at ... | [
11,
9,
6,
5,
2,
2,
2,
1
] | [] | [] | [
"memory",
"memory_management",
"python"
] | stackoverflow_0001659659_memory_memory_management_python.txt |
Q:
How can I pass a function's name to a function, and then call it?
How can I pass a functions name to a function and then call it?
Is it possible to do this without using getattribute?
How can I pass a class name to a function and then instantiate the class?
I know I just could pass the instance of the class direct... | How can I pass a function's name to a function, and then call it? |
How can I pass a functions name to a function and then call it?
Is it possible to do this without using getattribute?
How can I pass a class name to a function and then instantiate the class?
I know I just could pass the instance of the class directly to the function but it is important that the class gets instantiate... | [
"def outer(f): # any name: function, class, any callable\n return f() # class will be instantiated within the scope of the function\n\n",
"namespace = globals()\nresult = namespace[func_name]()\ninstance = namespace[class_name](*some_args)\n\nYou can use your own dictionary (namespace) instead... | [
5,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001660351_python.txt |
Q:
module to abstract limitations of GQL
I am after a Python module for Google App Engine that abstracts away limitations of the GQL.
Specifically I want to store big files (> 1MB) and retrieve all records for a model (> 1000). I have my own code that handles this at present but would prefer to build on existing work... | module to abstract limitations of GQL | I am after a Python module for Google App Engine that abstracts away limitations of the GQL.
Specifically I want to store big files (> 1MB) and retrieve all records for a model (> 1000). I have my own code that handles this at present but would prefer to build on existing work, if available.
Thanks
| [
"I'm not aware of any libraries that do that. You may want to reconsider what you're doing, at least in terms of retrieving more than 1000 results - those operations are not available because they're expensive, and needing to evade them is usually (though not always) a sign that you need to rearchitect your app to ... | [
1
] | [] | [] | [
"google_app_engine",
"gql",
"python"
] | stackoverflow_0001658829_google_app_engine_gql_python.txt |
Q:
Designing the storage for a very large game world
I'm starting up game programming again. 10 years ago I was making games in qbasic and I havn't done any game programming since, so I am quite rusty. I have been programming all the time though, I am web developer/DBA/admin now. I have several questions, but I'm goi... | Designing the storage for a very large game world | I'm starting up game programming again. 10 years ago I was making games in qbasic and I havn't done any game programming since, so I am quite rusty. I have been programming all the time though, I am web developer/DBA/admin now. I have several questions, but I'm going to limit it to one per post.
The game I am working o... | [
"Don't mess with relational databases unless you're forced to use them by external factors.\nLook at Python's pickle, shelve.\nShelve is fast and scales well. It eliminates messy conversion between Python and non-Python representation.\n\nEdit.\nMore important advice. Do not get bogged down in technology choices.... | [
11,
3,
1
] | [] | [] | [
"python",
"python_3.x",
"python_stackless",
"sqlite"
] | stackoverflow_0001650627_python_python_3.x_python_stackless_sqlite.txt |
Q:
TypeError: cannot concatenate 'str' and 'instance' objects (python urllib)
Writing a python program, and I came up with this error while using the urllib.urlopen function.
Traceback (most recent call last):
File "ChurchScraper.py", line 58, in <module>
html = GetAllChurchPages()
File "ChurchScraper.py", line 48, i... | TypeError: cannot concatenate 'str' and 'instance' objects (python urllib) | Writing a python program, and I came up with this error while using the urllib.urlopen function.
Traceback (most recent call last):
File "ChurchScraper.py", line 58, in <module>
html = GetAllChurchPages()
File "ChurchScraper.py", line 48, in GetAllChurchPages
CPs = CPs + urllib.urlopen(url)
TypeError: cannot concatenat... | [
"urlopen(url) returns a file-like object. To obtain the string contents, try\nCPs = CPs + urllib.urlopen(url).read()\n\n",
"urllib.urllopen doesn't return a string, it returns an object\ndoc\nIf all went well, a file-like object is returned.\n\n",
"The problem is in this line: CPs = CPs + urllib.urlopen(url) I ... | [
6,
2,
1,
0
] | [] | [] | [
"python",
"urllib"
] | stackoverflow_0001660954_python_urllib.txt |
Q:
least square solution to camera matrix [numpy]
I would like to use use numpy's least square algorithm to solve for a camera matrix from 6 known 3D -> 2D point correspondence.
I have been using this website as a reference:
http://homepages.inf.ed.ac.uk/rbf/CVonline/LOCAL_COPIES/OWENS/LECT9/node4.html
Currently my c... | least square solution to camera matrix [numpy] | I would like to use use numpy's least square algorithm to solve for a camera matrix from 6 known 3D -> 2D point correspondence.
I have been using this website as a reference:
http://homepages.inf.ed.ac.uk/rbf/CVonline/LOCAL_COPIES/OWENS/LECT9/node4.html
Currently my camera matrix seems to have very small values:
[[ -1.... | [
"\nI need to get scipy installed properly\n\nJust a note for installing scipy, ubuntu distributions since 8.04 have had a broken scipy build. That has been taken care of in the latest 9.10 beta build. You could build scipy from scratch, but it isn't in general an easy thing to do. Just a heads up because it took so... | [
2,
1,
0
] | [] | [] | [
"computer_vision",
"numpy",
"python"
] | stackoverflow_0001634555_computer_vision_numpy_python.txt |
Q:
Prototyping with Python code before compiling
I have been mulling over writing a peak-fitting library for a while. I know Python fairly well and plan on implementing everything in Python to begin with but envisage that I may have to re-implement some core routines in a compiled language eventually.
IIRC, one of Py... | Prototyping with Python code before compiling | I have been mulling over writing a peak-fitting library for a while. I know Python fairly well and plan on implementing everything in Python to begin with but envisage that I may have to re-implement some core routines in a compiled language eventually.
IIRC, one of Python's original remits was as a prototyping languag... | [
"Finally a question that I can really put a value answer to :). \nI have investigated f2py, boost.python, swig, cython and pyrex for my work (PhD in optical measurement techniques). I used swig extensively, boost.python some and pyrex and cython a lot. I also used ctypes. This is my breakdown:\nDisclaimer: This is ... | [
36,
10,
6,
4,
1,
0,
0
] | [] | [] | [
"ctypes",
"prototyping",
"python",
"python_sip",
"swig"
] | stackoverflow_0000016067_ctypes_prototyping_python_python_sip_swig.txt |
Q:
Why does my Python daemon hog all my CPU while sleeping?
I'm using this recipe: http://code.activestate.com/recipes/278731/ on an Ubuntu server.
I make a daemon instance like this:
class MyDaemon(Daemon):
def run(self):
while True:
try:
do_my_data_processing()
... | Why does my Python daemon hog all my CPU while sleeping? | I'm using this recipe: http://code.activestate.com/recipes/278731/ on an Ubuntu server.
I make a daemon instance like this:
class MyDaemon(Daemon):
def run(self):
while True:
try:
do_my_data_processing()
except MySQLdb.OperationalError:
# Sleep a... | [
"The posted code looks correct. Your error must be somewhere else. Put a print statement into the loop to make sure that it does sleep.\n",
"Turns out the daemon wasn't sleeping. It was looping without sleeping 30 seconds between every turn. Thanks Aaron.\nI fixed it by changing my code to this:\nclass MyDaemon(D... | [
3,
0
] | [] | [] | [
"cpu",
"daemon",
"python"
] | stackoverflow_0001661210_cpu_daemon_python.txt |
Q:
Data Structure for storing a sorting field to efficiently allow modifications
I'm using Django and PostgreSQL, but I'm not absolutely tied to the Django ORM if there's a better way to do this with raw SQL or database specific operations.
I've got a model that needs sequential ordering. Lookup operations will gener... | Data Structure for storing a sorting field to efficiently allow modifications | I'm using Django and PostgreSQL, but I'm not absolutely tied to the Django ORM if there's a better way to do this with raw SQL or database specific operations.
I've got a model that needs sequential ordering. Lookup operations will generally retrieve the entire list in order. The most common operation on this data is t... | [
"Prefered solutions:\nA linked list would be the usual way to achieve this. A query to return the items in order is trivial in Oracle, but Im not sure how you would do it in PostreSQL.\nAnother option would be to implement this using the ltree module for postgresql.\nLess graceful (and write-heavy) solution:\nStart... | [
6,
4,
1,
1,
1
] | [] | [] | [
"data_structures",
"database",
"django",
"python",
"sorting"
] | stackoverflow_0001640664_data_structures_database_django_python_sorting.txt |
Q:
App Engine: What is the fastest way to check if my datastore query returns any result?
I like to check if there is any result for my datastore query in the Google App Engine Datastore. This is my query:
users = User.all()
users.filter("hash =", current_user_hash)
What is the fastest and most elegant way to check ... | App Engine: What is the fastest way to check if my datastore query returns any result? | I like to check if there is any result for my datastore query in the Google App Engine Datastore. This is my query:
users = User.all()
users.filter("hash =", current_user_hash)
What is the fastest and most elegant way to check if my query returns any result?
PS: I know a way to do so, but I'm very unsure if it is very... | [
"If you also need to fetch the results, the most efficient way is to fetch the results with .fetch(), and then check if the list is nonempty. If you don't actually need the results, call .count(1).\nWhat you shouldn't do is call .count(1) if you also need the results - this'll require executing the query twice.\n",... | [
4,
2
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0001661421_google_app_engine_google_cloud_datastore_python.txt |
Q:
matplotlib for R user?
I regularly make figures (the exploratory data analysis type) in R. I also program in Python and was wondering if there are features or concepts in matplotlib that would be worth learning. For instance, I am quite happy with R - but its image() function will produce large files with pixelate... | matplotlib for R user? | I regularly make figures (the exploratory data analysis type) in R. I also program in Python and was wondering if there are features or concepts in matplotlib that would be worth learning. For instance, I am quite happy with R - but its image() function will produce large files with pixelated output, whereas Matlab's e... | [
"This is a tough one to answer. \nI recently switched some of my graphing workload from R to matplotlib. In my humble opinion, I find matplotlib's graphs to be prettier (better default colors, they look crisper and more modern). I also think matplotlib renders PNGs a whole lot better.\nThe real motivation for me... | [
13,
4
] | [] | [] | [
"data_visualization",
"matplotlib",
"python",
"r",
"scipy"
] | stackoverflow_0001661479_data_visualization_matplotlib_python_r_scipy.txt |
Q:
Creating an Infographic In Python
I want to create a simple infographic in python. Matplotlib seems to have a lot of features but nothing that covers off my simple heatmap grid example.
The infographic is a simple 5 x 5 grid with numbers inside ranging from 0 to 1. The grid squares would then be coloured in 0=whit... | Creating an Infographic In Python | I want to create a simple infographic in python. Matplotlib seems to have a lot of features but nothing that covers off my simple heatmap grid example.
The infographic is a simple 5 x 5 grid with numbers inside ranging from 0 to 1. The grid squares would then be coloured in 0=white 1=blue 0.5 being a pale blue.
Matplot... | [
"It depends what you need to do with the graph once you have it, Matplotlib allows you to interactively show the graph on the screen, save it in either vector, pdf or bitmap format, and more.\nIf you opt for this framework, imshow will do what you need, here is an example:\n# Just some data to test:\nfrom random im... | [
4,
2,
2
] | [] | [] | [
"charts",
"grid",
"heatmap",
"matplotlib",
"python"
] | stackoverflow_0001661565_charts_grid_heatmap_matplotlib_python.txt |
Q:
How to generate a choicelist from all ImageSpecs
I want to generate a choicelist for all specs that inherit from imagekit.specs.ImageSpec.
The idea is to allow users of the admin interface to select an ImageSpec to add to a picture.
i.e:
class Display(ImageSpec):
pre_cache = True
increment_count = True
... | How to generate a choicelist from all ImageSpecs | I want to generate a choicelist for all specs that inherit from imagekit.specs.ImageSpec.
The idea is to allow users of the admin interface to select an ImageSpec to add to a picture.
i.e:
class Display(ImageSpec):
pre_cache = True
increment_count = True
processors = [ResizeDisplay,]
class SingleDisplay(Im... | [
"Well, something like the following will get you a list of all the ImageSpec subclasses defined in the file:\ndef subclassfilter(x, baseclass):\n return x is not baseclass and isinstance(x, type) and issubclass(x, baseclass)\n\nsubclasses = [c for c in locals().values() if subclassfilter(c, ImageSpec)]\n\nYou co... | [
2
] | [] | [] | [
"django",
"django_imagekit",
"imagekit",
"python"
] | stackoverflow_0001662520_django_django_imagekit_imagekit_python.txt |
Q:
read string backwards and terminate at first '/'
I want to extract just the file name portion of a path. My code below works, but I'd like to know what the better (pythonic) way of doing this is.
filename = ''
tmppath = '/dir1/dir2/dir3/file.exe'
for i in reversed(tmppath):
if i != '/':
... | read string backwards and terminate at first '/' | I want to extract just the file name portion of a path. My code below works, but I'd like to know what the better (pythonic) way of doing this is.
filename = ''
tmppath = '/dir1/dir2/dir3/file.exe'
for i in reversed(tmppath):
if i != '/':
filename += str(i)
else:
break
... | [
"Try:\n#!/usr/bin/python\nimport os.path\npath = '/dir1/dir2/dir3/file.exe'\nname = os.path.basename(path)\nprint name\n\n",
"you'd be better off using standard library for this:\n>>> tmppath = '/dir1/dir2/dir3/file.exe'\n>>> import os.path\n>>> os.path.basename(tmppath)\n'file.exe'\n\n",
"Use os.path.basename(... | [
12,
4,
2,
1,
0
] | [] | [] | [
"path",
"python"
] | stackoverflow_0001660059_path_python.txt |
Q:
Is there a "do ... until" in Python?
Is there a
do until x:
...
in Python, or a nice way to implement such a looping construct?
A:
There is no do-while loop in Python.
This is a similar construct, taken from the link above.
while True:
do_something()
if condition():
break
A:
I prefer to... | Is there a "do ... until" in Python? | Is there a
do until x:
...
in Python, or a nice way to implement such a looping construct?
| [
"There is no do-while loop in Python.\nThis is a similar construct, taken from the link above.\n while True:\n do_something()\n if condition():\n break\n\n",
"I prefer to use a looping variable, as it tends to read a bit nicer than just \"while 1:\", and no ugly-looking break statement:\nfinished =... | [
314,
45,
28,
11
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0001662161_loops_python.txt |
Q:
Unable to get results when passing a string via parameter substitution in gql query
I am able to properly pass a string variable to the gqlquery through parameter substitution, here's the code i've tried to use;
user_name = self.request.get('username') #retrieved from UI
p = models.UserDetails.all().filter('user_n... | Unable to get results when passing a string via parameter substitution in gql query | I am able to properly pass a string variable to the gqlquery through parameter substitution, here's the code i've tried to use;
user_name = self.request.get('username') #retrieved from UI
p = models.UserDetails.all().filter('user_name = ', user_name).fetch(1)
I don't get any results and the query fails silently. But w... | [
"Have you tried filter('user_name = ', str(user_name)) ?\nI supose you are sure user_name has the expected content.\n",
"I think I've got it, I tried using this,\np = models.UserDetails.gql('WHERE user_name = :uname', uname = user_name).fetch(1)\n\nand I got the expected resultset. I wonder why other formats have... | [
0,
0,
0
] | [] | [] | [
"google_app_engine",
"gql",
"gqlquery",
"python",
"string_substitution"
] | stackoverflow_0001660640_google_app_engine_gql_gqlquery_python_string_substitution.txt |
Q:
Python on windows7 intel 64bit
I've been messing around with Python over the weekend and find myself pretty much back at where I started.
I've specifically been having issues with easy_install and nltk giving me errors about not finding packages, etc.
I've tried both Python 2.6 and Python 3.1.
I think part of t... | Python on windows7 intel 64bit | I've been messing around with Python over the weekend and find myself pretty much back at where I started.
I've specifically been having issues with easy_install and nltk giving me errors about not finding packages, etc.
I've tried both Python 2.6 and Python 3.1.
I think part of the problem may be that I'm running w... | [
"The most popular 64-bit mode for \"86-oid\" processor is commonly known as AMD64 because AMD first came up with it (Intel at that time was pushing Itanium instead, and that didn't really catch fire -- it's still around but I don't even know if Win7 supports it); Intel later had to imitate that mode to get into the... | [
13
] | [] | [] | [
"installation",
"python"
] | stackoverflow_0001662920_installation_python.txt |
Q:
Pexpect, running ssh-copy-id is hanging when trying to spawn a second process
I'm doing a Python script where I need to spawn several ssh-copy-id processes, and they need for me to type in a password, so i'm using PExpect.
I have basically this:
child = pexpect.spawn('command')
child.expect('password:')
child.send... | Pexpect, running ssh-copy-id is hanging when trying to spawn a second process | I'm doing a Python script where I need to spawn several ssh-copy-id processes, and they need for me to type in a password, so i'm using PExpect.
I have basically this:
child = pexpect.spawn('command')
child.expect('password:')
child.sendline('the password')
and then I want to spawn another process, I don't care about ... | [
"Fortunately or not, but OpenSSH client seems to be very picky about passwords and where they come from.\nYou may try using Paramiko Python SSH2 library. Here's a simple example how to use it with password authentication, then issue some shell commands (echo \"...\" >> $HOME/.ssh/authorized_keys being the simplest)... | [
3,
1,
0,
0
] | [] | [] | [
"pexpect",
"process",
"python"
] | stackoverflow_0000356830_pexpect_process_python.txt |
Q:
How do I loop through all levels of a data structure to extract all data when I don't know how many levels there will be?
I need to extract data from a structure and put it into a list, but I don't know how many levels the structure has.
For each level, I can call level.children(), if there are no levels below the... | How do I loop through all levels of a data structure to extract all data when I don't know how many levels there will be? | I need to extract data from a structure and put it into a list, but I don't know how many levels the structure has.
For each level, I can call level.children(), if there are no levels below the current one, it returns [], if there are, it returns [object, object, ...], on each of which I can call children() on again.
I... | [
"You're describing recursion, but I'm guessing there are better, ways, to, parse, XML.\n",
"The concept you're looking to use here is called \"Recursion\".\n"
] | [
10,
5
] | [] | [] | [
"data_structures",
"loops",
"python",
"xml"
] | stackoverflow_0001663077_data_structures_loops_python_xml.txt |
Q:
xml.etree.ElementTree equivalent in Java
I've been doing quite a bit of simple XML-processing in python and grown to like the ElementTree way of doing things.
Is there something similar and as easy to use in Java? I find the DOM model a bit cumbersome and find myself writing much more code than I would like to do... | xml.etree.ElementTree equivalent in Java | I've been doing quite a bit of simple XML-processing in python and grown to like the ElementTree way of doing things.
Is there something similar and as easy to use in Java? I find the DOM model a bit cumbersome and find myself writing much more code than I would like to do simple things.
Or am I asking the wrong thing... | [
"To be honest, all XML APIs in Java suck, you just can vary the level of suckage you push yourself into which may turn horrible/slow to manageable/decent to even suprisingly OK at times.\nThis all mostly stems from the fact that Java APIs try to be as W3C DOM compliant as possible, in fact Xerces (Java's current na... | [
6,
1,
1,
0
] | [] | [] | [
"java",
"python",
"xml"
] | stackoverflow_0001662375_java_python_xml.txt |
Q:
What may be the problem (Django views)...?
I am writing a GUI application using Django 1.1.1.
This is the views.py:
from django.http import HttpResponse
def mainpage(request):
f=open('pages/index.html','r').readlines()
out=''''''
for line in file:
out+=line
print out
return HttpRespon... | What may be the problem (Django views)...? | I am writing a GUI application using Django 1.1.1.
This is the views.py:
from django.http import HttpResponse
def mainpage(request):
f=open('pages/index.html','r').readlines()
out=''''''
for line in file:
out+=line
print out
return HttpResponse(out)
I am trying to load the contents of ind... | [
"If you require just simple output of html page, this can be achieved by simply putting following into urls.py:\n(r'^$', 'direct_to_template', {'template': 'index.html'})\n",
"For the root page don't use r'^/$', just r'^$', because this ^ means \"start of the string after domain AND SLASH\" (after 127.0.0.1/ if y... | [
3,
1,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001663082_django_python.txt |
Q:
mod_python req.subprocess_env not "seeing" PythonOptions
I'm having trouble getting an environmental variable out of apache config. (don't ask why it's being done this way, I didn't originally code it)
This is what I have in the apache config.
<Location "/var/www">
SetHandler python-program
PythonHandler m... | mod_python req.subprocess_env not "seeing" PythonOptions | I'm having trouble getting an environmental variable out of apache config. (don't ask why it's being done this way, I didn't originally code it)
This is what I have in the apache config.
<Location "/var/www">
SetHandler python-program
PythonHandler mod_python.publisher
PythonOption MYSQL_PWD ###########
... | [
"os.environ[\"MYSQL_PWD\"] = req.get_options()[\"MYSQL_PWD\"]\n\nSee docs on PythonOption for more details\n"
] | [
0
] | [] | [] | [
"apache2",
"debian",
"mod_python",
"python"
] | stackoverflow_0001663291_apache2_debian_mod_python_python.txt |
Q:
imagefield won't validate
I moved a site to a mediatemple server using python 2.3, now ImageField won't work in the admin. Upon saving, validation gives the "not valid image" error.
checked:
media_root and media_url are correct
PIL contains jpg support
upload folders set to 775
image is not corrupted
Ideas? Tha... | imagefield won't validate | I moved a site to a mediatemple server using python 2.3, now ImageField won't work in the admin. Upon saving, validation gives the "not valid image" error.
checked:
media_root and media_url are correct
PIL contains jpg support
upload folders set to 775
image is not corrupted
Ideas? Thanks.
| [
"If you read documentation here: http://docs.djangoproject.com/en/dev/intro/install/\nYou will find the answer. \n\nIt works with any Python version from\n 2.4 to 2.6!\n\nAnd :\n\nSet up a database\nIf you installed Python 2.5 or later,\n you can skip this step for now.\nIf not, or if you'd like to work with\n a... | [
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0001191487_django_django_models_python.txt |
Q:
Python, sending command to GPIB instrument
I need to send a command to a GPIB instrument and I can do it like this: power.write("volt 0.01").
This command sets the output of my power source to 0.01V, however, I'm trying to take an I-V curve and want to set the source to different values and take a measurement at e... | Python, sending command to GPIB instrument | I need to send a command to a GPIB instrument and I can do it like this: power.write("volt 0.01").
This command sets the output of my power source to 0.01V, however, I'm trying to take an I-V curve and want to set the source to different values and take a measurement at each value. I basically need some sort of loop to... | [
"Instead of power.write(\"volt k\"), use:\npower.write(\"volt \" + str(k))\n ^\n observe space here!\n\nIf you want to control the output precision, you can use the following:\npower.write(\"volt %0.2f\" % k)\n\nThat is, if k is 4.85866 then using %0.2f means volt 4.86 is sent to the device... | [
6,
3
] | [] | [] | [
"gpib",
"python",
"string_formatting"
] | stackoverflow_0001663763_gpib_python_string_formatting.txt |
Q:
Using Python to check words
I'm stuck on a simple problem. I've got a dictionary of words in the English language, and a sample text that is to be checked. I've got to check every word in the sample against the dictionary, and the code I'm using is wrong.
for word in checkList: # iterates through every word i... | Using Python to check words | I'm stuck on a simple problem. I've got a dictionary of words in the English language, and a sample text that is to be checked. I've got to check every word in the sample against the dictionary, and the code I'm using is wrong.
for word in checkList: # iterates through every word in the sample
if word not in r... | [
"The snippet you have is functional. See for example\n>>> refDict = {'alpha':1, 'bravo':2, 'charlie':3, 'delta':4}\n>>> s = 'he said bravo to charlie O\\'Brian and jack Alpha'\n>>> for word in s.split():\n... if word not in refDict:\n... print(repr(word)) # by temporarily using repr() we can see exactly\n... | [
6,
5,
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001663133_python.txt |
Q:
How to keep help strings the same when applying decorators?
How can I keep help strings in functions to be visible after applying a decorator?
Right now the doc string is (partially) replaced with that of the inner function of the decorator.
def deco(fn):
def x(*args, **kwargs):
return fn(*args, **kwar... | How to keep help strings the same when applying decorators? | How can I keep help strings in functions to be visible after applying a decorator?
Right now the doc string is (partially) replaced with that of the inner function of the decorator.
def deco(fn):
def x(*args, **kwargs):
return fn(*args, **kwargs)
x.func_doc = fn.func_doc
x.func_name = fn.func_name
... | [
"give the decorator module a peek. i believe it does exactly what you want.\nIn [1]: from decorator import decorator\nIn [2]: @decorator\n ...: def say_hello(f, *args, **kwargs):\n ...: print \"Hello!\"\n ...: return f(*args, **kwargs)\n ...: \nIn [3]: @say_hello\n ...: def double(x):\n ...: ... | [
5,
1
] | [] | [] | [
"decorator",
"documentation",
"python"
] | stackoverflow_0001663568_decorator_documentation_python.txt |
Q:
tokenizer errors with nltk
I'm very new to Python, and am trying to learn in conjunction with using nltk.
I've been following some examples and testing things out, but it seems I am very limited in what I can do due to errors being returned by python.
I know nltk is installed and importing fine, because this code... | tokenizer errors with nltk | I'm very new to Python, and am trying to learn in conjunction with using nltk.
I've been following some examples and testing things out, but it seems I am very limited in what I can do due to errors being returned by python.
I know nltk is installed and importing fine, because this code works
from nltk.sem import ch... | [
"Looks like the nltp package doesn't have a tokenizer package.\nA quick look on the NLTK website suggests that from nltp.tokenize import * is what you're after.\n",
"Adam's answer may well be correct for your immediate \"tokenizer\" problem. Here's some general advice:\nIt helps when one is in unfamiliar territor... | [
3,
0
] | [] | [] | [
"nltk",
"python"
] | stackoverflow_0001663762_nltk_python.txt |
Q:
What should I install in order to be able to use GTK in Python on Ubuntu?
In my source code I have:
import gtk
But when I run the script with python3 script.py command I get the following error. What package should I install to get it working?
Edit: my bad. here is the error:
ImportError: No module named gtk
Edi... | What should I install in order to be able to use GTK in Python on Ubuntu? | In my source code I have:
import gtk
But when I run the script with python3 script.py command I get the following error. What package should I install to get it working?
Edit: my bad. here is the error:
ImportError: No module named gtk
Edit2:
Thanks for the answer, kaizer.se. But I'm still getting an error messa... | [
"PyGtk doesn't support Python 3 yet. You might want to use Python 2.x and then you will need to install the python-gtk2 package.\n",
"There is no big difference between how Python 3 and Python 2.6 handle unicode and international text, technically. The biggest difference is what the classes are called and what th... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001663109_python.txt |
Q:
What does "evaluated only once" mean for chained comparisons in Python?
A friend brought this to my attention, and after I pointed out an oddity, we're both confused.
Python's docs, say, and have said since at least 2.5.1 (haven't checked further back:
Comparisons can be chained arbitrarily, e.g., x < y <= z is e... | What does "evaluated only once" mean for chained comparisons in Python? | A friend brought this to my attention, and after I pointed out an oddity, we're both confused.
Python's docs, say, and have said since at least 2.5.1 (haven't checked further back:
Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in b... | [
"The 'expression' y is evaluated once. I.e., in the following expression, the function is executed only one time.\n>>> def five():\n... print 'returning 5'\n... return 5\n... \n>>> 1 < five() <= 5\nreturning 5\nTrue\n\nAs opposed to:\n>>> 1 < five() and five() <= 5\nreturning 5\nreturning 5\nTrue\n\n",
"In ... | [
45,
8
] | [] | [] | [
"python"
] | stackoverflow_0001664292_python.txt |
Q:
How do you set the text direction for a TextTable Cell in OpenOffice?
I want to set the text direction for some cells in a TextTable so that they are vertical (i.e., the text is landscape instead of portrait).
You can do this in Writer by selecting the cell(s), and going to:
Table - Text Properties - Text Flow - T... | How do you set the text direction for a TextTable Cell in OpenOffice? | I want to set the text direction for some cells in a TextTable so that they are vertical (i.e., the text is landscape instead of portrait).
You can do this in Writer by selecting the cell(s), and going to:
Table - Text Properties - Text Flow - Text Direction
However, I cannot figure out how to do this through the API. ... | [
"I finally figured this out after all these months!\nYou have to set the \"WritingMode\" property for the cell. In C#:\nXCell cell = table.getCellByName(cellName);\n((XPropertySet)cell).setPropertyValue(\"WritingMode\", new Any((short) \nWritingMode.TB_RL));\n\nI haven't tried it in python yet, but I suppose it wou... | [
0
] | [] | [] | [
"c#",
"openoffice.org",
"openoffice_writer",
"python",
"uno"
] | stackoverflow_0000898739_c#_openoffice.org_openoffice_writer_python_uno.txt |
Q:
bencoding binary data in Java strings
I'm playing with bencoding and I would like to keep bencoded strings as Java strings, but they contain binary data, so blindly converting them to string will corrupt the data. What I am trying to accomplish is to have a conversion function that will keep the ASCII bytes as ASC... | bencoding binary data in Java strings | I'm playing with bencoding and I would like to keep bencoded strings as Java strings, but they contain binary data, so blindly converting them to string will corrupt the data. What I am trying to accomplish is to have a conversion function that will keep the ASCII bytes as ASCII and encode non-ASCII chars in a reversib... | [
"Bencoded strings are byte strings. You can attempt to decode a byte string to unicode codepoints in Java with String(byte[] bytes, Charset charset). Decoding with certain encodings such as ISO-8859-1 will always succeed, since any byte maps directly to a codepoint. With many of these encodings (including ISO-8859-... | [
2,
0
] | [] | [] | [
"encoding",
"java",
"python"
] | stackoverflow_0001664124_encoding_java_python.txt |
Q:
Parsing HTML generated from Legacy ASP Application to create ASP.NET 2.0 Pages
One of my friends is working on having a good solution to generate aspx pages, out of html pages generated from a legacy asp application.
The idea is to run the legacy app, capture html output, clean the html using some tool (say HtmlTi... | Parsing HTML generated from Legacy ASP Application to create ASP.NET 2.0 Pages | One of my friends is working on having a good solution to generate aspx pages, out of html pages generated from a legacy asp application.
The idea is to run the legacy app, capture html output, clean the html using some tool (say HtmlTidy) and parse it/transform it to aspx, (using Xslt or a custom tool) so that existi... | [
"Here's what you do.\n\nDefine what the legacy app is supposed to do. Write down the scenarios of getting pages, posting forms, navigating, etc.\nWrite unit test-like scripts for the various scenarios.\nUse the Python HTTP client library to exercise the legacy app in your various scripts.\nIf your scripts work, yo... | [
2,
0,
0
] | [] | [] | [
".net",
"c#",
"html",
"python"
] | stackoverflow_0000565264_.net_c#_html_python.txt |
Q:
Significant whitespace in C# like Python or Haskell?
I'm wondering if any other C# developers would find it an improvement to have a compiler directive for csc.exe to make whitespace significant a la Haskell or Python where the kinds of whitespace create code blocks.
While this would certainly be a massive departu... | Significant whitespace in C# like Python or Haskell? | I'm wondering if any other C# developers would find it an improvement to have a compiler directive for csc.exe to make whitespace significant a la Haskell or Python where the kinds of whitespace create code blocks.
While this would certainly be a massive departure from C-style languages, it seems to me that since C# is... | [
"If you want this syntax, why not just use IronPython or Boo instead of C#?\nIt seems better to implement a custom language for this, instead of trying to tweak C#. As you said, they all compile to the same IL, so there's no reason to change a good, clean working syntax to implement what would essentially be a new... | [
11,
3,
3,
2,
2,
1,
0,
0,
0
] | [] | [] | [
"c#",
"haskell",
"python"
] | stackoverflow_0001664394_c#_haskell_python.txt |
Q:
Python name grabber
if I have a string in the format of
(static string) name (different static string ) message (last static string)
(static string) name (different static string ) message (last static string)
(static string) name (different static string ) message (last static string)
(static string) name (differ... | Python name grabber | if I have a string in the format of
(static string) name (different static string ) message (last static string)
(static string) name (different static string ) message (last static string)
(static string) name (different static string ) message (last static string)
(static string) name (different static string ) messa... | [
">>> s=\"(static string) name (different static string ) message (last static string)\"\n>>> _,_,s=s.partition(\"(static string)\")\n>>> name,_,s=s.partition(\"(different static string )\")\n>>> message,_,s=s.partition(\"(last static string)\")\n>>> name\n' name '\n>>> message\n' message '\n\n",
"Expecting this s... | [
3,
0,
0,
0
] | [] | [] | [
"parsing",
"python",
"regex"
] | stackoverflow_0001659759_parsing_python_regex.txt |
Q:
secure and efficient file uploader
I am looking for a decent file uploader. I'm using django, but while i don't NEED a django file uploader, python is preferable. php would also be fine.
can anyone point me in the direction of a good file uploader which is secure and efficient?
EDIT: I need the server-side handler... | secure and efficient file uploader | I am looking for a decent file uploader. I'm using django, but while i don't NEED a django file uploader, python is preferable. php would also be fine.
can anyone point me in the direction of a good file uploader which is secure and efficient?
EDIT: I need the server-side handler of file uploads.
| [
"I'm using uploadify which is an upload plugin for jQuery with a flash progress bar. I use some basic php for the upload script. It can be made as secure as you need with a little investigating the forum.\n",
"Agree with jeerose: Uploadify is a nice app.\nI've made a simple Django wrapper for it as well if you'r... | [
2,
2
] | [] | [] | [
"django",
"php",
"python",
"upload"
] | stackoverflow_0001664597_django_php_python_upload.txt |
Q:
Python string interning and substrings
Does python create a completely new string (copying the contents) when you do a substring operation like:
new_string = my_old_string[foo:bar]
Or does it use interning to point to the old data ?
As a clarification, I'm curious if the underlying character buffer is shared as i... | Python string interning and substrings | Does python create a completely new string (copying the contents) when you do a substring operation like:
new_string = my_old_string[foo:bar]
Or does it use interning to point to the old data ?
As a clarification, I'm curious if the underlying character buffer is shared as it is in Java. I realize that strings are imm... | [
"Examining the source reveals:\nWhen the slice indexes match the start and end of the original string, then the original string is returned.\nOtherwise, you get the result of the function PyString_FromStringAndSize, which takes the existing string object. This function returns an interned string in the case of a 0 ... | [
8,
8,
2,
0
] | [
"In Python, strings are immutable. That means that you will always get a copy on any slice, concatenate, or other operations.\nhttp://effbot.org/pyfaq/why-are-python-strings-immutable.htm is a nice explanation for some of the reasons behind immutable strings.\n"
] | [
-2
] | [
"python"
] | stackoverflow_0001664840_python.txt |
Q:
Is there a way to inspect the (differing) internal structures of Python objects that test as equal (==)?
Yesterday I asked ("A case of outwardly equal lists of sets behaving differently under Python 2.5 (I think …)") why list W constructed as follows:
r_dim_1_based = range( 1, dim + 1)
set_dim_1_based = set( r_di... | Is there a way to inspect the (differing) internal structures of Python objects that test as equal (==)? | Yesterday I asked ("A case of outwardly equal lists of sets behaving differently under Python 2.5 (I think …)") why list W constructed as follows:
r_dim_1_based = range( 1, dim + 1)
set_dim_1_based = set( r_dim_1_based)
def listW_fill_func( val):
if (val == 0):
return set_dim_1_based
else:
ret... | [
"You're dealing with references in each case (more similar to pointers than to values). You can surely introspect your objects' references to your heart's contents -- for example, if you have a list and want to check if any items are identical references,\nif len(thelist) != len(set(id(x) for x in thelist)): ...\n... | [
1
] | [] | [] | [
"inspection",
"list",
"python",
"set"
] | stackoverflow_0001665176_inspection_list_python_set.txt |
Q:
Verifying that an object in python adheres to a specific structure
Is there some simple method that can check if an input object to some function adheres to a specific structure? For example, I want only a dictionary of string keys and values that are a list of integers.
One method would be to write a recursive fu... | Verifying that an object in python adheres to a specific structure | Is there some simple method that can check if an input object to some function adheres to a specific structure? For example, I want only a dictionary of string keys and values that are a list of integers.
One method would be to write a recursive function that you pass in the object and you iterate over it, checking at ... | [
"Why would you expect Python to provide an \"elegant way\" to check types, since the whole idea of type-checking is so utterly alien to the Pythonic way of conceiving the world and interacting with it?! Normally in Python you'd use duck typing -- so \"an integer\" might equally well be an int, a long, a gmpy.mpz -... | [
4,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001665260_python.txt |
Q:
BeautifulSoup with Jython
I just tried to run BeautifulSoup (3.1.0.1) with Jython (2.5.1) and I was amazed to see how much slower it was than CPython. Parsing a page (http://www.fixprotocol.org/specifications/fields/5000-5999) with CPython took just under a second (0.844 second to be exact). With Jython it took 56... | BeautifulSoup with Jython | I just tried to run BeautifulSoup (3.1.0.1) with Jython (2.5.1) and I was amazed to see how much slower it was than CPython. Parsing a page (http://www.fixprotocol.org/specifications/fields/5000-5999) with CPython took just under a second (0.844 second to be exact). With Jython it took 564 seconds - almost 700 times as... | [
"I can confirm similar findings.\nIntel Mac, OS X 10.6.1, Java 1.6.0_15 64-bit, Jython 2.5.1.\nRunning your code with CPython 2.6.1 takes 0.1–0.2 seconds, but running it with Jython takes at least tens of seconds; I didn't wait more than 30. It also uses a lot of CPU.\nI tried Beautiful Soup 3.0.7a, because it uses... | [
6
] | [] | [] | [
"beautifulsoup",
"jython",
"python"
] | stackoverflow_0001661310_beautifulsoup_jython_python.txt |
Q:
How to create an image from a string in python
I'm currently having trouble creating an image from a binary string of data in my Python program. I receive the binary data via a socket but when I try the methods I read about on here like this:
buff = StringIO.StringIO() #buffer where image is stored
#Then I concat... | How to create an image from a string in python | I'm currently having trouble creating an image from a binary string of data in my Python program. I receive the binary data via a socket but when I try the methods I read about on here like this:
buff = StringIO.StringIO() #buffer where image is stored
#Then I concatenate data by doing a
buff.write(data) #the data fr... | [
"I suspect that you're not seek-ing back to the beginning of the buffer before you pass the StringIO object to PIL. Here's some code the demonstrates the problem and solution:\n>>> buff = StringIO.StringIO()\n>>> buff.write(open('map.png', 'rb').read())\n>>> \n>>> #seek back to the beginning so the whole thing will... | [
29,
7
] | [] | [] | [
"image",
"python",
"sockets",
"string"
] | stackoverflow_0001664861_image_python_sockets_string.txt |
Q:
Python, Pygame, Pyro: How to send a surface over a network?
I am working on a project in python using pygame and pyro. I can send data, functions, classes, and the like easily. However, I cannot send a surface across the wire without it dying on me in transit.
The server makes a surface in the def __init__ of the ... | Python, Pygame, Pyro: How to send a surface over a network? | I am working on a project in python using pygame and pyro. I can send data, functions, classes, and the like easily. However, I cannot send a surface across the wire without it dying on me in transit.
The server makes a surface in the def __init__ of the class being accessed across the wire:
self.screen = pygame.displa... | [
"A pygame Surface is a wrapper around an underlying SDL surface, which I suspect can't be serialized by Pyro. If you want to copy its contents across the wire, you would be better off doing something like this:\n\non the server use Surface.get_buffer() to get\naccess to the underlying pixels.\nmake a note of the Su... | [
6,
1,
0
] | [] | [] | [
"network_programming",
"pygame",
"pyro",
"python"
] | stackoverflow_0001665376_network_programming_pygame_pyro_python.txt |
Q:
Forwarding command line arguments to a process in Python
I'm using a crude IDE (Microchip MPLAB) with C30 toolchain on Windows XP.
The C compiler has a very noisy output that I'm unable to control, and it's very hard to spot actual warnings and errors in output window.
I want to write a python script that would re... | Forwarding command line arguments to a process in Python | I'm using a crude IDE (Microchip MPLAB) with C30 toolchain on Windows XP.
The C compiler has a very noisy output that I'm unable to control, and it's very hard to spot actual warnings and errors in output window.
I want to write a python script that would receive arguments for compiler, call the compiler with same argu... | [
"Give the command arguments to Popen as a list:\narguments = sys.argv[1:]\ncmd = [compiler_path] + arguments\nprocess = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n",
"As ChristopheD said the shell removes the quotes.\nBut you don't need to create the string yourself when using Popen:... | [
4,
3,
0
] | [] | [] | [
"arguments",
"command_line_arguments",
"process",
"python",
"quotes"
] | stackoverflow_0001665917_arguments_command_line_arguments_process_python_quotes.txt |
Q:
What is the issubclass equivalent of isinstance in python?
Given an object, how do I tell if it's a class, and a subclass of a given class Foo?
e.g.
class Bar(Foo):
pass
isinstance(Bar(), Foo) # => True
issubclass(Bar, Foo) # <--- how do I do that?
A:
It works exactly as one would expect it to work...
class ... | What is the issubclass equivalent of isinstance in python? | Given an object, how do I tell if it's a class, and a subclass of a given class Foo?
e.g.
class Bar(Foo):
pass
isinstance(Bar(), Foo) # => True
issubclass(Bar, Foo) # <--- how do I do that?
| [
"It works exactly as one would expect it to work...\nclass Foo():\n pass\n\nclass Bar(Foo):\n pass\n\nclass Bar2():\n pass\n\nprint issubclass(Bar, Foo) # True\nprint issubclass(Bar2, Foo) # False\n\nIf you want to know if an instance of a class derived from a given base class, you could use:\nbar_instanc... | [
22
] | [] | [] | [
"introspection",
"python"
] | stackoverflow_0001666079_introspection_python.txt |
Q:
Does Django's Unit Testing Raise Warnings to Exceptions?
I am using Django's unit testing apparatus (manage.py test), which is throwing an error and halting when the code generates a warning. This same code when tested with the standard Python unittest module, generates warnings but continues code execution throu... | Does Django's Unit Testing Raise Warnings to Exceptions? | I am using Django's unit testing apparatus (manage.py test), which is throwing an error and halting when the code generates a warning. This same code when tested with the standard Python unittest module, generates warnings but continues code execution through them.
A little research shows that Python can be set to rai... | [
"Given the updated info, I'm inclined to say that this is the right thing for Django to be doing; MySQL's warnings can indicate any number of things up to and including loss of data (e.g., MySQL will warn and silently truncate if you try to insert a value larger than a column can hold), and that's the sort of thing... | [
2
] | [] | [] | [
"django",
"python",
"unit_testing"
] | stackoverflow_0001658265_django_python_unit_testing.txt |
Q:
IDE for Python + Django Template Highlight + JQuery
I try Netbeans 6.7 for python but don't have a good django template highlight and jquery code completion... i did find a project in google for django for netbeans but they don't explain how to do...
Also I try eclipse with pydev, but have some problems with code ... | IDE for Python + Django Template Highlight + JQuery | I try Netbeans 6.7 for python but don't have a good django template highlight and jquery code completion... i did find a project in google for django for netbeans but they don't explain how to do...
Also I try eclipse with pydev, but have some problems with code competion on my class...
I like to much Netbeans 6.7... I... | [
"Aptana is great in HTML/CSS/Javascript editing.\nYou may also refer to this question:\nWhich text editor has the most useful autocomplete for web page editing\n"
] | [
0
] | [] | [] | [
"django_templates",
"jquery",
"python"
] | stackoverflow_0001665468_django_templates_jquery_python.txt |
Q:
MOD_WSGI difficulties on Mac OS X Snow Leopard
I've been trying to get MOD_WSGI working on Apache via XAMPP on my Mac OS X Snow Leopard all day today without any success. I've followed all the instructions, searched the internet for solutions, etc but no luck so far. Below are my exact steps and details. When I ru... | MOD_WSGI difficulties on Mac OS X Snow Leopard | I've been trying to get MOD_WSGI working on Apache via XAMPP on my Mac OS X Snow Leopard all day today without any success. I've followed all the instructions, searched the internet for solutions, etc but no luck so far. Below are my exact steps and details. When I run localhost all I get is a white screen. When I remo... | [
"First off, run 'make distclean' and then redo configure/make/make install for mod_wsgi. Where you have 'Terminal \"make\" (message \"make: Nothing to be done for `all'.\")' indicates there were prior build results in directory and nothing got built for that execution of make.\nNext, use '.wsgi' extension instead o... | [
3
] | [] | [] | [
"apache",
"macos",
"mod_wsgi",
"python",
"xampp"
] | stackoverflow_0001665994_apache_macos_mod_wsgi_python_xampp.txt |
Q:
Public API with Private Elements in Python
I'm working on a web mapping service and would like to provide my users with a Python API that they can use to create custom plugins. These plugins would be running on my server so I'm trying to lock down Python as much as possible.
To ensure that users can't access files... | Public API with Private Elements in Python | I'm working on a web mapping service and would like to provide my users with a Python API that they can use to create custom plugins. These plugins would be running on my server so I'm trying to lock down Python as much as possible.
To ensure that users can't access files they are not supposed to, I'm planning on runni... | [
"This looks like a clean way to implement this to me. I believe it's also sometimes referred to as the \"Facade\" design pattern.\nIn python this is very easy to implement using explicit method delegation (a short snippet to give you a general idea):\nclass FacadingAPI():\n def __init__(fullapi_instance):\n ... | [
2,
0
] | [] | [] | [
"api",
"class",
"pipe",
"python",
"security"
] | stackoverflow_0001666533_api_class_pipe_python_security.txt |
Q:
Python: advantages and disvantages of _mysql vs MySQLdb?
Two libraries for Mysql.
I've always used _mysql because it's simpler.
Can anyone tell me the difference, and why I should use which one in certain occasions?
A:
MySQLdb uses DB-API (described in PEP 249) which should be preferred, since it's common to al... | Python: advantages and disvantages of _mysql vs MySQLdb? | Two libraries for Mysql.
I've always used _mysql because it's simpler.
Can anyone tell me the difference, and why I should use which one in certain occasions?
| [
"MySQLdb uses DB-API (described in PEP 249) which should be preferred, since it's common to all database drivers. IMHO there is no advantage in going low-level with _mysql. I'd rather think of using higher level libraries, like SQLAlchemy, instead.\n",
"Alternatively, you can use MySQL Connector/Python:\n\nMySQL ... | [
14,
9,
5
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0001620575_mysql_python.txt |
Q:
How to count the number of times something occurs inside a certain string?
In python, I remember there is a function to do this.
.count?
"The big brown fox is brown"
brown = 2.
A:
why not read the docs first, it's very simple:
>>> "The big brown fox is brown".count("brown")
2
A:
One thing worth learning if yo... | How to count the number of times something occurs inside a certain string? | In python, I remember there is a function to do this.
.count?
"The big brown fox is brown"
brown = 2.
| [
"why not read the docs first, it's very simple:\n>>> \"The big brown fox is brown\".count(\"brown\")\n2\n\n",
"One thing worth learning if you're a Python beginner is how to use interactive mode to help with this. The first thing to learn is the dir function which will tell you the attributes of an object.\n>>> ... | [
27,
19
] | [] | [] | [
"python"
] | stackoverflow_0001666700_python.txt |
Q:
file size is dramatically increased after pickle
I'm reading in a file and sending the data (once encrypted) to a dictionary, with a hash of the data before and after encryption. I then pickle the dictionary but find the file size is massive compared to the source file size. If I write the encrypted data straight ... | file size is dramatically increased after pickle | I'm reading in a file and sending the data (once encrypted) to a dictionary, with a hash of the data before and after encryption. I then pickle the dictionary but find the file size is massive compared to the source file size. If I write the encrypted data straight to a file the size is identical to the source. Any ide... | [
"Try using a binary pickle by specifying protocol=2 as a keyword argument to pickle.dump. It should be much more efficient.\n"
] | [
6
] | [] | [] | [
"aes",
"encryption",
"pickle",
"python"
] | stackoverflow_0001667144_aes_encryption_pickle_python.txt |
Q:
How to delete a certain IE cookie from python?
how can I delete IE 8 cookies for a certain site from Python?
A:
It is probably cleaner and less error prone to use the Python standard library module: cookielib this provides functions to manipulate cookies in various ways.
Unfortunately to use this with IE consid... | How to delete a certain IE cookie from python? | how can I delete IE 8 cookies for a certain site from Python?
| [
"It is probably cleaner and less error prone to use the Python standard library module: cookielib this provides functions to manipulate cookies in various ways. \nUnfortunately to use this with IE consider the third party extension to this module: Client Cookie. This module contains various \"cookie jars\" such as ... | [
1,
0
] | [] | [] | [
"cookies",
"internet_explorer",
"python"
] | stackoverflow_0001666989_cookies_internet_explorer_python.txt |
Q:
Accessing POST params with same name in python
I need to get values of these check boxes with same name through HTTP "POST".
<input type="checkbox" id="dde" name="dept[]" value="dde"/>
<input type="checkbox" id="dre" name="dept[]" value="dre"/>
<input type="checkbox" id="iid" name="dept[]" value="iid"/>
How to ge... | Accessing POST params with same name in python | I need to get values of these check boxes with same name through HTTP "POST".
<input type="checkbox" id="dde" name="dept[]" value="dde"/>
<input type="checkbox" id="dre" name="dept[]" value="dre"/>
<input type="checkbox" id="iid" name="dept[]" value="iid"/>
How to get these values in python using self.request.get() me... | [
"You can use request.get_all(). \nAccording to the docs it \"Returns a list of values of all of the query (URL) or POST arguments with the given name, possibly an empty list.\"\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"http",
"python"
] | stackoverflow_0001667349_google_app_engine_http_python.txt |
Q:
Best way to convert HTML to plaintext using Python
I'm working on a project that involves converting a large amount of HTML content to plain/text. I have a custom-written module that does the job OK, but I'm wondering if there's some standard tools to help get the job done.
A:
Html2Text seems to be a good option... | Best way to convert HTML to plaintext using Python | I'm working on a project that involves converting a large amount of HTML content to plain/text. I have a custom-written module that does the job OK, but I'm wondering if there's some standard tools to help get the job done.
| [
"Html2Text seems to be a good option\n",
"Here's a python library which does HTML parsing:\n\nlxml.html\n\nBeautifulSoup is another option.\n"
] | [
10,
4
] | [] | [] | [
"html",
"plaintext",
"python"
] | stackoverflow_0001668081_html_plaintext_python.txt |
Q:
Visibility_notify event in pyGTK
I am on windows and I am developing a pygtk app. I need to know when a window is visible or hidden by another window. In order to stop an heavy drawing process.
http://www.pygtk.org/docs/pygtk/class-gtkwidget.html#signal-gtkwidget--visibility-notify-event
I Use the visibility_notif... | Visibility_notify event in pyGTK | I am on windows and I am developing a pygtk app. I need to know when a window is visible or hidden by another window. In order to stop an heavy drawing process.
http://www.pygtk.org/docs/pygtk/class-gtkwidget.html#signal-gtkwidget--visibility-notify-event
I Use the visibility_notify_event to be notified on windows visi... | [
"It's quite likely that the underlying GDK layer simply isn't \"good enough\" on Windows. The GTK+ toolkit's port to Windows is known to be a bit lagging in functionality and polish.\nIf you can try the same program on a Linux machine, and it works there, you can be pretty certain this is a limitation of the Window... | [
2
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0001667525_pygtk_python.txt |
Q:
How do I get the string representation of a variable in python?
I have a variable x in python. How can i find the string 'x' from the variable. Here is my attempt:
def var(v,c):
for key in c.keys():
if c[key] == v:
return key
def f():
x = '321'
print 'Local var %s = %s'%(var(x,locals()),x)
x = ... | How do I get the string representation of a variable in python? | I have a variable x in python. How can i find the string 'x' from the variable. Here is my attempt:
def var(v,c):
for key in c.keys():
if c[key] == v:
return key
def f():
x = '321'
print 'Local var %s = %s'%(var(x,locals()),x)
x = '123'
print 'Global var %s = %s'%(var(x,locals()),x)
f()
The result... | [
"Q: I have a variable x in python. How can i find the string 'x' from the variable.\nA: If I am understanding your question properly, you want to go from the value of a variable to its name. This is not really possible in Python.\nIn Python, there really isn't any such thing as a \"variable\". What Python really h... | [
14,
7,
3,
1
] | [] | [] | [
"introspection",
"python"
] | stackoverflow_0001665833_introspection_python.txt |
Q:
qt - pyqt QTableView not populating when changing databases
I'm trying to allow my users to pick which database to open. Each database will have the same schema. For some reason though I can't get my QTableView to populate after I open the database.
I'm paraphrasing the example code but this should give you an ide... | qt - pyqt QTableView not populating when changing databases | I'm trying to allow my users to pick which database to open. Each database will have the same schema. For some reason though I can't get my QTableView to populate after I open the database.
I'm paraphrasing the example code but this should give you an idea of what I'm trying to do.
works:
class aMainWindow(QMainWindow,... | [
"I can't remember today exactly where I found it but as I was researching something else I found some forum posting that said the connection must be made before making the model. I suspect there must be some code in the model construct that's touching the db. I changed my on_actionOpen_DB_triggered to create the mo... | [
2
] | [] | [] | [
"pyqt",
"python",
"qt"
] | stackoverflow_0001659756_pyqt_python_qt.txt |
Q:
Reading bytestreams in Python
I'm using Python appscript to write artwork to my iTunes Songs. I have a file stored in .pict format and when I use the normal open and read routines, it reads the content as a string (encoded in utf-8).
imFile = open('/Users/kartikaiyer/temp.pict','r')
data = imFile.read()
it = app('... | Reading bytestreams in Python | I'm using Python appscript to write artwork to my iTunes Songs. I have a file stored in .pict format and when I use the normal open and read routines, it reads the content as a string (encoded in utf-8).
imFile = open('/Users/kartikaiyer/temp.pict','r')
data = imFile.read()
it = app('iTunes')
sel = it.current_track.get... | [
"Try setting the read mode to binary:\nimFile = open('/Users/kartikaiyer/temp.pict','rb')\n\n"
] | [
7
] | [] | [] | [
"py_appscript",
"python",
"sourceforge_appscript"
] | stackoverflow_0001669040_py_appscript_python_sourceforge_appscript.txt |
Q:
Summing Consecutive Ranges Pythonically
I have a sumranges() function, which sums all the ranges of consecutive numbers found in a tuple of tuples. To illustrate:
def sumranges(nums):
return sum([sum([1 for j in range(len(nums[i])) if
nums[i][j] == 0 or
nums[i][j - 1] ... | Summing Consecutive Ranges Pythonically | I have a sumranges() function, which sums all the ranges of consecutive numbers found in a tuple of tuples. To illustrate:
def sumranges(nums):
return sum([sum([1 for j in range(len(nums[i])) if
nums[i][j] == 0 or
nums[i][j - 1] + 1 != nums[i][j]]) for
i in ... | [
"My 2 cents:\n>>> sum(len(set(x - i for i, x in enumerate(t))) for t in nums)\n7\n\nIt's basically the same idea as descriped in Alex' post, but using a set instead of itertools.groupby, resulting in a shorter expression. Since sets are implemented in C and len() of a set runs in constant time, this should also be ... | [
14,
9,
7,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001668491_python.txt |
Q:
Python: importing through function to main namespace
(Important: See update below.)
I'm trying to write a function, import_something, that will important certain modules. (It doesn't matter which for this question.) The thing is, I would like those modules to be imported at the level from which the function is cal... | Python: importing through function to main namespace | (Important: See update below.)
I'm trying to write a function, import_something, that will important certain modules. (It doesn't matter which for this question.) The thing is, I would like those modules to be imported at the level from which the function is called. For example:
import_something() # Let's say this impo... | [
"Functions have the ability to return something to where they were called. Its called their return value :p\ndef import_something():\n # decide what to import\n # ...\n mod = __import__( something )\n return mod\nmy_module = import_something()\nmy_module.do_stuff()\n\ngood style, no hassle.\nAbout your ... | [
4,
1,
1,
0
] | [] | [] | [
"import",
"python"
] | stackoverflow_0001668882_import_python.txt |
Q:
Python auto define variables
I am new to programming and am learning Python as my first language. I have been tasked with writing a script that converts one input file type to another. My problem is this: There is one part of the input files where there can be any number of rows of data. I wrote a loop to determin... | Python auto define variables | I am new to programming and am learning Python as my first language. I have been tasked with writing a script that converts one input file type to another. My problem is this: There is one part of the input files where there can be any number of rows of data. I wrote a loop to determine how many rows there are but cann... | [
"You can dynamically create the variables, but it doesn't make sense unless this is homework.\ninstead use\nrprim=infile.readlines()\n\nthen the lines are \nrprim[0], rprim[1], rprim[2], rprim[3], rprim[4], rprim[5], rprim[6]\n\nyou can find out how many rows there are with\nlen(rprim)\n\n",
"That is something yo... | [
13,
1
] | [] | [] | [
"python",
"variables"
] | stackoverflow_0001670252_python_variables.txt |
Q:
How can I get pyplot images to show on a console app?
I'm trying to create an image using matplotlib.pyplot.imshow(). However, when I run the program from my console, it doesn't display anything?
This is the code:
import matplotlib.pyplot
myimage = gen_image()
matplotlib.pyplot.gray()
matplotlib.pyplot.imshow(r... | How can I get pyplot images to show on a console app? | I'm trying to create an image using matplotlib.pyplot.imshow(). However, when I run the program from my console, it doesn't display anything?
This is the code:
import matplotlib.pyplot
myimage = gen_image()
matplotlib.pyplot.gray()
matplotlib.pyplot.imshow(results)
But this shows nothing.
| [
"You have to call the show function to actually display anything, like\nmatplotlib.pyplot.show()\n\nUnfortunately the matplotlib documentation seems to be currently broken, so I can't provide a link.\nNote that for interactive plotting one typically uses IPython, which has special support for matplotlib.\nBy the wa... | [
14,
0
] | [] | [] | [
"console",
"image",
"matplotlib",
"python"
] | stackoverflow_0001670480_console_image_matplotlib_python.txt |
Q:
Set Max Width for Frame with ScrolledWindow in wxPython
I created a Frame object and I want to limit the width it can expand to. The only window in the frame is a ScrolledWindow object and that contains all other children. I have a lot of objects arranged with a BoxSizer oriented vertically so the ScrolledWindow o... | Set Max Width for Frame with ScrolledWindow in wxPython | I created a Frame object and I want to limit the width it can expand to. The only window in the frame is a ScrolledWindow object and that contains all other children. I have a lot of objects arranged with a BoxSizer oriented vertically so the ScrolledWindow object gets pretty tall. There is often a scrollbar to the rig... | [
"This is a little ugly, but seems to work on Window and Linux. There is difference, though. The self.GetVirtualSize() seems to return different values on each platform. At any rate, I think this may help you.\nwidth, height = self.scroll.GetBestSize()\nwidth_2, height_2 = self.GetVirtualSize()\nprint width\nprin... | [
1
] | [] | [] | [
"python",
"user_interface",
"wxpython"
] | stackoverflow_0001371510_python_user_interface_wxpython.txt |
Q:
How to prepopulate ID in Django
I have simple question model :
class Question(Polymorph):
text = models.CharField(max_length=256)
poll = models.ForeignKey(Poll)
index = models.IntegerField()
And I would like to prepopulate ( when saving ) index field with ID value. Of course before save I dont have ID... | How to prepopulate ID in Django | I have simple question model :
class Question(Polymorph):
text = models.CharField(max_length=256)
poll = models.ForeignKey(Poll)
index = models.IntegerField()
And I would like to prepopulate ( when saving ) index field with ID value. Of course before save I dont have ID value ( its created after it ), so I... | [
"However you do it, you'll have to call save twice. The ID is generated directly by the database server (except for sqlite, I believe) when the new row is INSERTed, so you'll need to do that in any case.\nI would ask if you really need to have the ID value in your index field, though. It's always available as obj.i... | [
5,
0,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0001653828_django_django_models_python.txt |
Q:
Namespace-respecting relative import in Python
I have this folder structure:
package/
__init__.py
misc/
__init__.py
tools.py
subpackage/
__init__.py
submodule.py
I am in submodule.py, and I would like to import misc.tools. I don't want to use absolute import to import p... | Namespace-respecting relative import in Python | I have this folder structure:
package/
__init__.py
misc/
__init__.py
tools.py
subpackage/
__init__.py
submodule.py
I am in submodule.py, and I would like to import misc.tools. I don't want to use absolute import to import package.misc.tools, because then my package would onl... | [
"What about...:\nfrom .. import misc\nfrom ..misc import tools as _\n\nprint misc.tools.__file__\n\nThis makes misc.tools available, as the print confirms, and with the right name and contents.\nInevitably, it also binds the same module to some barename -- I've chosen _ as a typical \"throw-away barename\", but of ... | [
6
] | [] | [] | [
"import",
"python",
"relative_path"
] | stackoverflow_0001671362_import_python_relative_path.txt |
Q:
feedparser and Google News
I'm trying to download a corpus of news (to try to do some natural language processing) from Google News using the universal feedparser with python. I really know nothing of XML, I'm just using an example of how to use the feedparser.
The problem is that I can't find in the dict I get fr... | feedparser and Google News | I'm trying to download a corpus of news (to try to do some natural language processing) from Google News using the universal feedparser with python. I really know nothing of XML, I'm just using an example of how to use the feedparser.
The problem is that I can't find in the dict I get from the RSS feed the content of t... | [
"Have you examined the feed from Google News?\nThere is a root element in each feed which contains a bunch of information and the actual entries dict. Here's a dirty way to see what's available:\nimport feedparser\nd = feedparser.parse('http://news.google.com/news?pz=1&cf=all&ned=ca&hl=en&topic=w&output=rss')\n\npr... | [
8,
1
] | [] | [] | [
"feedparser",
"google_news",
"python",
"rss"
] | stackoverflow_0001671428_feedparser_google_news_python_rss.txt |
Q:
Send and receive messages via (libpurple) messenger protocols
I had an idea that would require me be able to send and receive messages via the standard messenger protocols such as msn, icq, aim, skype, etc...
I am currently only familiar with PHP and Python and would thus enjoy a library which I can access from sa... | Send and receive messages via (libpurple) messenger protocols | I had an idea that would require me be able to send and receive messages via the standard messenger protocols such as msn, icq, aim, skype, etc...
I am currently only familiar with PHP and Python and would thus enjoy a library which I can access from said languages. I have found phurple (http://sourceforge.net/projects... | [
"Here is how to connect to the Pidgin DBus server.\n#!/usr/bin/env python\nimport dbus\n\nbus = dbus.SessionBus()\n\nif \"im.pidgin.purple.PurpleService\" in bus.list_names():\n purple = bus.get_object(\"im.pidgin.purple.PurpleService\",\n \"/im/pidgin/purple/PurpleObject\",\n \"im.pidgin.p... | [
11,
2,
1,
0
] | [] | [] | [
"libpurple",
"php",
"python"
] | stackoverflow_0001620793_libpurple_php_python.txt |
Q:
Decorating Instance Methods in Python
Here's the gist of what I'm trying to do. I have a list of objects, and I know they have an instance method that looks like:
def render(self, name, value, attrs)
# Renders a widget...
I want to (essentialy) decorate these functions at runtime, as I'm iterating over the lis... | Decorating Instance Methods in Python | Here's the gist of what I'm trying to do. I have a list of objects, and I know they have an instance method that looks like:
def render(self, name, value, attrs)
# Renders a widget...
I want to (essentialy) decorate these functions at runtime, as I'm iterating over the list of objects. So that their render function... | [
"def decorate_method(f):\n def wrapper(self, name, value, attrs):\n self.attrs = attrs\n return f(self, name, value, attrs)\n return wrapper\n\ndef decorate_class(c):\n for n in dir(c):\n f = getattr(c, n)\n if hasattr(f, 'im_func'):\n setattr(c, n, decorate_method(f.im_func))\n\nYou'll probably... | [
7,
3
] | [] | [] | [
"class",
"decorator",
"django",
"instance",
"python"
] | stackoverflow_0001672064_class_decorator_django_instance_python.txt |
Q:
text-mine PDF files with Python?
Is there a package/library for python that would allow me to open a PDF, and search the text for certain words?
A:
Using PyPdf2 you can use extractText() method to extract pdf text and work on it.
Update: Changed text to refer to PyPdf2, thanks to @Aditya Kumar for heads up.
A:
... | text-mine PDF files with Python? | Is there a package/library for python that would allow me to open a PDF, and search the text for certain words?
| [
"Using PyPdf2 you can use extractText() method to extract pdf text and work on it.\nUpdate: Changed text to refer to PyPdf2, thanks to @Aditya Kumar for heads up.\n",
"I don't think you can do it in one step, but you can certainly get the text out of a pdf with pdfminer. Then you can apply whatever text search to... | [
12,
4
] | [] | [] | [
"pdf",
"python",
"text_mining"
] | stackoverflow_0001672202_pdf_python_text_mining.txt |
Q:
Reading from files in python
I need to find out the maximum and minimum value in a line by reading a file and should be dividing the maximum value by the minimum value. Am interested to do this in python.
the contents of the file (file.txt) looks like this..
A28102_at,151,263,88,484,118,270,458,872,62,194
AB00011... | Reading from files in python | I need to find out the maximum and minimum value in a line by reading a file and should be dividing the maximum value by the minimum value. Am interested to do this in python.
the contents of the file (file.txt) looks like this..
A28102_at,151,263,88,484,118,270,458,872,62,194
AB000114_at,72,21,20,61,20,85,20,25,20,65... | [
"Python comes with batteries! Use the csv module to parse csv files:\n#!/usr/bin/env python\nimport csv\ncsvobj=csv.reader(open('file.txt','r'))\nfor datum in csvobj:\n datum=[float(val) for val in datum[1:]] \n print(datum)\n maximum=max(datum)\n minimum=min(datum)\n print(maximum/minimum)\n\n# [151... | [
6,
4,
3
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0001672360_file_io_python.txt |
Q:
How to upload huge files from Nokia 95 to webserver?
I'm trying to upload a huge file from my Nokia N95 mobile to my webserver using Pys60 python code. However the code crashes because I'm trying to load the file into memory and trying to post to a HTTP url. Any idea how to upload huge files > 120 MB to webserver ... | How to upload huge files from Nokia 95 to webserver? | I'm trying to upload a huge file from my Nokia N95 mobile to my webserver using Pys60 python code. However the code crashes because I'm trying to load the file into memory and trying to post to a HTTP url. Any idea how to upload huge files > 120 MB to webserver using Pys60.
Following is the code I use to send the HTTP ... | [
"You can't. It's pretty much physically impossible. You'll need to split the file into small chunks and upload it bit by bit, which is very difficult to do quickly and efficiently on that sort of platform.\nJamie\n",
"You'll need to craft a client code to split your source file in small chunks and rebuild that pi... | [
0,
0,
0
] | [] | [] | [
"file_upload",
"http",
"post",
"pys60",
"python"
] | stackoverflow_0001670944_file_upload_http_post_pys60_python.txt |
Q:
overloading __init__ of unittest.testcase
I want to add two variables to my subclass which is inherited from unittest.testcase
like I have:
import unittest
class mrp_repair_test_case(unittest.TestCase):
def __init__(self, a=None, b=None, methodName=['runTest']):
unittest.TestCase.__init__(self)... | overloading __init__ of unittest.testcase | I want to add two variables to my subclass which is inherited from unittest.testcase
like I have:
import unittest
class mrp_repair_test_case(unittest.TestCase):
def __init__(self, a=None, b=None, methodName=['runTest']):
unittest.TestCase.__init__(self)
self.a= a
self.b = ... | [
"At first glance, it looks like you need to create an instance of mrp_repair_test_case. Your current line:\nmrp_repair_test_case(a=10,b=20)\n\ndoesn't actually do anything.\nTry (not tested):\ndef runtest():\n m = mrp_repair_test_case(a=10, b=20)\n suite = unittest.TestLoader().loadsTestsFromTestCase(m)\n ... | [
6
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0001672520_python_unit_testing.txt |
Q:
web chart with hover events
I am after a library with a Python interface to render nice looking charts with hover events for each point.
ChartDirector does what I want, but I would prefer an open source solution.
OpenFlashChart looks good, although ideally I would want a non-Flash solution.
Any other contenders?
... | web chart with hover events | I am after a library with a Python interface to render nice looking charts with hover events for each point.
ChartDirector does what I want, but I would prefer an open source solution.
OpenFlashChart looks good, although ideally I would want a non-Flash solution.
Any other contenders?
| [
"Not strictly Python, but you may want to look at Flot. (assuming by web chart you mean those that are to be embedded on web pages)\n"
] | [
2
] | [] | [] | [
"charts",
"graph",
"hover",
"python"
] | stackoverflow_0001671520_charts_graph_hover_python.txt |
Q:
SQL returning extra data
Hey there, was wondering if anyone could help a newbie on SQL and Python. I thought I had a pretty decent grasp of it, however something odd happened recently.
Here is the the following code snipped from a larger portion:
try:
self.db.query("SELECT * FROM account WHERE email = '{0}... | SQL returning extra data | Hey there, was wondering if anyone could help a newbie on SQL and Python. I thought I had a pretty decent grasp of it, however something odd happened recently.
Here is the the following code snipped from a larger portion:
try:
self.db.query("SELECT * FROM account WHERE email = '{0}' AND pass = '{1}'".format(sel... | [
"I think, python's dbapi is supposed to always return integer-fields as long. \nAnyway, 10L, 5L and so on is the way repr (which is used on every item of a tuple in your case) works for longs.\nOne more thing. I see, you are using MySQLdb. In that case, I strongly suggest, that you stop using the c-api wrapper, but... | [
7,
2,
1,
1
] | [] | [] | [
"mysql",
"python",
"sql"
] | stackoverflow_0001672814_mysql_python_sql.txt |
Q:
python chat client lib
I'm trying to write a Python lib that will implement the client side of a certain chat protocol.
After I connect to the server,
I start the main loop where I read from the server and handle received commands and here I need to call a callback function (like on_message or on file_received, ... | python chat client lib | I'm trying to write a Python lib that will implement the client side of a certain chat protocol.
After I connect to the server,
I start the main loop where I read from the server and handle received commands and here I need to call a callback function (like on_message or on file_received, etc).
How should I go abou... | [
"For a python app doing this, I wouldn't use threads. I would use a framework like Twisted.\nThe docs have examples; here's a chat example.\n",
"I would use the select module, or alternately twisted, however select is a bit more portable, and to my mind somewhat more pythonic.\n",
"Threads are just an unnecess... | [
6,
2,
1
] | [] | [] | [
"chat",
"multithreading",
"python"
] | stackoverflow_0001670735_chat_multithreading_python.txt |
Q:
parse.unquote_plus TypeError
I'm trying to format a file so that it can be inserted into a database, the file is originally compressed and arround 1.3MB big.
Each line looks something like this:
398,%7EAnoniem+001%7E,543,480,7525010,1775,0
This is how the code looks like that parses this file:
Village = gzip.... | parse.unquote_plus TypeError | I'm trying to format a file so that it can be inserted into a database, the file is originally compressed and arround 1.3MB big.
Each line looks something like this:
398,%7EAnoniem+001%7E,543,480,7525010,1775,0
This is how the code looks like that parses this file:
Village = gzip.open(Root+'\\data'+'\\' +str(Newes... | [
"PROBLEM 1 is that urllib.unquote_plus doesn't like the line that you have fed it. The message should be \"Please supply a str object\" :-) I suggest that you fix problem 2 below, and insert:\nprint('line', type(line), repr(line))\n\nimmediately after your for statement so that you can see what you are getting in l... | [
2,
0
] | [] | [] | [
"parsing",
"python",
"typeerror",
"urllib"
] | stackoverflow_0001672621_parsing_python_typeerror_urllib.txt |
Q:
Setting a lambda function as a property
Consider these two classes:
class Test(int):
difference = property(lambda self: self.__sub__)
class Test2(int):
difference=lambda self: self.__sub__
Is there any difference between these two classes? New: If so, what is the purpose of using the property to store a ... | Setting a lambda function as a property | Consider these two classes:
class Test(int):
difference = property(lambda self: self.__sub__)
class Test2(int):
difference=lambda self: self.__sub__
Is there any difference between these two classes? New: If so, what is the purpose of using the property to store a lambda function that returns another function... | [
"For Test1, you could use .difference - for Test2, you'd need to use .difference() instead.\nAs for why you might use it, a potential use would be to replace something that was previously directly stored as a property with a dynamic calculation instead.\nFor instance, if you used to store property obj.a, but then y... | [
8,
3,
3,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0001665789_python.txt |
Q:
Combining 2 lists in python
I have 2 lists each of equal size and am interested to combine these two lists and write it into a file.
alist=[1,2,3,5]
blist=[2,3,4,5]
--the resulting list should be like
[(1,2), (2,3), (3,4), (5,5)]
After that i want that to be written it to a file. How can i accomplish this?... | Combining 2 lists in python | I have 2 lists each of equal size and am interested to combine these two lists and write it into a file.
alist=[1,2,3,5]
blist=[2,3,4,5]
--the resulting list should be like
[(1,2), (2,3), (3,4), (5,5)]
After that i want that to be written it to a file. How can i accomplish this?
| [
"# combine the lists\nzipped = zip(alist, blist)\n\n# write to a file (in append mode)\nfile = open(\"filename\", 'a') \nfor item in zipped:\n file.write(\"%d, %d\\n\" % item) \nfile.close()\n\nThe resulting output in the file will be:\n 1,2\n 2,3\n 3,4\n 5,5\n\n",
"For the sake of completeness, I'll add to Be... | [
13,
6
] | [] | [] | [
"list",
"python"
] | stackoverflow_0001673005_list_python.txt |
Q:
python and pyPdf - how to extract text from the pages so that there are spaces between lines
currently, if I make a page object of a pdf page with pyPdf, and extractText(), what happens is that lines are concatenated together. For example, if line 1 of the page says "hello" and line 2 says "world" the resulting te... | python and pyPdf - how to extract text from the pages so that there are spaces between lines | currently, if I make a page object of a pdf page with pyPdf, and extractText(), what happens is that lines are concatenated together. For example, if line 1 of the page says "hello" and line 2 says "world" the resulting text returned from extractText() is "helloworld" instead of "hello world." Does anyone know how to f... | [
"This is a common problem with pdf parsing. You can also expect trailing dashes that you will have to fix in some cases. I came up with a workaround for one of my projects which I will describe here shortly:\nI used pdfminer to extract XML from PDF and also found concatenated words in the XML. I extracted the same ... | [
2
] | [] | [] | [
"formatting",
"pypdf",
"python",
"text"
] | stackoverflow_0001672466_formatting_pypdf_python_text.txt |
Q:
What do backticks mean to the Python interpreter? Example: `num`
I'm playing around with list comprehensions and I came across this little snippet on another site:
return ''.join([`num` for num in xrange(loop_count)])
I spent a few minutes trying to replicate the function (by typing) before realising the `num` bi... | What do backticks mean to the Python interpreter? Example: `num` | I'm playing around with list comprehensions and I came across this little snippet on another site:
return ''.join([`num` for num in xrange(loop_count)])
I spent a few minutes trying to replicate the function (by typing) before realising the `num` bit was breaking it.
What does enclosing a statement in those characters... | [
"Backticks are a deprecated alias for repr(). Don't use them any more; the syntax was removed in Python 3.0.\nUsing backticks seems to be faster than using repr(num) or num.__repr__() in version 2.x. I guess it's because additional dictionary lookup is required in the global namespace (for repr), or in the object's... | [
134,
10,
1
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0001673071_list_comprehension_python.txt |
Q:
How to deal with query parameter's encoding?
I assumed that any data being sent to my parameter strings would be utf-8, since that is what my whole site uses throughout. Lo-and-behold I was wrong.
For this example has the character ä in utf-8 in the document (from the query string) but proceeds to send a B\xe4ule ... | How to deal with query parameter's encoding? | I assumed that any data being sent to my parameter strings would be utf-8, since that is what my whole site uses throughout. Lo-and-behold I was wrong.
For this example has the character ä in utf-8 in the document (from the query string) but proceeds to send a B\xe4ule (which is either ISO-8859-1 or windows 1252) when ... | [
"Since Django 1.0 all values you get from form submission are unicode objects, not bytestrings like in Django 0.96 and earlier. To get utf-8 from your values encode them with utf-8 codec:\nrequest.POST['somefield'].encode('utf-8')\n\nTo get query parameters decoded properly, they have to be properly encoded first:\... | [
3,
1,
0,
0,
0
] | [] | [] | [
"django",
"python",
"unicode",
"utf_8"
] | stackoverflow_0001526965_django_python_unicode_utf_8.txt |
Q:
Need help on making the recursive parser using pyparsing
I am trying the python pyparsing for parsing. I got stuck up while making the recursive parser.
Let me explain the problem
I want to make the Cartesian product of the elements. The syntax is
cross({elements },{element})
I put in more specific way
cross({... | Need help on making the recursive parser using pyparsing | I am trying the python pyparsing for parsing. I got stuck up while making the recursive parser.
Let me explain the problem
I want to make the Cartesian product of the elements. The syntax is
cross({elements },{element})
I put in more specific way
cross({a},{c1}) or cross({a,b},{c1}) or cross({a,b,c,d},{c1}) or
So... | [
"You should look at definitions of other languages to see how this is usually handled.\nFor example, look at how multiplication is defined.\nIt isn't\n{expression} * {expression}\n\nBecause the recursion is hard to deal with, and there's no implied left-to-right ordering. What you see more often are things like\n... | [
6,
4,
3
] | [] | [] | [
"parsing",
"pyparsing",
"python",
"recursion"
] | stackoverflow_0000634432_parsing_pyparsing_python_recursion.txt |
Q:
DBus Python Problems
When I'm trying to get the idle time of the gnome screensaver in seconds, through dbus, python throws an TypeError.
In the documentation I found for the screensaver sessionIdleTime, it returns a unsigned integer. http://www.gnome.org/~mccann/gnome-screensaver/docs/gnome-screensaver.html#gs-met... | DBus Python Problems | When I'm trying to get the idle time of the gnome screensaver in seconds, through dbus, python throws an TypeError.
In the documentation I found for the screensaver sessionIdleTime, it returns a unsigned integer. http://www.gnome.org/~mccann/gnome-screensaver/docs/gnome-screensaver.html#gs-method-GetSessionIdle
However... | [
"str(gs.GetSessionIdleTime()) cast the integer into a string.\nAnd after that, using + in a string variable incorporated it into another dbus call that was called by the output.\n"
] | [
0
] | [] | [] | [
"dbus",
"gnome",
"python"
] | stackoverflow_0001672113_dbus_gnome_python.txt |
Q:
How to match alphabetical chars without numeric chars with Python regexp?
Using Python module re, how to get the equivalent of the "\w" (which matches alphanumeric chars) WITHOUT matching the numeric characters (those which can be matched by "[0-9]")?
Notice that the basic need is to match any character (including... | How to match alphabetical chars without numeric chars with Python regexp? | Using Python module re, how to get the equivalent of the "\w" (which matches alphanumeric chars) WITHOUT matching the numeric characters (those which can be matched by "[0-9]")?
Notice that the basic need is to match any character (including all unicode variation) without numerical chars (which are matched by "[0-9]").... | [
"You want [^\\W\\d]: the group of characters that is not (either a digit or not an alphanumeric). Add an underscore in that negated set if you don't want them either.\nA bit twisted, if you ask me, but it works. Should be faster than the lookahead alternative.\n",
"(?!\\d)\\w\n\nA position that is not followed by... | [
37,
9
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0001673749_python_regex.txt |
Q:
How to generate graphical sitemap of large website
I would like to generate a graphical sitemap for my website. There are two stages, as far as I can tell:
crawl the website and analyse the link relationship to extract the tree structure
generate a visually pleasing render of the tree
Does anyone have advice or... | How to generate graphical sitemap of large website | I would like to generate a graphical sitemap for my website. There are two stages, as far as I can tell:
crawl the website and analyse the link relationship to extract the tree structure
generate a visually pleasing render of the tree
Does anyone have advice or experience with achieving this, or know of existing wor... | [
"The only automatic way to create a sitemap is to know the structure of your site and write a program which builds on that knowledge. Just crawling the links won't usually work because links can be between any pages so you get a graph (i.e. connections between nodes). There is no way to convert a graph into a tree ... | [
4,
3,
1
] | [] | [] | [
"python",
"sitemap",
"web",
"web_crawler"
] | stackoverflow_0001672532_python_sitemap_web_web_crawler.txt |
Q:
How can I get the full list of running processes on a Mac from a python app
I want to get the list of running processes on the Mac, similar to what you get from 'ps -ea'
I have tried os.popen('ps -ea') but this only lists a small subset of the processes, presumably those owned by the owning shell.
Other options I... | How can I get the full list of running processes on a Mac from a python app | I want to get the list of running processes on the Mac, similar to what you get from 'ps -ea'
I have tried os.popen('ps -ea') but this only lists a small subset of the processes, presumably those owned by the owning shell.
Other options I have tried are
'sh -c /bin/ps -ea'
'bash -c /bin/ps -ea'
'csh -c /bin/ps -ea'
Ru... | [
"os.popen('ps aux') looks like it's listing all processes for me.\n"
] | [
8
] | [] | [] | [
"macos",
"process",
"python"
] | stackoverflow_0001673874_macos_process_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.