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 psycopg2 error when changing environment to os x
I have this error when i perform the following task,
results = db1.executeSelectCommand(siteSql, (),)
TypeError: unbound method executeSelectCommand() must be called with dbConnn instance as first argument (got str instance instead)
My code is as follows:
class dbConnn:
db_con = None
execfile("/Users/usera/Documents/workspace/testing/src/db/db_config.py")
def executeSelectCommand(self,sql,ip):
#psycopg connection here.
I use this class here:
from db import dbConnections
db1 = dbConnections.dbConnn
siteSql = 'select post_content from post_content_ss order by RANDOM() limit 500' #order by year,month ASC'
results = db1.executeSelectCommand(siteSql, (),)
In windows, there don't seem to have a problem with this? God, it must be really elementary but I can't find it.
A:
db1 = dbConnections.dbConnn
Here you assign the class dbConn to the variable db1. You probably wanted to create a new instance instead:
db1 = dbConnections.dbConnn()
| Python psycopg2 error when changing environment to os x | I have this error when i perform the following task,
results = db1.executeSelectCommand(siteSql, (),)
TypeError: unbound method executeSelectCommand() must be called with dbConnn instance as first argument (got str instance instead)
My code is as follows:
class dbConnn:
db_con = None
execfile("/Users/usera/Documents/workspace/testing/src/db/db_config.py")
def executeSelectCommand(self,sql,ip):
#psycopg connection here.
I use this class here:
from db import dbConnections
db1 = dbConnections.dbConnn
siteSql = 'select post_content from post_content_ss order by RANDOM() limit 500' #order by year,month ASC'
results = db1.executeSelectCommand(siteSql, (),)
In windows, there don't seem to have a problem with this? God, it must be really elementary but I can't find it.
| [
"db1 = dbConnections.dbConnn\n\nHere you assign the class dbConn to the variable db1. You probably wanted to create a new instance instead:\ndb1 = dbConnections.dbConnn()\n\n"
] | [
0
] | [] | [] | [
"macos",
"psycopg2",
"python"
] | stackoverflow_0003488521_macos_psycopg2_python.txt |
Q:
Idiomatic way of taking action on attempt to loop over an empty iterable
Suppose that I am looping over a iterable and would like to take some action if the iterator is empty. The two best ways that I can think of to do this are:
for i in iterable:
# do_something
if not iterable:
# do_something_else
and
empty = True
for i in iterable:
empty = False
# do_something
if empty:
# do_something_else
The first depends on the the iterable being a collection (so useless for when the iterable gets passed into the function/method where the loop is) and the second sets empty on every pass through the loop which seems ugly.
Is there another way that I'm missing or is the second alternative the best? It would be really cool if there was some clause that I could add to the loop statement that would handle this for me much like else makes not_found flags go away.
I am not looking for clever hacks.
I am not looking for solutions that involve a lot of code
I am looking for a simple language feature.
I am looking for a clear and pythonic way to iterate over an iterable and take some action if the iterable is empty that any experienced python programmer will be understand. If I could do it without setting a flag on every iteration, that would be fantastic.
If there is no simple idiom that does this, then forget about it.
A:
This is quite hackish, but you can delete i and then check if it exists after the loop (if not, the loop never happened):
try:
del i
except NameException: pass
for i in iterable:
do_something(i)
try:
del i
except NameException:
do_something_else()
I think that's probably uglier than just using a flag though
A:
I think this the the cleanest way to do this:
# first try with exceptions
def nonempty( iter ):
""" returns `iter` if iter is not empty, else raises TypeError """
try:
first = next(iter)
except StopIteration:
raise TypeError("Emtpy Iterator")
yield first
for item in iter:
yield item
# a version without exceptions. Seems nicer:
def isempty( iter ):
""" returns `(True, ())` if `iter` if is empty else `(False, iter)`
Don't use the original iterator! """
try:
first = next(iter)
except StopIteration:
return True, ()
else:
def iterator():
yield first
for item in iter:
yield item
return False, iterator()
for x in ([],[1]):
# first version
try:
list(nonempty(iter(x))) # trying to consume a empty iterator raises
except TypeError:
print x, "is empty"
else:
print x, "is not empty"
# with isempty
empty, it = isempty(iter(x))
print x, "is", ("empty" if empty else "not empty")
A:
Update 2
I liked Odomontois' answer. IMHO it is better suited to this problem than what I have written below.
Update
(After reading the OP's comment and edited question) You can do that too. See below:
def with_divisible(n, a, b, f):
it = (i for i in xrange(a, b) if not i % n)
for i in wrapper(it):
f(i)
>>> with_divisible(1, 1, 1, lambda x: x)
Traceback (most recent call last):
File "<pyshell#55>", line 1, in <module>
with_divisible(1, 1, 1, lambda x: x)
File "<pyshell#54>", line 3, in with_divisible
for i in wrapper(it):
File "<pyshell#46>", line 4, in wrapper
raise EmptyIterableException("Empty")
EmptyIterableException: Empty
>>> with_divisible(7, 1, 21, lambda x: x)
7
14
...Snipped...
raise EmptyIterableException("Empty")
EmptyIterableException: Empty
Original Answer
Interesting problem. I did some experiments and came up with the following:
class EmptyIterableException(Exception):
pass
def wrapper(iterable):
for each in iterable:
yield each
raise EmptyIterableException("Empty")
try:
for each in wrapper(iterable):
do_something(each)
except EmptyIterableException, e:
do_something_else()
A:
if not map(do_something_callable,iterable) :
# do something else
A:
The general way forward if an iterator is to be partially checked before being consumed is to use itertools.tee. This way we can have two copies of the iterator and check one for emptiness while still consuming the other copy from the start.
from itertools import tee
it1, it2 = tee(iterable)
try:
it1.next()
for i in it2:
do_some_action(i) #iterator is not empty
except StopIteration:
do_empty_action() #iterator is empty
The StopIteration exception is bound to be a result of the call to it1.next(), as any StopIteration exceptions raised froom inside the loop will terminate that loop.
Edit: for those who don't like such exceptions, islice can be used to set up a single step loop:
from itertools import tee, islice
it1, it2 = tee(iterable)
for _ in islice(it1, 1):
#loop entered if iterator is not empty
for i in it2:
do_some_action(i)
break #if loop entered don't execute the else section
else:
do_empty_action()
I personally prefer the first style. YMMV.
A:
What about reversing "if" and "for":
if iterable:
for i in iterable:
do_something(i)
else:
do_something_else()
OK, this does not work!
Here is an other solution: http://code.activestate.com/recipes/413614-testing-for-an-empty-iterator/
A:
This is a combination of Michael Mrozek's and FM's answers:
def with_divisible(n, a, b, f):
'''apply f to every integer x such that n divides x and a <= x < b'''
it = (i for i in xrange(a, b) if not i % n)
for i in it:
f(i)
try: i # test if `it` was empty
except NameError: print('do something else')
def g(i):
print i,
with_divisible( 3, 1, 10, g) # Prints 3 6 9.
with_divisible(33, 1, 10, g) # Prints "do something else"
A:
Generators have a 'gi_frame' property which is None once the generator is exhausted, but only after StopIteration has been raised. If that's acceptable, here's something you could try:
import types
def do(x, f, f_empty):
if type(x) == types.GeneratorType:
# generators have a 'gi_frame' property,
# which is None once the generator is exhausted
if x.gi_frame:
# not empty
return f(x)
return f_empty(x)
if x:
return f(x)
return f_empty(x)
def nempty(lst):
print lst, 'not empty'
def empty(lst):
print 'Twas empty!'
# lists
do([2,3,4], nempty, empty)
do([], nempty, empty)
# generators
do((i for i in range(5)), nempty, empty)
gen = (i for i in range(1))
gen.next()
try:
gen.next()
except StopIteration:
pass
do(gen, nempty, empty)
| Idiomatic way of taking action on attempt to loop over an empty iterable | Suppose that I am looping over a iterable and would like to take some action if the iterator is empty. The two best ways that I can think of to do this are:
for i in iterable:
# do_something
if not iterable:
# do_something_else
and
empty = True
for i in iterable:
empty = False
# do_something
if empty:
# do_something_else
The first depends on the the iterable being a collection (so useless for when the iterable gets passed into the function/method where the loop is) and the second sets empty on every pass through the loop which seems ugly.
Is there another way that I'm missing or is the second alternative the best? It would be really cool if there was some clause that I could add to the loop statement that would handle this for me much like else makes not_found flags go away.
I am not looking for clever hacks.
I am not looking for solutions that involve a lot of code
I am looking for a simple language feature.
I am looking for a clear and pythonic way to iterate over an iterable and take some action if the iterable is empty that any experienced python programmer will be understand. If I could do it without setting a flag on every iteration, that would be fantastic.
If there is no simple idiom that does this, then forget about it.
| [
"This is quite hackish, but you can delete i and then check if it exists after the loop (if not, the loop never happened):\ntry:\n del i\nexcept NameException: pass\n\nfor i in iterable:\n do_something(i)\n\ntry:\n del i\nexcept NameException:\n do_something_else()\n\nI think that's probably uglier than... | [
3,
3,
2,
2,
1,
0,
0,
0
] | [] | [] | [
"coding_style",
"iterable",
"python"
] | stackoverflow_0003486257_coding_style_iterable_python.txt |
Q:
Writing unittests for a function that returns a hierarchy of objects
I have a function that performs a hierarchical clustering on a list of input vectors. The return value is the root element of an object hierarchy, where each object represents a cluster. I want to test the following things:
Does each cluster contain the correct elements (and maybe other properties as well)?
Does each cluster point to the correct children?
Does each cluster point to the correct parent?
I have two problems here. First, how do I specify the expected output in a readable format. Second, how do I write a test-assertion accepts isomorphic variants of the expected data I provide? Suppose one cluster in the expected hierarchy has two children, A and B. Now suppose that cluster is represented by an object with the properties child1 and child2. I do not care whether child1 corresponds to cluster A or B, just that it corresponds to one of them, and that child2 corresponds to the other. The solution should be somewhat general because I will write several tests with different input data.
Actually my main problem here is to find a way to specify the expected output in a readable and understandable way. Any suggestions?
A:
If there are isomorphic results, you should probably have a predicate that can test for logical equivalence. This would likely be good for your code unit as well as helping to implement the unit test.
This is the core of Manoj Govindan's answer without the string intermediates and since you aren't interested in string intermediates (presumably) then adding them to the test regime would be an unnecessary source of error.
As to the readability issue, you'd need to show what you consider unreadable for a proper answer to be given. Perhaps the equivalence predicate will obviate this.
A:
This is an off-the-top-off-my-head suggestion. It is a bit roundabout as well. Caveat emptor!
First, write a function to create a string representation of a cluster. You will have to write unit tests to ensure that this function works in all cases. The format could be custom or XML (not exactly human friendly but usually easy to work with hierarchical data). You can invoke this function by passing in a cluster: string_representation(cluster).
Second, write a variant of this to generate the same output without passing in an actual cluster. Something like util.test.generate_string_representation('child1', 'child2').
Third, modify your unit test assertions to compare the output of string_representation(cluster) with generate_string_representation('child1', 'child2') as the case may be.
actual = string_representation(f(*args, **kwargs))
expected = generate_string_representation('child1', 'child2')
self.assertEqual(actual, expected)
Make sure that both string functions use the same mechanism to format their output. You don't want to end up chasing minute differences in strings.
Told you, it is quite hackish. I hope others have better answers.
A:
It feels like there maybe some room for breaking your method into smaller pieces. Ones focused on dealing with parsing input and formatting output, could be separate from the actual clustering logic. This way tests around your clustering methods would be fewer and dealing with easily understood and testable data structures like dicts and lists.
| Writing unittests for a function that returns a hierarchy of objects | I have a function that performs a hierarchical clustering on a list of input vectors. The return value is the root element of an object hierarchy, where each object represents a cluster. I want to test the following things:
Does each cluster contain the correct elements (and maybe other properties as well)?
Does each cluster point to the correct children?
Does each cluster point to the correct parent?
I have two problems here. First, how do I specify the expected output in a readable format. Second, how do I write a test-assertion accepts isomorphic variants of the expected data I provide? Suppose one cluster in the expected hierarchy has two children, A and B. Now suppose that cluster is represented by an object with the properties child1 and child2. I do not care whether child1 corresponds to cluster A or B, just that it corresponds to one of them, and that child2 corresponds to the other. The solution should be somewhat general because I will write several tests with different input data.
Actually my main problem here is to find a way to specify the expected output in a readable and understandable way. Any suggestions?
| [
"If there are isomorphic results, you should probably have a predicate that can test for logical equivalence. This would likely be good for your code unit as well as helping to implement the unit test.\nThis is the core of Manoj Govindan's answer without the string intermediates and since you aren't interested in s... | [
2,
0,
0
] | [] | [] | [
"python",
"readability",
"unit_testing"
] | stackoverflow_0003487507_python_readability_unit_testing.txt |
Q:
Using tweepy library with Python in identi.ca
I'm using the tweepy library to make a small news application for my desktop in Python. As I've seen in the main web page: http://github.com/joshthecoder/tweepy it has support for identi.ca but I can't manage to log in correctly. To authenticate I do:
auth = tweepy.BasicAuthHandler(username, password)
api = tweepy.API(host = 'identi.ca/api')
To check if I logged in correctly:
if api.verify_credentials() is False:
print 'Unable to log in, check credentials and server status\n'
return 1
else:
print 'Correctly logged in!\n'
return 0
This always returns 1 :(
Some help please? Thank you! :D
P.D.: Of course, username and password are correct credentials :)
A:
Using just identi.ca as the host and setting api_root to /api would be the correct way to access the identi.ca API, as implied by the tweepy documentation.
| Using tweepy library with Python in identi.ca | I'm using the tweepy library to make a small news application for my desktop in Python. As I've seen in the main web page: http://github.com/joshthecoder/tweepy it has support for identi.ca but I can't manage to log in correctly. To authenticate I do:
auth = tweepy.BasicAuthHandler(username, password)
api = tweepy.API(host = 'identi.ca/api')
To check if I logged in correctly:
if api.verify_credentials() is False:
print 'Unable to log in, check credentials and server status\n'
return 1
else:
print 'Correctly logged in!\n'
return 0
This always returns 1 :(
Some help please? Thank you! :D
P.D.: Of course, username and password are correct credentials :)
| [
"Using just identi.ca as the host and setting api_root to /api would be the correct way to access the identi.ca API, as implied by the tweepy documentation.\n"
] | [
1
] | [] | [] | [
"python",
"tweepy"
] | stackoverflow_0003488738_python_tweepy.txt |
Q:
Bandwidth throttling in Python
What libraries out there let you control the download speed of network requests (http in particular). I don't see anything built-in in urllib2 (nor in (Py)Qt which I intend on using).
Can Twisted control bandwidth? If not, how can I control the read buffer size of urllib2 or Twisted? sleeping to suspend network operations isn't an option.
A:
urllib2 doesn't offer a way to do this, so you'd have to extend some of the classes it uses and implement rate limiting yourself. You might want to look at this question. If you decide to write a limiter, read up on the token bucket and leaky bucket algorithms.
Some attempted hack solutions available on github are Phredward/throttle and minkustree/socket-throttle.
Alternatively, you could use pycurl along with the CURLOPTMAXRECVSPEEDLARGE option.
EDIT: The urlgrabber package appears to support throttling as well, and is probably easier to understand than pycurl.
If you prefer to program using an event loop model, there's the Twisted approach, which has already been mentioned in another answer.
A:
Of course twisted can. You want twisted.protocols.policies.ThrottlingFactory. Just wrap your existing factory in it before you pass it to whatever wants a factory.
| Bandwidth throttling in Python | What libraries out there let you control the download speed of network requests (http in particular). I don't see anything built-in in urllib2 (nor in (Py)Qt which I intend on using).
Can Twisted control bandwidth? If not, how can I control the read buffer size of urllib2 or Twisted? sleeping to suspend network operations isn't an option.
| [
"urllib2 doesn't offer a way to do this, so you'd have to extend some of the classes it uses and implement rate limiting yourself. You might want to look at this question. If you decide to write a limiter, read up on the token bucket and leaky bucket algorithms.\nSome attempted hack solutions available on github ... | [
9,
8
] | [] | [] | [
"network_programming",
"networking",
"python"
] | stackoverflow_0003488616_network_programming_networking_python.txt |
Q:
A more suitable way to rewrite this?
I have the method:
def checkAgainstDate():
currentDate = date.today()
currentMonth = date.today().month
if currentMonth == 1
year = currentDate.year-1
return date(year, 11, 01)
elif currentMonth == 2:
year = currentDate.year-1
return date(year, 12, 01)
else
return date(currentDate.year, currentMonth-2, 01)
This just returns the first of the month 2 months ago, which is what I want is there a better approach I could have used using timedeltas? I choose my way because weeks in a month are not always constant.
A:
dateutil is an amazing thing. It really should become stdlib someday.
>>> from dateutil.relativedelta import relativedelta
>>> from datetime import datetime
>>> (datetime.now() - relativedelta(months=2)).replace(day=1)
datetime.datetime(2010, 6, 1, 13, 16, 29, 643077)
>>> (datetime(2010, 4, 30) - relativedelta(months=2)).replace(day=1)
datetime.datetime(2010, 2, 1, 0, 0)
>>> (datetime(2010, 2, 28) - relativedelta(months=2)).replace(day=1)
datetime.datetime(2009, 12, 1, 0, 0)
A:
Convert to an "absolute month number", subtract 2, convert back to year & month:
currentdate = date.today()
monthindex = 12*currentdate.year + (currentdate.month-1) -2
return datetime( monthindex // 12, monthindex % 12 + 1, 1)
| A more suitable way to rewrite this? | I have the method:
def checkAgainstDate():
currentDate = date.today()
currentMonth = date.today().month
if currentMonth == 1
year = currentDate.year-1
return date(year, 11, 01)
elif currentMonth == 2:
year = currentDate.year-1
return date(year, 12, 01)
else
return date(currentDate.year, currentMonth-2, 01)
This just returns the first of the month 2 months ago, which is what I want is there a better approach I could have used using timedeltas? I choose my way because weeks in a month are not always constant.
| [
"dateutil is an amazing thing. It really should become stdlib someday.\n>>> from dateutil.relativedelta import relativedelta\n>>> from datetime import datetime\n>>> (datetime.now() - relativedelta(months=2)).replace(day=1)\ndatetime.datetime(2010, 6, 1, 13, 16, 29, 643077)\n>>> (datetime(2010, 4, 30) - relativedelt... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003489028_python.txt |
Q:
How can I make an http request without getting back an http response in Python?
I want to send it and forget it. The http rest service call I'm making takes a few seconds to respond. The goal is to avoid waiting those few seconds before more code can execute.
I'd rather not use python threads
I'll use twisted async calls if I must and ignore the response.
A:
You are going to have to implement that asynchronously as HTTP protocol states you have a request and a reply.
Another option would be to work directly with the socket, bypassing any pre-built module. This would allow you to violate protocol and write your own bit that ignores any responses, in essence dropping the connection after it has made the request.
A:
HTTP implies a request and a reply for that request. Go with an async approach.
A:
You do not need twisted for this, just urllib will do. See http://pythonquirks.blogspot.com/2009/12/asynchronous-http-request.html
I am copying the relevant code here but the credit goes to that link:
import urllib2
class MyHandler(urllib2.HTTPHandler):
def http_response(self, req, response):
return response
o = urllib2.build_opener(MyHandler())
o.open('http://www.google.com/')
| How can I make an http request without getting back an http response in Python? | I want to send it and forget it. The http rest service call I'm making takes a few seconds to respond. The goal is to avoid waiting those few seconds before more code can execute.
I'd rather not use python threads
I'll use twisted async calls if I must and ignore the response.
| [
"You are going to have to implement that asynchronously as HTTP protocol states you have a request and a reply. \nAnother option would be to work directly with the socket, bypassing any pre-built module. This would allow you to violate protocol and write your own bit that ignores any responses, in essence dropping ... | [
1,
0,
0
] | [] | [] | [
"http",
"python"
] | stackoverflow_0003486372_http_python.txt |
Q:
Google App Engine - Naked Domain Path Redirect in Python
I'm working on a site, colorurl.com, and I need users to be able to type in colorurl.com/00ff00 (or some variation of that), and see the correct page. However, with the naked domain issue, users who type in colorurl.com/somepath will instead be redirected to www.colorurl.com/.
Is there a way to detect this in python, and then redirect the user to where they meant to go (With the www. added?)
EDIT:
Clarification: In my webhost's configuration I have colorurl.com forward to www.colorurl.com. They do not support keeping the path (1and1). I have to detect the previous path and redirect users to it.
User goes to colorurl.com/path
User is redirected to www.colorurl.com
App needs to detect what the path was.
App sends user to www.colorurl.com/path
A:
What I'd do in this scenario is set up a small site at your naked domain which consists of just a .htaccess file which redirects path and all to www.*:
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^colorurl.com [NC]
RewriteRule ^(.*)$ http://www.colorurl.com/$1 [L,R=301]
A:
You need to use a third-party site to do the redirection to www.*; many registrars offer this service. Godaddy's service (which is even free with domain registration) forwards foo.com/bar to www.foo.com/bar; I can't speak to the capabilities of the others but it seems to me that any one that doesn't behave this way is broken.
| Google App Engine - Naked Domain Path Redirect in Python | I'm working on a site, colorurl.com, and I need users to be able to type in colorurl.com/00ff00 (or some variation of that), and see the correct page. However, with the naked domain issue, users who type in colorurl.com/somepath will instead be redirected to www.colorurl.com/.
Is there a way to detect this in python, and then redirect the user to where they meant to go (With the www. added?)
EDIT:
Clarification: In my webhost's configuration I have colorurl.com forward to www.colorurl.com. They do not support keeping the path (1and1). I have to detect the previous path and redirect users to it.
User goes to colorurl.com/path
User is redirected to www.colorurl.com
App needs to detect what the path was.
App sends user to www.colorurl.com/path
| [
"What I'd do in this scenario is set up a small site at your naked domain which consists of just a .htaccess file which redirects path and all to www.*:\nOptions +FollowSymLinks \nRewriteEngine on \nRewriteCond %{HTTP_HOST} ^colorurl.com [NC] \nRewriteRule ^(.*)$ http://www.colorurl.com/$1 [L,R=301]\n\n",
"You ne... | [
4,
0
] | [] | [] | [
"google_app_engine",
"python",
"redirect"
] | stackoverflow_0003482152_google_app_engine_python_redirect.txt |
Q:
Programming Language: What language has both Python & Ruby features?
I came across this great comparison chart between Python & Ruby.
I'm looking for a programming language that is truly a blend between Python and Ruby (with a slight lean towards Python).
I really like in Ruby that everything is an object (unlike Python). However, I really like in Python that things are immutable, so that code maintenance is much easier as well as built-in Unicode support (unlike Ruby).
Does anyone know of a good programming languages that has the best of both Python and Ruby.
I've attempted to make a feature listing below.
Language Features
Everything's an Object YES***
Namespaces yes
Constants YES***
Generators yes
Iterators yes
Coroutines yes
Continuations no
Classes
Multiple Inheritance NO***
Interfaces no
Class Includes* no
Nested Classes yes
Properties yes
Operator Overloading yes
Functions
First-Class Functions yes
Anonymous Functions yes
Keyword Arguments yes
Closures yes
Decorators yes
Collection Objects
Tuples NO***
Lists yes
Hashes yes
Strings
String Type yes
Char Type no
Symbol Type no
Immutable yes
Interned yes
Heredocs no
Multiline Strings yes
Unicode Support yes
Regular Expressions
Regex Literal no
Named Groups yes
Lookaheads yes
Lookbehinds yes
Yes/No Pattern yes
Unicode Support yes
Lua looks interesting, though I'm having a difficult time finding enough information on it to determine if it's a good middle language between Python and Ruby.
A:
I don't understand what you mean by "everything is an object", as far as I know Python has no primitives either (you can derive from the basic integer type in Python 3 for example.)
I've used both, and although I prefer Python, Ruby is no doubt a very potent language, so instead of going by a chart, install both and see which you prefer programming in. If you still can't decide, look at the surrounding environment (how good is the standard library, tools, docs etc.)
Ruby and Python has different "idioms", and underlying philosophies which most probably differs on some points, which might be worth investigating.
A:
Check out groovy. Also it has great feature that have Python and Ruby and some other popular langages, but most of dynamic languages lacks - IDE support ( by NetBeans, Eclipse and IDEA ).
Differences from python and differences from ruby
| Programming Language: What language has both Python & Ruby features? | I came across this great comparison chart between Python & Ruby.
I'm looking for a programming language that is truly a blend between Python and Ruby (with a slight lean towards Python).
I really like in Ruby that everything is an object (unlike Python). However, I really like in Python that things are immutable, so that code maintenance is much easier as well as built-in Unicode support (unlike Ruby).
Does anyone know of a good programming languages that has the best of both Python and Ruby.
I've attempted to make a feature listing below.
Language Features
Everything's an Object YES***
Namespaces yes
Constants YES***
Generators yes
Iterators yes
Coroutines yes
Continuations no
Classes
Multiple Inheritance NO***
Interfaces no
Class Includes* no
Nested Classes yes
Properties yes
Operator Overloading yes
Functions
First-Class Functions yes
Anonymous Functions yes
Keyword Arguments yes
Closures yes
Decorators yes
Collection Objects
Tuples NO***
Lists yes
Hashes yes
Strings
String Type yes
Char Type no
Symbol Type no
Immutable yes
Interned yes
Heredocs no
Multiline Strings yes
Unicode Support yes
Regular Expressions
Regex Literal no
Named Groups yes
Lookaheads yes
Lookbehinds yes
Yes/No Pattern yes
Unicode Support yes
Lua looks interesting, though I'm having a difficult time finding enough information on it to determine if it's a good middle language between Python and Ruby.
| [
"I don't understand what you mean by \"everything is an object\", as far as I know Python has no primitives either (you can derive from the basic integer type in Python 3 for example.)\nI've used both, and although I prefer Python, Ruby is no doubt a very potent language, so instead of going by a chart, install bot... | [
2,
0
] | [] | [] | [
"lua",
"programming_languages",
"python",
"ruby"
] | stackoverflow_0003489339_lua_programming_languages_python_ruby.txt |
Q:
Is it possible to test Google App Engine OpenID authentication on development Server?
I'm trying OpenID support for Google App Engine on a small project i have on my machine but when i call:
users.create_login_url(federated_identity = provider_url)
i get this error:
google_appengine/google/appengine/api/user_service_pb.py", line 178, in ByteSize
n += self.lengthString(len(self.destination_url_))
TypeError: object of type 'NoneType' has no len()
provider_url is https://www.google.com/accounts/o8/id
any clue?
A:
You should normally pass a dest_url parameter to create_login_url, unless you're certain that there is a "current request" whose url you want to use instead. Apparently, the latter condition does not obtain, so the destination url stays None, which causes the problem you're observing. Passing an explicit dest_url should fix it.
| Is it possible to test Google App Engine OpenID authentication on development Server? | I'm trying OpenID support for Google App Engine on a small project i have on my machine but when i call:
users.create_login_url(federated_identity = provider_url)
i get this error:
google_appengine/google/appengine/api/user_service_pb.py", line 178, in ByteSize
n += self.lengthString(len(self.destination_url_))
TypeError: object of type 'NoneType' has no len()
provider_url is https://www.google.com/accounts/o8/id
any clue?
| [
"You should normally pass a dest_url parameter to create_login_url, unless you're certain that there is a \"current request\" whose url you want to use instead. Apparently, the latter condition does not obtain, so the destination url stays None, which causes the problem you're observing. Passing an explicit dest_... | [
6
] | [] | [] | [
"google_app_engine",
"openid",
"python"
] | stackoverflow_0003489488_google_app_engine_openid_python.txt |
Q:
Can't figure out how to invoke cProfile inside of a program
Sorry for the beginner question, but I can't figure out cProfile (I'm really new to Python)
I can run it via my terminal with:
python -m cProfile myscript.py
But I need to run it on a webserver, so I'd like to put the command within the script it will look at. How would I do this? I've seen stuff using terms like __init__ and __main__ but I dont really understand what those are.
I know this is simple, I'm just still trying to learn everything and I know there's someone who will know this.
Thanks in advance! I appreciate it.
A:
I think you've been seeing ideas like this:
if __name__ == "__main__":
# do something if this script is invoked
# as python scriptname. Otherwise, gets ignored.
What happens is when you call python on a script, that file has an attribute __name__ set to "__main__" if it is the file being directly called by the python executable. Otherwise, (if it is not directly called) it is imported.
Now, you can use this trick on your scripts if you need to, for example, assuming you have:
def somescriptfunc():
# does something
pass
if __name__ == "__main__":
# do something if this script is invoked
# as python scriptname. Otherwise, gets ignored.
import cProfile
cProfile.run('somescriptfunc()')
This changes your script. When imported, its member functions, classes etc can be used as normal. When run from the command-line, it profiles itself.
Is this what you're looking for?
From the comments I've gathered more is perhaps needed, so here goes:
If you're running a script from CGI changes are it is of the form:
# do some stuff to extract the parameters
# do something with the parameters
# return the response.
When I say abstract out, you can do this:
def do_something_with_parameters(param1, param2):
pass
if __name__ = "__main__":
import cProfile
cProfile.run('do_something_with_parameters(param1=\'sometestvalue\')')
Put that file on your python path. When run itself, it will profile the function you want profiling.
Now, for your CGI script, create a script that does:
import {insert name of script from above here}
# do something to determine parameter values
# do something with them *via the function*:
do_something_with_parameters(param1=..., param2=...)
# return something
So your cgi script just becomes a little wrapper for your function (which it is anyway) and your function is now self-testing.
You can then profile the function using made up values on your desktop, away from the production server.
There are probably neater ways to achieve this, but it would work.
| Can't figure out how to invoke cProfile inside of a program | Sorry for the beginner question, but I can't figure out cProfile (I'm really new to Python)
I can run it via my terminal with:
python -m cProfile myscript.py
But I need to run it on a webserver, so I'd like to put the command within the script it will look at. How would I do this? I've seen stuff using terms like __init__ and __main__ but I dont really understand what those are.
I know this is simple, I'm just still trying to learn everything and I know there's someone who will know this.
Thanks in advance! I appreciate it.
| [
"I think you've been seeing ideas like this:\nif __name__ == \"__main__\":\n # do something if this script is invoked\n # as python scriptname. Otherwise, gets ignored.\n\nWhat happens is when you call python on a script, that file has an attribute __name__ set to \"__main__\" if it is the file being directly... | [
5
] | [] | [] | [
"cprofile",
"profiler",
"python",
"time"
] | stackoverflow_0003489769_cprofile_profiler_python_time.txt |
Q:
list index out of range error received
hey guys, beginner here. I have written a program that outputs files to .txt's and am using another to read them and use them. i have used a list to store these values (len(..) gives me 100 for all files). However, whenever i run this:
for w in range(1,20): # i want files file01-file20 excluding file00
for x in range(100):
c=c+1 #counter to keep list position on f=0
exec "f=open('file%02d.txt','r').readlines()"%w #stores data from file00,file01,file02...
f00=open('file00.txt','r').readlines() #same as ^ but from file00
for y in range(100):
xvp=float(f[c].rstrip('\n')) #the error is on this line; the file are stored in vertical order
pvp=float(f00[y].rstrip('\n')) #maybe even this one
#and i do stuff with those values...
I get in line 12,
xvp=float(f[c].rstrip('\n'))
IndexError: list index out of range
note: there are 100 numbers stored on separate lines in the .txt's
please, if there is any way to help you help me, let me know
thanks
A:
You seem to be incrementing c two thousand times (20 times 100 -- actually only 1900 times, since range(1,20) will not reach the value 20, as you seem to desire in a comment) -- so of course you're going out of range if you use it to index a list of 100! The whole code is rather a mess and I suggest refactoring it radically, to avoid exec and do things the Python way. Assuming Python 2.6 or better (in 2.5, you need a from __future__ import with_statement at the start of your module):
f00 = open('file00.txt').readlines()
for w in range(1, 21):
for x in range(100):
with open('file%02d.txt' % w) as f:
for line in f:
xvp = float(line)
for line00 in f00:
rvp = float(line00)
do_stuff(xvp, rvp)
I don't know if this is the logic you want -- coupling every line of file00.txt with each line from the 20 other files -- but at least this makes it clear which lines are coupled up with which;-). If what you want is to only couple the first line of file00.txt with the first line from each of the others, then second line with second lines, etc, then add import itertools at the start of your module and change the contents of the with into:
for line00, line in itertools.izip(f00, f):
rvp = float(line00)
xvp = float(line)
do_stuff(xvp, rvp)
and so forth.
Note that I'm reading all of file00.txt in memory once and for all (into the f00 list of lines) because apparently you need to loop on those contents more than once, but that's not needed for the other files.
An obvious optimization is to convert file00.txt's lines to floats only once, replacing the f00 = statement with
with open('file00.txt') as f:
rvps = [float(line) for line in f]
then use rvps directly instead of repeating the conversion every time on the strings in f00 -- for example, in the second version (the one using itertools.izip):
for rvp, line in itertools.izip(rvps, f):
xvp = float(line)
do_stuff(xvp, rvp)
Edit: I see I've done a number of tiny enhancements while hardly realizing I was doing so, maybe I'd better explain them;-). No need to pass 'r' when opening a file for reading (can't hurt, but it's quite idiomatic to omit it). No need to strip trailing (or for that matter leading) whitespace from a string before calling float on it -- float happily skips all such leading and trailing whitespace itself. I did fix what apparently was another bug (you'd never deal with file20.txt) by fixing the applicable range to range(1, 21).
The with open(...) as f: statements do the opening, bind name f to the open file object, and, as soon as the block of statements they control is finished, guarantee that the file is properly closed -- it should almost invariably be used in preference to a stand-alone open, because ensuring all files are closed ASAP is really very good practice (the with statement has many other excellent use cases, but this is the single most frequent one, and the only one that happens to be necessary for this functionality).
Looping directly on an open file object f (provided the file is opened in text mode, as is the default and applies throughout here), for line in f:, provides one after the other the lines of f (without ever needing to keep them all in memory at once) and is an extremely popular and good Pythonic idiom.
The construct rvps = [float(line) for line in f], which I use in my recommended optimization, is known as a "list comprehension" and it's a nicely speedy and compact alternative to a loop that builds a new list.
itertools.izip, given a number of iterables, provides a single iterable whose items are tuples made by the items of the other iterables "walked in lockstep". The built-in zip is similar, but (in Python 2) it builds a list in memory, which itertools.izip avoids, so it's good practice to learn to use the itertools version to avoid wasting memory (not really important for small files like the ones you have, but good habits are best learned and "just applied" rather than having to reflect on them every single time -- just one one doesn't start every morning pondering whether one should brush one's teeth, but just goes and does so as a matter of good habit;-).
I'm sure there's more, but this is what comes to mind off-hand - feel free to ask if I can be of further assistance!
A:
there are 100 numbers stored on
separate lines in the .txt's
but in
for w in range(1,20): # i want files file01-file20 excluding file00
for x in range(100):
c=c+1 #counter to keep list position on f=0
you incrementing c by 20*100 = 2000 times.
Maybe you need c = 0 in "w" cycle or just use x instead of c?
A:
Based on how you describe your files, you are indexing into them incorrectly. By using c which is incremented for each iteration of the second loop. It will reach values of up to 2000. Using x seems to be the logical choice.
#restructured for efficiency
file = open('file00.txt','r')
f00 = file.readlines() #no need to reopen the file for every iteration
file.close() #always close the file when done with
for w in range(1,20):
file = open('file%02d.txt'%w,'r')
f = file.readlines() #only open once per iteration
file.close()
for x in range(100):
xvp = float(f[x].rstrip('\n'))
for y in range(100):
pvp = float(f00[y].rstrip('\n'))
#do stuff
| list index out of range error received | hey guys, beginner here. I have written a program that outputs files to .txt's and am using another to read them and use them. i have used a list to store these values (len(..) gives me 100 for all files). However, whenever i run this:
for w in range(1,20): # i want files file01-file20 excluding file00
for x in range(100):
c=c+1 #counter to keep list position on f=0
exec "f=open('file%02d.txt','r').readlines()"%w #stores data from file00,file01,file02...
f00=open('file00.txt','r').readlines() #same as ^ but from file00
for y in range(100):
xvp=float(f[c].rstrip('\n')) #the error is on this line; the file are stored in vertical order
pvp=float(f00[y].rstrip('\n')) #maybe even this one
#and i do stuff with those values...
I get in line 12,
xvp=float(f[c].rstrip('\n'))
IndexError: list index out of range
note: there are 100 numbers stored on separate lines in the .txt's
please, if there is any way to help you help me, let me know
thanks
| [
"You seem to be incrementing c two thousand times (20 times 100 -- actually only 1900 times, since range(1,20) will not reach the value 20, as you seem to desire in a comment) -- so of course you're going out of range if you use it to index a list of 100! The whole code is rather a mess and I suggest refactoring i... | [
4,
1,
1
] | [] | [] | [
"debugging",
"list",
"python"
] | stackoverflow_0003489756_debugging_list_python.txt |
Q:
Automatically readdress all variables referring to an object
Suppose I have in python this object
class Foo:
def __init__(self, val):
self.val = val
and these two variables
a=Foo(5)
b=a
both b and a refer to the same instance of Foo(), so any modification to the attribute .val will be seen equally and synchronized as a.val and b.val.
>>> b.val
5
>>> b.val=3
>>> a.val
3
Now suppose I want to say a=Foo(7). This will create another instance of Foo, so now a and b are independent.
My question is: is there a way to have b readdressed automatically to the new Foo() instance, without using an intermediate proxy object? It's clearly not possible with the method I presented, but maybe there's some magic I am not aware of.
A:
As Aaron points out, there may be very hacky and fragile solutions but there is likely nothing that would be guaranteed to work across all Python implementations (e.g. CPython, IronPython, Jython, PyPy, etc). But why would one realistically want to do something that is so contrary to the design and idiomatic use of the language when there are simple idiomatic solutions available? Calling a class object typically returns an instance object. Names are bound to that object. Rather than trying to fight the language by coming up with hacks to track down references to objects in order to update bindings, the natural thing would be to design a mutable instance object, if necessary using a simple wrapper around an existing class.
A:
Updated for aaronasterling:
for d in gc.get_referrers(old):
if isinstance(d,list):
new_list = [ new if item is old else item for item in d]
while d: del d[-1]
d.extend(new_list)
elif isinstance(d,dict):
try:
for item in d:
if d[item] is old: d[item] = new
except Exception:pass
else: print('cant handle referrer at %i' % id(d))
Also you dont need to readdress reference to make it's instance equal to some other object.
You can just write
new.__dict__ = old.__dict__
new.__class__ = old.__class__
But this will work only with not-built-in class instances.
A:
update:
I figured out how to make it work with tuples. This is basically Odomontois' solution with some type checking removed and made recursive for tuples.
import gc
import inspect
def update(obj, value):
objects = gc.get_referrers(obj)
old = obj # this protects our reference to the initial object
for o in objects:
if hasattr(o, '__iter__') and hasattr(o, 'extend'): # list like objects
new_list = [value if item is old else item for item in o]
while o: del o[-1]
o.extend(new_list)
elif hasattr(o, '__iter__') and hasattr(o, 'keys'): # dictionary like objects
for item in o.keys():
if o[item] is old: o[item] = value
elif isinstance(o, set):
o.remove(old)
o.add(value)
elif isinstance(o, tuple):
new_tuple = tuple(value if item is old else item for item in o)
update(o, new_tuple)
elif inspect.isframe(o):
continue
else:
raise Exception("can't handle referrer {0}".format(o))
class Test(object):
def __init__(self, obj):
self.val = obj
a = (1, ) #works
b = a #works
t = Test(b) #works because we this t.__dict__
L = [a] # works
S = set((a, )) # works
T = (a, ) # works
update(a, (2, ))
print a, b, t.val, L, S, T
wrong answer
deleted
A:
Maybe and just maybe you're looking for a Singleton
class Singleton(type):
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls.instance = None
def __call__(cls, *args, **kw):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
return cls.instance
class MyClass(object):
__metaclass__ = Singleton
print MyClass()
print MyClass()
| Automatically readdress all variables referring to an object | Suppose I have in python this object
class Foo:
def __init__(self, val):
self.val = val
and these two variables
a=Foo(5)
b=a
both b and a refer to the same instance of Foo(), so any modification to the attribute .val will be seen equally and synchronized as a.val and b.val.
>>> b.val
5
>>> b.val=3
>>> a.val
3
Now suppose I want to say a=Foo(7). This will create another instance of Foo, so now a and b are independent.
My question is: is there a way to have b readdressed automatically to the new Foo() instance, without using an intermediate proxy object? It's clearly not possible with the method I presented, but maybe there's some magic I am not aware of.
| [
"As Aaron points out, there may be very hacky and fragile solutions but there is likely nothing that would be guaranteed to work across all Python implementations (e.g. CPython, IronPython, Jython, PyPy, etc). But why would one realistically want to do something that is so contrary to the design and idiomatic use ... | [
7,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003489380_python.txt |
Q:
How to remove the things I don't like about Python?
Python is a great programming language, but certain things about it just annoy the heck out of me.
As such, I:
1) wanted to find out how to remove these annoyances from the language itself, or
2) find a language that is Python-like that don't have these annoyances.
I love Python for everything except:
self: just seems stupid to me that I need to include "self" as the first parameter of a function
double-underscores: It just looks ugly and a terrible special character.
__name__ has always felt like a hack to me. Try explaining it to a novice programmer, or worse to someone who programs in perl or ruby or java for a living. Comparing the magic variable name to the magic constant ”main” feels doubly so
Blocks give me of ruby envy or smalltalk envy. I like local functions. Love them. I tolerate lambda. But I really, really would like to see a more rubyesque iterator setup where we pass a callable to the list, and the callable can be defined free-form inline. Python doesn’t really do that and so it’s less of a language lab than I might like.
Properties are unattractive, partly because of blocks being absent. I don’t really want to define a named parameter (with double-underscores, most likely) and then two named functions, and THEN declare a property. That seems like so much work for such a simple situation. It is something I will only do if all other methods fail me, or if all other methods are overriding setattr and getattr.
I do realize this might be petty annoyances, but for a language I program in daily, these small annoyances can grow to be quite large.
A:
pypy is a complete implementation of Python in Python itself (with all of the things you consider annoyances, nevertheless a very high-level implementation language that makes altering even the core of the language itself for your own purposes easier than ever before). Download it, fork it, and edit it to fix whatever you like (be sure to eventually translate the compiler and runtime to your new non-Python language, too, of course).
If that's just too much work (whiners are rarely interested in working to fix their own complaints, no matter how easy you make such work for them), just switch to Ruby, which appears to match your tastes more closely - or find the Ruby implementation written in Ruby (I don't know how it's called, but surely such a powerful language will have one) and hack that one (to fix whatever your whines are against Ruby).
Meanwhile, at least some of your annoyances leave me quite perplexed. Take, for example, the rant about properties: I don't understand what you mean. The normal way to define a R/W property is:
@property
def thename(self):
"""add the geting-code here""
@property.set
def thename(self, value):
"""add the seting-code here""
so what the hey do you mean by
define a named parameter (with
double-underscores, most likely) and
then two named functions, and THEN
declare a property
???
I could ask equally puzzled questions about the other whines, but let's wait to see if you clarify this one first (if the clarification is of the kind "oh I didn't know about it", i.e. you're whining against a language without knowing the fundaments thereof, well, I can make a guess about what that does to your credibility, of course;-).
A:
This is a troll, and you know the answers to your own questions:
self: Write a wrapper that does away with it and inherit from that. But it does need some name if you're going to reference the object in question, unless you just want it to just magically be present (an ugly thing indeed)...
double-underscores: don't use them. Simple. They're in no way required.
_name_: again, call it something else if you like, and inherit from that base class. I don't see what the problem here is. You still need something to provide that function.
Blocks: It sounds to me like you're trying to program ruby or java in python. You can certainly pass a callable to an iterator (and you should probably go read about generators), but defining it inline leads to serious code ugliness fast. Python makes you do it out of line so that you don't end up with half your program logic in an inline, unnamed function. I don't see what the problem here is.
Properties: I don't understand what you're saying. I certainly don't define multiple functions to use or create properties of an object in most cases.
A:
How about trying back to the basics using UNIX bash scripts?
| How to remove the things I don't like about Python? | Python is a great programming language, but certain things about it just annoy the heck out of me.
As such, I:
1) wanted to find out how to remove these annoyances from the language itself, or
2) find a language that is Python-like that don't have these annoyances.
I love Python for everything except:
self: just seems stupid to me that I need to include "self" as the first parameter of a function
double-underscores: It just looks ugly and a terrible special character.
__name__ has always felt like a hack to me. Try explaining it to a novice programmer, or worse to someone who programs in perl or ruby or java for a living. Comparing the magic variable name to the magic constant ”main” feels doubly so
Blocks give me of ruby envy or smalltalk envy. I like local functions. Love them. I tolerate lambda. But I really, really would like to see a more rubyesque iterator setup where we pass a callable to the list, and the callable can be defined free-form inline. Python doesn’t really do that and so it’s less of a language lab than I might like.
Properties are unattractive, partly because of blocks being absent. I don’t really want to define a named parameter (with double-underscores, most likely) and then two named functions, and THEN declare a property. That seems like so much work for such a simple situation. It is something I will only do if all other methods fail me, or if all other methods are overriding setattr and getattr.
I do realize this might be petty annoyances, but for a language I program in daily, these small annoyances can grow to be quite large.
| [
"pypy is a complete implementation of Python in Python itself (with all of the things you consider annoyances, nevertheless a very high-level implementation language that makes altering even the core of the language itself for your own purposes easier than ever before). Download it, fork it, and edit it to fix wha... | [
7,
2,
0
] | [] | [] | [
"programming_languages",
"python"
] | stackoverflow_0003489929_programming_languages_python.txt |
Q:
Using cProfile or line_profile on a Python script in /cgi-bin/?
Is there a way to run cProfile or line_profile on a script on a server?
ie: how could I get the results for one of the two methods on http://www.Example.com/cgi-bin/myScript.py
Thanks!
A:
Not sure what line_profile is. For cProfile, you just need to direct the results to a file you can later read on the server (depending on what kind of access you have to the server).
To quote the example from the docs,
import cProfile
cProfile.run('foo()', 'fooprof')
and put all the rest of the code into a def foo(): -- then later retrieve that fooprof file and analyze it at leisure (assuming your script runs with permissions to write it in the first place, of course).
Of course you can ensure different runs get profiled into different files, etc, etc -- whether this is practical also depends on what kind of access and permissions you're getting from your hosting provider, i.e., how are you allowed to persist data, in a way that lets you retrieve that data later? That's not a question of Python, it's a question of contracts between you and your hosting provider;-).
| Using cProfile or line_profile on a Python script in /cgi-bin/? | Is there a way to run cProfile or line_profile on a script on a server?
ie: how could I get the results for one of the two methods on http://www.Example.com/cgi-bin/myScript.py
Thanks!
| [
"Not sure what line_profile is. For cProfile, you just need to direct the results to a file you can later read on the server (depending on what kind of access you have to the server).\nTo quote the example from the docs,\nimport cProfile\ncProfile.run('foo()', 'fooprof')\n\nand put all the rest of the code into a ... | [
1
] | [] | [] | [
"cgi_bin",
"cprofile",
"python",
"time"
] | stackoverflow_0003489932_cgi_bin_cprofile_python_time.txt |
Q:
App Engine - Output Response Time
Say I wanted to print the response time on my pages like Google do.
How would I go about doing this?
A:
Call start = time.time() as the very first operation in your handling scripts, and, when you're just about done with everything, as the very last thing you output use (a properly formatted version of) time.time() - start.
If you're using templates for your output (e.g., the Django templates that come with app engine -- 0.96 by default, though you can explicitly ask for newer and better ones;-), or jinja2, mako, ...), it's important to be able to use in those templates a tag or filter to request and format such an expression. (You don't want to compute it at the time you call the template's render method, and pass it as part of that method's context, or else you'll fail to account for all the template rendering time in your estimate of "response time"!-). You may have to code and inject such a tag or filter into the "templating language" if your chosen templating language and version doesn't already supply one but is at least minimally extensible;-).
`
| App Engine - Output Response Time | Say I wanted to print the response time on my pages like Google do.
How would I go about doing this?
| [
"Call start = time.time() as the very first operation in your handling scripts, and, when you're just about done with everything, as the very last thing you output use (a properly formatted version of) time.time() - start.\nIf you're using templates for your output (e.g., the Django templates that come with app eng... | [
3
] | [] | [] | [
"google_app_engine",
"performance",
"python"
] | stackoverflow_0003489968_google_app_engine_performance_python.txt |
Q:
Why does Python require the "self" parameter?
Possible Duplicates:
python ‘self’ explained
Why do you need explicitly have the “self” argument into a Python method?
Why does Python require the "self" parameter for methods?
For example def method_abc(self, arg1)
And is there ever a date that the need for it will be removed?
A:
Python gives you the option of naming it something other than self, even though the standard is to name it self. Just as it gives you the option of using tabs for indents, even though the standard is to use spaces.
In other words, it's not just "assumed" because...
To give you naming flexibility
To make it clearer that something will be passed self (or not).
| Why does Python require the "self" parameter? |
Possible Duplicates:
python ‘self’ explained
Why do you need explicitly have the “self” argument into a Python method?
Why does Python require the "self" parameter for methods?
For example def method_abc(self, arg1)
And is there ever a date that the need for it will be removed?
| [
"Python gives you the option of naming it something other than self, even though the standard is to name it self. Just as it gives you the option of using tabs for indents, even though the standard is to use spaces.\nIn other words, it's not just \"assumed\" because...\n\nTo give you naming flexibility\nTo make it ... | [
0
] | [] | [] | [
"programming_languages",
"python"
] | stackoverflow_0003490017_programming_languages_python.txt |
Q:
How to install/organize python modules on a mac?
I have a mbp, but I've been lazy and have been using ubuntu for my python development thus far b/c its so easy to install modules etc.
How do you install modules on a mac? And best-practises with storing all .py files?
A:
One of the perks of using high level languages is that they function mostly the same on each platform they support. Python is no diffent. You install modules the same way you do on Linux: using easy_install or pip, check them out http://pypi.python.org/pypi/setuptools http://pypi.python.org/pypi/pip
A:
See my lengthy answer to a similar question here. Bottom line, if you are familiar and comfortable with a package-managed environment like on Ubuntu, you may want to use a package manager like MacPorts or Fink or Homebrew on OS X. But there are subtle differences since, unlike Ubuntu, this is not the system-wide package manager so you have to be aware of and co-exist with things supplied by Apple in OS X or by having multiple Python installations.
| How to install/organize python modules on a mac? | I have a mbp, but I've been lazy and have been using ubuntu for my python development thus far b/c its so easy to install modules etc.
How do you install modules on a mac? And best-practises with storing all .py files?
| [
"One of the perks of using high level languages is that they function mostly the same on each platform they support. Python is no diffent. You install modules the same way you do on Linux: using easy_install or pip, check them out http://pypi.python.org/pypi/setuptools http://pypi.python.org/pypi/pip\n",
"See my ... | [
0,
0
] | [] | [] | [
"installation",
"python"
] | stackoverflow_0003489646_installation_python.txt |
Q:
Does python have a ruby installer like gem that lets you install modules from the command line even if they are not on your machine?
With Ruby you can do gem install from the command line to install a module...even if it is not on your machine.
Can you do that with python. Does someone know of a module?
Seth
A:
no it does not have a ruby installer that I know of. It does have easy_install and pip though. Your google-fu is lacking.
A:
There's setuptools, which allows you to install packages from PyPi via easy_install. Another option is pip, which also installs from PyPi.
| Does python have a ruby installer like gem that lets you install modules from the command line even if they are not on your machine? | With Ruby you can do gem install from the command line to install a module...even if it is not on your machine.
Can you do that with python. Does someone know of a module?
Seth
| [
"no it does not have a ruby installer that I know of. It does have easy_install and pip though. Your google-fu is lacking.\n",
"There's setuptools, which allows you to install packages from PyPi via easy_install. Another option is pip, which also installs from PyPi.\n"
] | [
4,
3
] | [] | [] | [
"python",
"rubygems"
] | stackoverflow_0003490543_python_rubygems.txt |
Q:
How to display and tag a region of an image with python
I'm used to writing python scripts that interact with files, data and databases but I haven't done user-interfaces.
For my current project, I want to show an image (jpg/gif/png) to a user so it can be region-tagged. Region-tags are not just information about the image (like location or has/doesn't have people in it) but about the contents and where they are in the image.
I would like to have the user select the tag, draw a rectangle and then store the x.y coordinates of the start and end corners of the rectangle. Almost all images have one of five different tags so the process could be a button for the tag I want, then draw the rectangle over the image, agree or redo the selection and store the data when done.
I would like to get starting pointers to python GUI tools which would enable me to do this image manipulation.
A:
Python has bindings for may GUI toolkits which can allow you to display an image and interact with it in any way you want. A binding for Tk comes installed with Python. I personally recommend PyQt (a binding to the Qt library), but many people also like wxPython, a binding to wxWindows.
See here for more. Googling will turn up much more information especially on comparison between the various toolkits. There are also SO questions that address this issue - look up for the relevant tags.
| How to display and tag a region of an image with python | I'm used to writing python scripts that interact with files, data and databases but I haven't done user-interfaces.
For my current project, I want to show an image (jpg/gif/png) to a user so it can be region-tagged. Region-tags are not just information about the image (like location or has/doesn't have people in it) but about the contents and where they are in the image.
I would like to have the user select the tag, draw a rectangle and then store the x.y coordinates of the start and end corners of the rectangle. Almost all images have one of five different tags so the process could be a button for the tag I want, then draw the rectangle over the image, agree or redo the selection and store the data when done.
I would like to get starting pointers to python GUI tools which would enable me to do this image manipulation.
| [
"Python has bindings for may GUI toolkits which can allow you to display an image and interact with it in any way you want. A binding for Tk comes installed with Python. I personally recommend PyQt (a binding to the Qt library), but many people also like wxPython, a binding to wxWindows.\nSee here for more. Googlin... | [
1
] | [] | [] | [
"image",
"python",
"tags",
"user_interface"
] | stackoverflow_0003490552_image_python_tags_user_interface.txt |
Q:
Parsing text files using Python
I am very new to Python and am looking to use it to parse a text file. The file has between 250-300 lines of the following format:
---- Mark Grey (mark.grey@gmail.com) changed status from Busy to Available @ 14/07/2010 16:32:36 ----
---- Silvia Pablo (spablo@gmail.com) became Available @ 14/07/2010 16:32:39 ----
I need to store the following information into another file (excel or text) for all the entries from this file
UserName/ID Previous Status New Status Date Time
So my result file should look like this for the above entried
Mark Grey/mark.grey@gmail.com Busy Available 14/07/2010 16:32:36
Silvia Pablo/spablo@gmail.com NaN Available 14/07/2010 16:32:39
Thanks in advance,
Any help would be really appreciated
A:
To get you started:
result = []
regex = re.compile(
r"""^-*\s+
(?P<name>.*?)\s+
\((?P<email>.*?)\)\s+
(?:changed\s+status\s+from\s+(?P<previous>.*?)\s+to|became)\s+
(?P<new>.*?)\s+@\s+
(?P<date>\S+)\s+
(?P<time>\S+)\s+
-*$""", re.VERBOSE)
with open("inputfile") as f:
for line in f:
match = regex.match(line)
if match:
result.append([
match.group("name"),
match.group("email"),
match.group("previous")
# etc.
])
else:
# Match attempt failed
will get you an array of the parts of the match. I'd then suggest you use the csv module to store the results in a standard format.
A:
import re
pat = re.compile(r"----\s+(.*?) \((.*?)\) (?:changed status from (\w+) to|became) (\w+) @ (.*?) ----\s*")
with open("data.txt") as f:
for line in f:
(name, email, prev, curr, date) = pat.match(line).groups()
print "{0}/{1} {2} {3} {4}".format(name, email, prev or "NaN", curr, date)
This makes assumptions about whitespace and also assumes that every line conforms to the pattern. You might want to add error checking (such as checking that pat.match() doesn't return None) if you want to handle dirty input gracefully.
A:
The two RE patterns of interest seem to be...:
p1 = r'^---- ([^(]+) \(([^)]+)\) changed status from (\w+) to (\w+) (\S+) (\S+) ----$'
p2 = r'^---- ([^(]+) \(([^)]+)\) became (\w+) (\S+) (\S+) ----$'
so I'd do:
import csv, re, sys
# assign p1, p2 as above (or enhance them, etc etc)
r1 = re.compile(p1)
r2 = re.compile(p2)
data = []
with open('somefile.txt') as f:
for line in f:
m = p1.match(line)
if m:
data.append(m.groups())
continue
m = p2.match(line)
if not m:
print>>sys.stderr, "No match for line: %r" % line
continue
listofgroups = m.groups()
listofgroups.insert(2, 'NaN')
data.append(listofgroups)
with open('result.csv', 'w') as f:
w = csv.writer(f)
w.writerow('UserName/ID Previous Status New Status Date Time'.split())
w.writerows(data)
If the two patterns I described are not general enough, they may need to be tweaked, of course, but I think this general approach will be useful. While many Python users on Stack Overflow intensely dislike REs, I find them very useful for this kind of pragmatical ad hoc text processing.
Maybe the dislike is explained by others wanting to use REs for absurd uses such as ad hoc parsing of CSV, HTML, XML, ... -- and many other kinds of structured text formats for which perfectly good parsers exist! And also, other tasks well beyond REs' "comfort zone", and requiring instead solid general parser systems like pyparsing. Or at the other extreme super-simple tasks done perfectly well with simple strings (e.g. I remember a recent SO question which used if re.search('something', s): instead of if 'something' in s:!-).
But for the reasonably broad swathe of tasks (excluding the very simplest ones at one end, and the parsing of structured or somewhat-complicated grammars at the other) for which REs are appropriate, there's really nothing wrong with using them, and I recommend to all programmers to learn at least REs' basics.
A:
Alex mentioned pyparsing and so here is a pyparsing approach to your same problem:
from pyparsing import Word, Suppress, Regex, oneOf, SkipTo
import datetime
DASHES = Word('-').suppress()
LPAR,RPAR,AT = map(Suppress,"()@")
date = Regex(r'\d{2}/\d{2}/\d{4}')
time = Regex(r'\d{2}:\d{2}:\d{2}')
status = oneOf("Busy Available Idle Offline Unavailable")
statechange1 = 'changed status from' + status('fromstate') + 'to' + status('tostate')
statechange2 = 'became' + status('tostate')
linefmt = (DASHES + SkipTo('(')('name') + LPAR + SkipTo(RPAR)('email') + RPAR +
(statechange1 | statechange2) +
AT + date('date') + time('time') + DASHES)
def convertFields(tokens):
if 'fromstate' not in tokens:
tokens['fromstate'] = 'NULL'
tokens['name'] = tokens.name.strip()
tokens['email'] = tokens.email.strip()
d,mon,yr = map(int, tokens.date.split('/'))
h,m,s = map(int, tokens.time.split(':'))
tokens['datetime'] = datetime.datetime(yr, mon, d, h, m, s)
linefmt.setParseAction(convertFields)
for line in text.splitlines():
fields = linefmt.parseString(line)
print "%(name)s/%(email)s %(fromstate)-10.10s %(tostate)-10.10s %(datetime)s" % fields
prints:
Mark Grey/mark.grey@gmail.com Busy Available 2010-07-14 16:32:36
Silvia Pablo/spablo@gmail.com NULL Available 2010-07-14 16:32:39
pyparsing allows you to attach names to the results fields (just like the named groups in Tom Pietzcker's RE-styled answer), plus parse-time actions to act on or manipulate the parsed actions - note the conversion of the separate date and time fields into a true datetime object, already converted and ready for processing after parsing with no additional muss nor fuss.
Here is a modified loop that just dumps out the parsed tokens and the named fields for each line:
for line in text.splitlines():
fields = linefmt.parseString(line)
print fields.dump()
prints:
['Mark Grey ', 'mark.grey@gmail.com', 'changed status from', 'Busy', 'to', 'Available', '14/07/2010', '16:32:36']
- date: 14/07/2010
- datetime: 2010-07-14 16:32:36
- email: mark.grey@gmail.com
- fromstate: Busy
- name: Mark Grey
- time: 16:32:36
- tostate: Available
['Silvia Pablo ', 'spablo@gmail.com', 'became', 'Available', '14/07/2010', '16:32:39']
- date: 14/07/2010
- datetime: 2010-07-14 16:32:39
- email: spablo@gmail.com
- fromstate: NULL
- name: Silvia Pablo
- time: 16:32:39
- tostate: Available
I suspect that as you continue to work on this problem, you will find other variations on the format of the input text specifying how the user's state changed. In this case, you would just add another definition like statechange1 or statechange2, and insert it into linefmt with the others. I feel that pyparsing's structuring of the parser definition helps developers come back to a parser after things have changed, and easily extend their parsing program.
A:
Well, if i were to approach this problem, probably I'd start by splitting each entry into its own, separate string. This looks like it might be line oriented, so a inputfile.split('\n') is probably adequate. From there I would probably craft a regular expression to match each of the possible status changes, with subgroups wrapping each of the important fields.
A:
thanks very much for all your comments. They were very useful. I wrote my code using the directory functionality. What it does is it reads through the file and creates an output file for each of the user with all his status updates. Here is the code pasted below.
#Script to extract info from individual data files and print out a data file combining info from these files
import os
import commands
dataFileDir="data/";
#Dictionary linking names to email ids
#For the time being, assume no 2 people have the same name
usrName2Id={};
#User id to user name mapping to check for duplicate names
usrId2Name={};
#Store info: key: user ids and values a dictionary with time stamp keys and status messages values
infoDict={};
#Given an array of space tokenized inputs, extract user name
def getUserName(info,mailInd):
userName="";
for i in range(mailInd-1,0,-1):
if info[i].endswith("-") or info[i].endswith("+"):
break;
userName=info[i]+" "+userName;
userName=userName.strip();
userName=userName.replace(" "," ");
userName=userName.replace(" ","_");
return userName;
#Given an array of space tokenized inputs, extract time stamp
def getTimeStamp(info,timeStartInd):
timeStamp="";
for i in range(timeStartInd+1,len(info)):
timeStamp=timeStamp+" "+info[i];
timeStamp=timeStamp.replace("-","");
timeStamp=timeStamp.strip();
return timeStamp;
#Given an array of space tokenized inputs, extract status message
def getStatusMsg(info,startInd,endInd):
msg="";
for i in range(startInd,endInd):
msg=msg+" "+info[i];
msg=msg.strip();
msg=msg.replace(" ","_");
return msg;
#Extract and store info from each line in the datafile
def extractLineInfo(line):
print line;
info=line.split(" ");
mailInd=-1;userId="-NONE-";
timeStartInd=-1;timeStamp="-NONE-";
becameInd="-1";
statusMsg="-NONE-";
#Find indices of email id and "@" char indicating start of timestamp
for i in range(0,len(info)):
#print (str(i)+" "+info[i]);
if(info[i].startswith("(") and info[i].endswith("@in.ibm.com)")):
mailInd=i;
if(info[i]=="@"):
timeStartInd=i;
if(info[i]=="became"):
becameInd=i;
#Debug print of mail and time stamp start inds
"""print "\n";
print "Index of mail id: "+str(mailInd);
print "Index of time start index: "+str(timeStartInd);
print "\n";"""
#Extract IBM user id and name for lines with ibm id
if(mailInd>=0):
userId=info[mailInd].replace("(","");
userId=userId.replace(")","");
userName=getUserName(info,mailInd);
#Lines with no ibm id are of the form "Suraj Godar Mr became idle @ 15/07/2010 16:30:18"
elif(becameInd>0):
userName=getUserName(info,becameInd);
#Time stamp info
if(timeStartInd>=0):
timeStamp=getTimeStamp(info,timeStartInd);
if(mailInd>=0):
statusMsg=getStatusMsg(info,mailInd+1,timeStartInd);
elif(becameInd>0):
statusMsg=getStatusMsg(info,becameInd,timeStartInd);
print userId;
print userName;
print timeStamp
print statusMsg+"\n";
if not(userName in usrName2Id) and not(userName=="-NONE-") and not(userId=="-NONE-"):
usrName2Id[userName]=userId;
#Store status messages keyed by user email ids
timeDict={};
#Retrieve user id corresponding to user name
if userName in usrName2Id:
userId=usrName2Id[userName];
#For valid user ids, store status message in the dict within dict data str arrangement
if not(userId=="-NONE-"):
if not(userId in infoDict.keys()):
infoDict[userId]={};
timeDict=infoDict[userId];
if not(timeStamp in timeDict.keys()):
timeDict[timeStamp]=statusMsg;
else:
timeDict[timeStamp]=timeDict[timeStamp]+" "+statusMsg;
#Print for each user a file containing status
def printStatusFiles(dataFileDir):
volNum=0;
for userName in usrName2Id:
volNum=volNum+1;
filename=dataFileDir+"/"+"status-"+str(volNum)+".txt";
file = open(filename,"w");
print "Printing output file name: "+filename;
print volNum,userName,usrName2Id[userName]+"\n";
file.write(userName+" "+usrName2Id[userName]+"\n");
timeDict=infoDict[usrName2Id[userName]];
for time in sorted(timeDict.keys()):
file.write(time+" "+timeDict[time]+"\n");
#Read and store data from individual data files
def readDataFiles(dataFileDir):
#Process each datafile
files=os.listdir(dataFileDir)
files.sort();
for i in range(0,len(files)):
#for i in range(0,1):
file=files[i];
#Do not process other non-data files lying around in that dir
if not file.endswith(".txt"):
continue
print "Processing data file: "+file
dataFile=dataFileDir+str(file);
inpFile=open(dataFile,"r");
lines=inpFile.readlines();
#Process lines
for line in lines:
#Clean lines
line=line.strip();
line=line.replace("/India/Contr/IBM","");
line=line.strip();
#Skip header line of the file and L's sign in sign out times
if(line.startswith("System log for account") or line.find("signed")>-1):
continue;
extractLineInfo(line);
print "\n";
readDataFiles(dataFileDir);
print "\n";
printStatusFiles("out/");
| Parsing text files using Python | I am very new to Python and am looking to use it to parse a text file. The file has between 250-300 lines of the following format:
---- Mark Grey (mark.grey@gmail.com) changed status from Busy to Available @ 14/07/2010 16:32:36 ----
---- Silvia Pablo (spablo@gmail.com) became Available @ 14/07/2010 16:32:39 ----
I need to store the following information into another file (excel or text) for all the entries from this file
UserName/ID Previous Status New Status Date Time
So my result file should look like this for the above entried
Mark Grey/mark.grey@gmail.com Busy Available 14/07/2010 16:32:36
Silvia Pablo/spablo@gmail.com NaN Available 14/07/2010 16:32:39
Thanks in advance,
Any help would be really appreciated
| [
"To get you started:\nresult = []\nregex = re.compile(\n r\"\"\"^-*\\s+\n (?P<name>.*?)\\s+\n \\((?P<email>.*?)\\)\\s+\n (?:changed\\s+status\\s+from\\s+(?P<previous>.*?)\\s+to|became)\\s+\n (?P<new>.*?)\\s+@\\s+\n (?P<date>\\S+)\\s+\n (?P<time>\\S+)\\s+\n -*$\"\"\", re.VERBOSE)\nwith open(\... | [
16,
6,
6,
4,
1,
1
] | [] | [] | [
"parsing",
"python"
] | stackoverflow_0003253383_parsing_python.txt |
Q:
Reading files using Python
I have a file of the following format.
"08-10-2010 13:29:31 1 APs were seen
"
"08-10-2010 13:29:31 MAC Address SSID RSSI"
"08-10-2010 13:29:31 00:1e:79:d7:d5:b0 -80"
"08-10-2010 13:30:32 2 APs were seen
"
"08-10-2010 13:30:32 MAC Address SSID RSSI"
"08-10-2010 13:30:32 00:1e:79:d7:d5:40 -93"
"08-10-2010 13:30:32 00:1e:79:d7:d5:b0 -78"
"08-10-2010 13:31:33 2 APs were seen
"
"08-10-2010 13:31:33 MAC Address SSID RSSI"
"08-10-2010 13:31:33 00:1e:79:d7:d5:40 -94"
"08-10-2010 13:31:33 00:1e:79:d7:d5:b0 -79"
"08-10-2010 13:32:34 1 APs were seen
"
"08-10-2010 13:32:34 MAC Address SSID RSSI"
"08-10-2010 13:32:34 00:1e:79:d7:d5:b0 -94"
"08-10-2010 13:33:35 1 APs were seen
"
"08-10-2010 13:33:35 MAC Address SSID RSSI"
"08-10-2010 13:33:35 00:1e:79:d7:d5:b0 -88"
"08-10-2010 13:34:36 1 APs were seen
"
"08-10-2010 13:34:36 MAC Address SSID RSSI"
"08-10-2010 13:34:36 00:1e:79:d7:d5:b0 -82"
As you can see from the copied text, at every instant of time, a computer might see 1 or 2 or 3 (or maybe more) number of APs. I need to create the following file:
1. The file will have a date and time (specified as a datetime object). It needs to go and check the file and return the MAC addresses of the two APs which have the highest RSSI values.
Now as you can see from the file at some times the computer will see only one AP. In that case the function has to return the MAC address of that AP, and "none" as the second return value. When there are more than two APs recorded at that time, then it has to return the highest two.
How would I do this?
A:
http://docs.python.org/library/
Look carefully at sections 10 and 7. They will give you what you need to look at a file and parse it for the information required. Study, post something, whether it works or not, and we'll help you out more.
| Reading files using Python | I have a file of the following format.
"08-10-2010 13:29:31 1 APs were seen
"
"08-10-2010 13:29:31 MAC Address SSID RSSI"
"08-10-2010 13:29:31 00:1e:79:d7:d5:b0 -80"
"08-10-2010 13:30:32 2 APs were seen
"
"08-10-2010 13:30:32 MAC Address SSID RSSI"
"08-10-2010 13:30:32 00:1e:79:d7:d5:40 -93"
"08-10-2010 13:30:32 00:1e:79:d7:d5:b0 -78"
"08-10-2010 13:31:33 2 APs were seen
"
"08-10-2010 13:31:33 MAC Address SSID RSSI"
"08-10-2010 13:31:33 00:1e:79:d7:d5:40 -94"
"08-10-2010 13:31:33 00:1e:79:d7:d5:b0 -79"
"08-10-2010 13:32:34 1 APs were seen
"
"08-10-2010 13:32:34 MAC Address SSID RSSI"
"08-10-2010 13:32:34 00:1e:79:d7:d5:b0 -94"
"08-10-2010 13:33:35 1 APs were seen
"
"08-10-2010 13:33:35 MAC Address SSID RSSI"
"08-10-2010 13:33:35 00:1e:79:d7:d5:b0 -88"
"08-10-2010 13:34:36 1 APs were seen
"
"08-10-2010 13:34:36 MAC Address SSID RSSI"
"08-10-2010 13:34:36 00:1e:79:d7:d5:b0 -82"
As you can see from the copied text, at every instant of time, a computer might see 1 or 2 or 3 (or maybe more) number of APs. I need to create the following file:
1. The file will have a date and time (specified as a datetime object). It needs to go and check the file and return the MAC addresses of the two APs which have the highest RSSI values.
Now as you can see from the file at some times the computer will see only one AP. In that case the function has to return the MAC address of that AP, and "none" as the second return value. When there are more than two APs recorded at that time, then it has to return the highest two.
How would I do this?
| [
"http://docs.python.org/library/\nLook carefully at sections 10 and 7. They will give you what you need to look at a file and parse it for the information required. Study, post something, whether it works or not, and we'll help you out more.\n"
] | [
1
] | [] | [] | [
"file",
"function",
"python"
] | stackoverflow_0003490492_file_function_python.txt |
Q:
Mongodb - are reliability issues significant still?
I have a couple of sqlite dbs (i'd say about 15GBs), with about 1m rows in total - so not super big. I was looking at mongodb, and it looks pretty easy to work with, especially if I want to try and do some basic natural language processing on the documents which make up the databases.
I've never worked with Mongo in the past, no would have to learn from scratch (will be working in python). After googling around a bit, I came across a number of somewhat horrific stories about Mongodb re. reliability. Is this still a major problem ? In a crunch, I will of course retain the sqlite backups, but I'd rather not have to reconstruct my mongo databases constantly.
Just wondering what sort data corruption issues people have actually faced recently with Mongo ? Is this a big concern?
Thanks!
A:
As others have said, MongoDB does not have single-server durability right now. Fortunately, it's dead easy to set up multi-node replication. You can even set up a second machine in another data center and have data automatically replicated to it live!
If a write must succeed, you can cause Mongo to not return from an insert/update until that data has been replicated to n slaves. This ensures that you have at least n copies of the data. Replica sets allow you to add and remove nodes from your cluster on the fly without any significant work; just add a new node and it'll automatically sync a copy of the data. Remove a node and the cluster rebalances itself. It is very much designed to be used across multiple machines, with multiple nodes acting in parallel; this is it's preferred default setup, compared to something like MySQL, which expects one giant machine to do its work on, which you can then pair slaves against when you need to scale out. It's a different approach to data storage and scaling, but a very comfortable one if you take the time to understand its difference in assumptions, and how to build an architecture that capitalizes on its strengths.
A:
Yes, durability is a big problem in mongo. You have to use replication sets in mongodb for durability (you need at least 2 machines), otherwise you can loose upto last 1 minute on a power fail for example. There is no single server durability in mongo, but it'll be developed for 1.7-1.8 as I know. After a crash you have to repair db manually and rapair operation may took hours if your data is large. There is no transaction or acid, so it's not suitable for an ecommerce or banking application.
You should not use development versions of mongo (odd versiond number like 1.3.x,1.5.x,1.7.x are development versions) and you prefer to use 64 bit operating systems. If you digg into disaster articles on the web about mongo, the source of the problem is these two ones in most cases.
CouchDB, Cassandra and postgresql all have strong durability (fsync is 10 milliseconds by default in cassandra and postgresql), so they all have single server durability.
If you need dead easy scalability, fault tolerance and load balancing; cassandra is the best, but with poor query options. Failing nodes may go away and come back after a period of time, no problem, system auto repairs itself.
EDIT: mongo 1.8 came with journaling (allows durability) but it's not the default setting. Also take look at this http://news.ycombinator.com/item?id=2684423
Regards,
Serdar Irmak
A:
"MongoDB supports an automated sharding architecture, enabling horizontal scaling across multiple nodes." -source So you need to run multiple nodes for balancing and failover support. If you are wanting to run a single instance that won't fail if power is suddenly lost you need something that supports ACID like couchDB. That being said i've been using mongo at work for a month and it has not crashed on me however we are moving to a 6 node cluster soon.
Durability
The products take different approaches
to durability. CouchDB is a
"crash-only" design where the db can
terminate at any time and remain
consistent. MongoDB take a different
approach to durability. On a machine
crash, one then would run a
repairDatabase() operation when
starting up again (similar to MyISAM).
MongoDB recommends using replication
-- either LAN or WAN -- for true durability as a given server could
permanently be dead. To summarize:
CouchDB is better at durability when
using a single server with no
replication.
Quote from mongodb.org's official site.
A:
Mongo does not have ACID properties, specifically durability. So you can face issues if the process does not shut down cleanly or the machine loses power. You are supposed to implement backups and redundancy to handle that.
A:
I don't see the problem if you have the same data also in the sqlite backups. You can always refill your MongoDb databases. Refilling will only take a few minutes.
| Mongodb - are reliability issues significant still? | I have a couple of sqlite dbs (i'd say about 15GBs), with about 1m rows in total - so not super big. I was looking at mongodb, and it looks pretty easy to work with, especially if I want to try and do some basic natural language processing on the documents which make up the databases.
I've never worked with Mongo in the past, no would have to learn from scratch (will be working in python). After googling around a bit, I came across a number of somewhat horrific stories about Mongodb re. reliability. Is this still a major problem ? In a crunch, I will of course retain the sqlite backups, but I'd rather not have to reconstruct my mongo databases constantly.
Just wondering what sort data corruption issues people have actually faced recently with Mongo ? Is this a big concern?
Thanks!
| [
"As others have said, MongoDB does not have single-server durability right now. Fortunately, it's dead easy to set up multi-node replication. You can even set up a second machine in another data center and have data automatically replicated to it live!\nIf a write must succeed, you can cause Mongo to not return fro... | [
10,
9,
4,
3,
2
] | [] | [] | [
"mongodb",
"python",
"sqlite"
] | stackoverflow_0003487456_mongodb_python_sqlite.txt |
Q:
python program bug help
I've got an exam coming up soon. I've been looking through the past paper, this question keeps bugging me. I can't seem to find what the bug in the program could be because I'm quite new to all this. Can anyone help me out?
The following program contains a bug. Determine what kind of problem the program exhibits, and show how it can be fixed.
import threading
import time
import random
#the list "data" must contain two values.
#The second must always be equal to the first multiplied by 4
class GeneratorThread(threading.Thread):
#Thread for generating value pairs
def __init__(self,data):
threading.Thread.__init__(self)
self.data=data
def run(self):
while True:
#Pick a new first number
num=random.randint(0,100)
self.data[0]=num
#simulate some processing
#to calculate second number
time.sleep(1)
#Place second value into ata
self.data[1]=num*4
time.sleep(1)
class ProcessorThread(threading.Thread):
#Thread for processing value pairs
def __init__(self,data):
threading.Thread.__init__(self)
self.data=data
def run(self):
while True:
#Process current data
num1=self.data[0]
num2=self.data[1]
print "Values are %d and %d."%(num1,num2)
if num2!=num1*4:
print "\tDATA INCONSISTENCY!"
time.sleep(2)
if __name__=="__main__":
data=[1,4]
t1=GeneratorThread(data)
t2=ProcessorThread(data)
t1.start()
t2.start()
A:
There's a race condition between your two threads. Basically, there is a time between setting data[0] to something before setting data[1] to four times that value.
If the second thread comes in and checks the values during that time, the data inconsistency will occur.
You may think the two threads refer to their own data information but that's not the case. They are both references to the main data array. If you really want them to have their own data arrays, you should change:
self.data=data
into:
self.data=data[:]
in both init functions.
Otherwise (and this is the more likely case where you want to share the data), you need to ensure your threads are properly synchronised so that the data is always consistent, something like using a mutex:
#!/usr/bin/python
import threading
import time
import random
#the list "data" must contain two values.
#The second must always be equal to the first multiplied by 4
class GeneratorThread(threading.Thread):
#Thread for generating value pairs
def __init__(self,data):
threading.Thread.__init__(self)
self.datamutex=datamutex # save reference to the mutex.
self.data=data
def run(self):
while True:
#Pick a new first number
num=random.randint(0,100)
self.datamutex.acquire() # get the mutex.
self.data[0]=num
#simulate some processing
#to calculate second number
time.sleep(1)
#Place second value into ata
self.data[1]=num*4
self.datamutex.release() # release it to allow other thread
# to run now that data is consistent.
time.sleep(1)
class ProcessorThread(threading.Thread):
#Thread for processing value pairs
def __init__(self,data):
threading.Thread.__init__(self)
self.datamutex=datamutex # save mutex reference.
self.data=data
def run(self):
while True:
#Process current data
self.datamutex.acquire() # lock (can only happen if data consistent).
num1=self.data[0]
num2=self.data[1]
self.datamutex.release() # release it to allow updates.
print "Values are %d and %d."%(num1,num2)
if num2!=num1*4:
print "\tDATA INCONSISTENCY!"
time.sleep(2)
if __name__=="__main__":
datamutex = threading.Lock() # Create the mutex for both threads.
data=[1,4]
t1=GeneratorThread(data)
t2=ProcessorThread(data)
t1.start()
t2.start()
Now locks aren't the only way to synchronise threads but they're fine for this particular case.
A:
There is no need for explicit locking if you stick to thread safe ways of updating and reading the data. In this case using the fact that slice operations on lists are thread safe.
import threading
import time
import random
#the list "data" must contain two values.
#The second must always be equal to the first multiplied by 4
class GeneratorThread(threading.Thread):
#Thread for generating value pairs
def __init__(self,data):
threading.Thread.__init__(self)
self.data=data
def run(self):
while True:
#Pick a new first number
num=random.randint(0,100)
data0=num
#simulate some processing
#to calculate second number
time.sleep(1)
#Place second value into ata
data1=num*4
self.data[0:2]=data0,data1
time.sleep(1)
class ProcessorThread(threading.Thread):
#Thread for processing value pairs
def __init__(self,data):
threading.Thread.__init__(self)
self.data=data
def run(self):
while True:
#Process current data
num1,num2=self.data[0:2]
print "Values are %d and %d."%(num1,num2)
if num2!=num1*4:
print "\tDATA INCONSISTENCY!"
time.sleep(2)
if __name__=="__main__":
data=[1,4]
t1=GeneratorThread(data)
t2=ProcessorThread(data)
t1.start()
t2.start()
| python program bug help | I've got an exam coming up soon. I've been looking through the past paper, this question keeps bugging me. I can't seem to find what the bug in the program could be because I'm quite new to all this. Can anyone help me out?
The following program contains a bug. Determine what kind of problem the program exhibits, and show how it can be fixed.
import threading
import time
import random
#the list "data" must contain two values.
#The second must always be equal to the first multiplied by 4
class GeneratorThread(threading.Thread):
#Thread for generating value pairs
def __init__(self,data):
threading.Thread.__init__(self)
self.data=data
def run(self):
while True:
#Pick a new first number
num=random.randint(0,100)
self.data[0]=num
#simulate some processing
#to calculate second number
time.sleep(1)
#Place second value into ata
self.data[1]=num*4
time.sleep(1)
class ProcessorThread(threading.Thread):
#Thread for processing value pairs
def __init__(self,data):
threading.Thread.__init__(self)
self.data=data
def run(self):
while True:
#Process current data
num1=self.data[0]
num2=self.data[1]
print "Values are %d and %d."%(num1,num2)
if num2!=num1*4:
print "\tDATA INCONSISTENCY!"
time.sleep(2)
if __name__=="__main__":
data=[1,4]
t1=GeneratorThread(data)
t2=ProcessorThread(data)
t1.start()
t2.start()
| [
"There's a race condition between your two threads. Basically, there is a time between setting data[0] to something before setting data[1] to four times that value.\nIf the second thread comes in and checks the values during that time, the data inconsistency will occur.\nYou may think the two threads refer to their... | [
4,
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0003487301_multithreading_python.txt |
Q:
error when call python object thru MEL code
How to resolve this.
Following error occurs from maya. I am doing the following in Filemenu.mel file. this runs at the startup.
python("import saveCentral_fromPath");
.
.
.
global proc runSaveCentral()
{
python("saveCentral_fromPath.saveCentral()");
python("a._first_()");
}
.
.
.
menuItem -label ("save Central") -en 1
-annotation ("publish : copy to central area")
-command ("runSaveCentral()") publishItem;
# Error: file: S:/xxxxxxxx/scripts/maya/melTEST/FileMenu.mel line 64: class saveCentral_fromPath has no attribute 'saveCentral'
# Traceback (most recent call last):
# File "<maya console>", line 1, in <module>
# AttributeError: class saveCentral_fromPath has no attribute 'saveCentral' #
Brgds,
kNish
A:
python("import saveCentral_fromPath");
.
..
global proc runSaveCentral()
{
python("saveCentral_fromPath.saveCentral()._first_()");
# filename.classname.functionname
}
.
.
.
menuItem -label ("save Central") -en 1
-annotation ("publish : copy to central area")
-command ("runSaveCentral()") publishItem;
| error when call python object thru MEL code | How to resolve this.
Following error occurs from maya. I am doing the following in Filemenu.mel file. this runs at the startup.
python("import saveCentral_fromPath");
.
.
.
global proc runSaveCentral()
{
python("saveCentral_fromPath.saveCentral()");
python("a._first_()");
}
.
.
.
menuItem -label ("save Central") -en 1
-annotation ("publish : copy to central area")
-command ("runSaveCentral()") publishItem;
# Error: file: S:/xxxxxxxx/scripts/maya/melTEST/FileMenu.mel line 64: class saveCentral_fromPath has no attribute 'saveCentral'
# Traceback (most recent call last):
# File "<maya console>", line 1, in <module>
# AttributeError: class saveCentral_fromPath has no attribute 'saveCentral' #
Brgds,
kNish
| [
"python(\"import saveCentral_fromPath\");\n.\n..\n\nglobal proc runSaveCentral()\n\n{\n python(\"saveCentral_fromPath.saveCentral()._first_()\");\n# filename.classname.functionname\n}\n\n.\n.\n.\nmenuItem -label (\"save Central\") -en 1\n-annotation (\"publish : copy to central area\")\n-command (\... | [
0
] | [] | [] | [
"maya",
"python"
] | stackoverflow_0003147757_maya_python.txt |
Q:
Python on windows, shutting down and taking a screenshot
I have the following two quesions:
1 I want to be able to shutdown windows xp from python code. I am able to do that by running the following code in the python console:
import os
os.system("shutdown -s -f")
But, if i put the same code in a .py file and try to execute it,it does not work. I get the help prompt for the shutdown command.Any way to fix this ?
2 Is there any way i can take a screenshot of the current screen using python on windows ?
Thank You
A:
There's some code to shutdown windows in this message from the python-win32 list.
You can take a screen shot using PIL's ImageGrab module.
| Python on windows, shutting down and taking a screenshot | I have the following two quesions:
1 I want to be able to shutdown windows xp from python code. I am able to do that by running the following code in the python console:
import os
os.system("shutdown -s -f")
But, if i put the same code in a .py file and try to execute it,it does not work. I get the help prompt for the shutdown command.Any way to fix this ?
2 Is there any way i can take a screenshot of the current screen using python on windows ?
Thank You
| [
"There's some code to shutdown windows in this message from the python-win32 list.\nYou can take a screen shot using PIL's ImageGrab module.\n"
] | [
2
] | [] | [] | [
"python",
"windows",
"windows_xp"
] | stackoverflow_0003491226_python_windows_windows_xp.txt |
Q:
what is wrong in my python code?
#!usr/bin/python
listofnames = []
names = input("Pls enter how many of names:")
x = 1
for x in range(0, names):
inname = input("Enter the name " + str(x))
listofnames.append(inname)
print listofnames
error
inname = input("Enter the name " + str(x))
File "", line 1, in
NameError: name 'Jhon' is not defined
A:
Use raw_input instead. See http://docs.python.org/library/functions.html#raw_input. input will do the same thing as eval(raw_input(prompt)), so entering in Jhon will try to find the symbol Jhon within the file (which doesn't exist). So for your existing script you'd have to input 'Jhon' (notice the set of quotes) in the prompt so the eval will convert the value to a string.
Here's the excerpt warning from the input documentation.
Warning
This function is not safe from user
errors! It expects a valid Python
expression as input; if the input is
not syntactically valid, a SyntaxError
will be raised. Other exceptions may
be raised if there is an error during
evaluation. (On the other hand,
sometimes this is exactly what you
need when writing a quick script for
expert use.)
Below is the corrected version:
#!usr/bin/python
# The list is implied with the variable name, see my comment below.
names = []
try:
# We need to convert the names input to an int using raw input.
# If a valid number is not entered a `ValueError` is raised, and
# we throw an exception. You may also want to consider renaming
# names to num_names. To be "names" sounds implies a list of
# names, not a number of names.
num_names = int(raw_input("Pls enter how many of names:"))
except ValueError:
raise Exception('Please enter a valid number.')
# You don't need x=1. If you want to start your name at 1
# change the range to start at 1, and add 1 to the number of names.
for x in range(1, num_names+1)):
inname = raw_input("Enter the name " + str(x))
names.append(inname)
print names
NOTE: This is for Python2.x. Python3.x has fixed the input vs. raw_input confusion as explained in the other answers.
A:
input gets text from the user which is then interpreted as Python code (hence it's trying to evaluate the thing you entered, Jhon). You need raw_input for both of them and you'll need to convert the number entered (since it's a string) to an integer for your range.
#!usr/bin/python
listofnames = []
names = 0
try:
names = int(raw_input("Pls enter how many of names:"))
except:
print "Problem with input"
for x in range(0, names):
inname = raw_input("Enter the name %d: "%(x))
listofnames.append(inname)
print listofnames
A:
In python3, input() now works like raw_input(). However to get your code to work with Python3 a couple of changes are still required
#!usr/bin/python3
listofnames = []
names = int(input("Pls enter how many of names:"))
x = 1
for x in range(0, names):
inname = input("Enter the name " + str(x))
listofnames.append(inname)
print(listofnames)
| what is wrong in my python code? | #!usr/bin/python
listofnames = []
names = input("Pls enter how many of names:")
x = 1
for x in range(0, names):
inname = input("Enter the name " + str(x))
listofnames.append(inname)
print listofnames
error
inname = input("Enter the name " + str(x))
File "", line 1, in
NameError: name 'Jhon' is not defined
| [
"Use raw_input instead. See http://docs.python.org/library/functions.html#raw_input. input will do the same thing as eval(raw_input(prompt)), so entering in Jhon will try to find the symbol Jhon within the file (which doesn't exist). So for your existing script you'd have to input 'Jhon' (notice the set of quotes)... | [
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003491316_python.txt |
Q:
Converting graph traversal to multiprocessing in Python
I've been working on a graph traversal algorithm over a simple network and I'd like to run it using multiprocessing since it it going to require a lot of I/O bounded calls when I scale it over the full network. The simple version runs pretty fast:
already_seen = {}
already_seen_get = already_seen.get
GH_add_node = GH.add_node
GH_add_edge = GH.add_edge
GH_has_node = GH.has_node
GH_has_edge = GH.has_edge
def graph_user(user, depth=0):
logger.debug("Searching for %s", user)
logger.debug("At depth %d", depth)
users_to_read = followers = following = []
if already_seen_get(user):
logging.debug("Already seen %s", user)
return None
result = [x.value for x in list(view[user])]
if result:
result = result[0]
following = result['following']
followers = result['followers']
users_to_read = set().union(following, followers)
if not GH_has_node(user):
logger.debug("Adding %s to graph", user)
GH_add_node(user)
for follower in users_to_read:
if not GH_has_node(follower):
GH_add_node(follower)
logger.debug("Adding %s to graph", follower)
if depth < max_depth:
graph_user(follower, depth + 1)
if GH_has_edge(follower, user):
GH[follower][user]['weight'] += 1
else:
GH_add_edge(user, follower, {'weight': 1})
Its actually significantly faster than my multiprocessing version:
to_write = Queue()
to_read = Queue()
to_edge = Queue()
already_seen = Queue()
def fetch_user():
seen = {}
read_get = to_read.get
read_put = to_read.put
write_put = to_write.put
edge_put = to_edge.put
seen_get = seen.get
while True:
try:
logging.debug("Begging for a user")
user = read_get(timeout=1)
if seen_get(user):
continue
logging.debug("Adding %s", user)
seen[user] = True
result = [x.value for x in list(view[user])]
write_put(user, timeout=1)
if result:
result = result.pop()
logging.debug("Got user %s and result %s", user, result)
following = result['following']
followers = result['followers']
users_to_read = list(set().union(following, followers))
[edge_put((user, x, {'weight': 1})) for x in users_to_read]
[read_put(y, timeout=1) for y in users_to_read if not seen_get(y)]
except Empty:
logging.debug("Fetches complete")
return
def write_node():
users = []
users_app = users.append
write_get = to_write.get
while True:
try:
user = write_get(timeout=1)
logging.debug("Writing user %s", user)
users_app(user)
except Empty:
logging.debug("Users complete")
return users
def write_edge():
edges = []
edges_app = edges.append
edge_get = to_edge.get
while True:
try:
edge = edge_get(timeout=1)
logging.debug("Writing edge %s", edge)
edges_app(edge)
except Empty:
logging.debug("Edges Complete")
return edges
if __name__ == '__main__':
pool = Pool(processes=1)
to_read.put(me)
pool.apply_async(fetch_user)
users = pool.apply_async(write_node)
edges = pool.apply_async(write_edge)
GH.add_weighted_edges_from(edges.get())
GH.add_nodes_from(users.get())
pool.close()
pool.join()
What I can't figure out is why the single process version is so much faster. In theory, the multiprocessing version should be writing and reading simultaneously. I suspect there is lock contention on the queues and that is the cause of the slow down but I don't really have any evidence of that. When I scale the number of fetch_user processes it seems to run faster, but then I have issues with synchronizing the data seen across them. So some thoughts I've had are
Is this even a good application for
multiprocessing? I was originally
using it because I wanted to be able
to fetch from the db in parallell.
How can I avoid resource contention when reading and writing from the same queue?
Did I miss some obvious caveat for the design?
What can I do to share a lookup table between the readers so I don't keep fetching the same user twice?
When increasing the number of fetching processes they writers eventually lock. It looks like the write queue is not being written to, but the read queue is full. Is there a better way to handle this situation than with timeouts and exception handling?
A:
Queues in Python are synchronized. This means that only one thread at a time can read/write, this will definitely provoke a bottleneck in your app.
One better solution is to distribute the processing based on a hash function and assign the processing to the threads with a simple module operation. So for instance if you have 4 threads you could have 4 queues:
thread_queues = []
for i in range(4):
thread_queues = Queue()
for user in user_list:
user_hash=hash(user.user_id) #hash in here is just shortcut to some standard hash utility
thread_id = user_hash % 4
thread_queues[thread_id].put(user)
# From here ... your pool of threads access thread_queues but each thread ONLY accesses
# one queue based on a numeric id given to each of them.
Most of hash functions will distribute evenly your data. I normally use UMAC. But maybe you can just try with the hash function from the Python String implementation.
Another improvement would be to avoid the use of Queues and use a non-sync object, such a list.
| Converting graph traversal to multiprocessing in Python | I've been working on a graph traversal algorithm over a simple network and I'd like to run it using multiprocessing since it it going to require a lot of I/O bounded calls when I scale it over the full network. The simple version runs pretty fast:
already_seen = {}
already_seen_get = already_seen.get
GH_add_node = GH.add_node
GH_add_edge = GH.add_edge
GH_has_node = GH.has_node
GH_has_edge = GH.has_edge
def graph_user(user, depth=0):
logger.debug("Searching for %s", user)
logger.debug("At depth %d", depth)
users_to_read = followers = following = []
if already_seen_get(user):
logging.debug("Already seen %s", user)
return None
result = [x.value for x in list(view[user])]
if result:
result = result[0]
following = result['following']
followers = result['followers']
users_to_read = set().union(following, followers)
if not GH_has_node(user):
logger.debug("Adding %s to graph", user)
GH_add_node(user)
for follower in users_to_read:
if not GH_has_node(follower):
GH_add_node(follower)
logger.debug("Adding %s to graph", follower)
if depth < max_depth:
graph_user(follower, depth + 1)
if GH_has_edge(follower, user):
GH[follower][user]['weight'] += 1
else:
GH_add_edge(user, follower, {'weight': 1})
Its actually significantly faster than my multiprocessing version:
to_write = Queue()
to_read = Queue()
to_edge = Queue()
already_seen = Queue()
def fetch_user():
seen = {}
read_get = to_read.get
read_put = to_read.put
write_put = to_write.put
edge_put = to_edge.put
seen_get = seen.get
while True:
try:
logging.debug("Begging for a user")
user = read_get(timeout=1)
if seen_get(user):
continue
logging.debug("Adding %s", user)
seen[user] = True
result = [x.value for x in list(view[user])]
write_put(user, timeout=1)
if result:
result = result.pop()
logging.debug("Got user %s and result %s", user, result)
following = result['following']
followers = result['followers']
users_to_read = list(set().union(following, followers))
[edge_put((user, x, {'weight': 1})) for x in users_to_read]
[read_put(y, timeout=1) for y in users_to_read if not seen_get(y)]
except Empty:
logging.debug("Fetches complete")
return
def write_node():
users = []
users_app = users.append
write_get = to_write.get
while True:
try:
user = write_get(timeout=1)
logging.debug("Writing user %s", user)
users_app(user)
except Empty:
logging.debug("Users complete")
return users
def write_edge():
edges = []
edges_app = edges.append
edge_get = to_edge.get
while True:
try:
edge = edge_get(timeout=1)
logging.debug("Writing edge %s", edge)
edges_app(edge)
except Empty:
logging.debug("Edges Complete")
return edges
if __name__ == '__main__':
pool = Pool(processes=1)
to_read.put(me)
pool.apply_async(fetch_user)
users = pool.apply_async(write_node)
edges = pool.apply_async(write_edge)
GH.add_weighted_edges_from(edges.get())
GH.add_nodes_from(users.get())
pool.close()
pool.join()
What I can't figure out is why the single process version is so much faster. In theory, the multiprocessing version should be writing and reading simultaneously. I suspect there is lock contention on the queues and that is the cause of the slow down but I don't really have any evidence of that. When I scale the number of fetch_user processes it seems to run faster, but then I have issues with synchronizing the data seen across them. So some thoughts I've had are
Is this even a good application for
multiprocessing? I was originally
using it because I wanted to be able
to fetch from the db in parallell.
How can I avoid resource contention when reading and writing from the same queue?
Did I miss some obvious caveat for the design?
What can I do to share a lookup table between the readers so I don't keep fetching the same user twice?
When increasing the number of fetching processes they writers eventually lock. It looks like the write queue is not being written to, but the read queue is full. Is there a better way to handle this situation than with timeouts and exception handling?
| [
"Queues in Python are synchronized. This means that only one thread at a time can read/write, this will definitely provoke a bottleneck in your app.\nOne better solution is to distribute the processing based on a hash function and assign the processing to the threads with a simple module operation. So for instance ... | [
1
] | [] | [] | [
"algorithm",
"graph",
"multithreading",
"parallel_processing",
"python"
] | stackoverflow_0003469343_algorithm_graph_multithreading_parallel_processing_python.txt |
Q:
What's the best dispatcher/callback library in Python?
I need to allow other Python applications to register callback functions for events in my application. These need to have priorities associated with them (so a callback with a priority of 10 runs before a callback with a priority of 1) and callback functions need to be able to signal errors to the dispatcher.
These are all lightweight callbacks running in the same process, so I don't need to send signals across process boundaries.
Is there a good Python library to handle this, or do I need to write my own?
A:
Are these other applications running in another address space? If so, you'll need to use an interprocess communication library like D-BUS.
If you're just sending signals in the same process, try PyDispatcher
A:
What platform are you running under? GObject is the basis of the GTK GUI that's widely-used under Linux, and it supports event loops with prioritizable events like this.
A:
Try Twisted for anything network-related. Its perspective broker is quite nice to use.
A:
Try python-callbacks - http://code.google.com/p/python-callbacks/.
| What's the best dispatcher/callback library in Python? | I need to allow other Python applications to register callback functions for events in my application. These need to have priorities associated with them (so a callback with a priority of 10 runs before a callback with a priority of 1) and callback functions need to be able to signal errors to the dispatcher.
These are all lightweight callbacks running in the same process, so I don't need to send signals across process boundaries.
Is there a good Python library to handle this, or do I need to write my own?
| [
"Are these other applications running in another address space? If so, you'll need to use an interprocess communication library like D-BUS.\nIf you're just sending signals in the same process, try PyDispatcher\n",
"What platform are you running under? GObject is the basis of the GTK GUI that's widely-used under ... | [
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0000118221_python.txt |
Q:
get http response codes with python
I know how to do this with httplib, but I need to also set the user-agent and I'm sure you need urllib to do that. How can I get the http response codes with urllib?
A:
You can use .getcode() in urllib2 to get the HTTP code:
urllib2.urlopen("http://google.com").getcode()
Full headers with are in info() as a list:
urllib2.urlopen("http://google.com").info().headers
A:
Actually, httplib DOES allow to set User-Agent.
headers = { 'User-Agent' : 'someapp', 'Content-Type' : 'text/html' }
conn = httplib.HTTPConnection(host, port)
conn.request('POST', '/foobar', 'mydata', headers)
| get http response codes with python | I know how to do this with httplib, but I need to also set the user-agent and I'm sure you need urllib to do that. How can I get the http response codes with urllib?
| [
"You can use .getcode() in urllib2 to get the HTTP code:\nurllib2.urlopen(\"http://google.com\").getcode()\n\nFull headers with are in info() as a list:\nurllib2.urlopen(\"http://google.com\").info().headers\n\n",
"Actually, httplib DOES allow to set User-Agent.\nheaders = { 'User-Agent' : 'someapp', 'Content-Typ... | [
5,
0
] | [] | [] | [
"http",
"python"
] | stackoverflow_0003491495_http_python.txt |
Q:
Calling python script on MAC/Linux from Command line - passing arguments
Consider this setup and folder structure:
c:\foo
\bin\foo.bat
\lib\foo.py
I have foo.bat path added to my environment PATH, so I can call it from anywhere passing in some arguments:
c:/>foo.bat -v
foo.bat contains this code:
@ECHO OFF
"c:\foo\lib\foo.py" %1 %2 %3 %4 %5 %6 %7 %8 %9
This works fine in Windows.
Now I want to be able to do the same in Mac or Linux.
How can I create this executable file, that will call the script lib\foo.py, passing in some arguments?
thanks
[SOLUTION]
thanks guys, your answers helped me end up with this script that works as intended:
in \foo\bin\foo file
#!/usr/bin/env bash
python /usr/local/foo/lib/foo.py $*
A:
You can call python scripts directly on mac/linux, just make sure to put your python interpreter on the first line, example file foo:
#!/usr/bin/python
if __name__ == "__main__":
print 'bar'
to run the file call it directly form your current directory using ./foo
if you want to access if from everywhere you can put it in /usr/local/bin, for example, just make sure that the file is executable (chmod +x foo).
A:
You didn't explicitly say what your shell of choice is, but assuming it's GNU bash:
#!/usr/bin/env bash
/path/to/lib/foo.py $*
Note that both your shell script and foo.py need to have the execution bit set to be run this way (that is only a chmod +x /path/to/your/script /path/to/lib/foo.py away).
| Calling python script on MAC/Linux from Command line - passing arguments | Consider this setup and folder structure:
c:\foo
\bin\foo.bat
\lib\foo.py
I have foo.bat path added to my environment PATH, so I can call it from anywhere passing in some arguments:
c:/>foo.bat -v
foo.bat contains this code:
@ECHO OFF
"c:\foo\lib\foo.py" %1 %2 %3 %4 %5 %6 %7 %8 %9
This works fine in Windows.
Now I want to be able to do the same in Mac or Linux.
How can I create this executable file, that will call the script lib\foo.py, passing in some arguments?
thanks
[SOLUTION]
thanks guys, your answers helped me end up with this script that works as intended:
in \foo\bin\foo file
#!/usr/bin/env bash
python /usr/local/foo/lib/foo.py $*
| [
"You can call python scripts directly on mac/linux, just make sure to put your python interpreter on the first line, example file foo:\n#!/usr/bin/python \nif __name__ == \"__main__\":\n print 'bar'\n\nto run the file call it directly form your current directory using ./foo\nif you want to access if from everywh... | [
6,
2
] | [] | [] | [
"batch_file",
"command_line",
"linux",
"macos",
"python"
] | stackoverflow_0003492050_batch_file_command_line_linux_macos_python.txt |
Q:
Get existing or create new App Engine Syntax
I came across this syntax browsing through code for examples. From its surrounding code, it looked like would a) get the entity with the given keyname or b) if the entity did not exist, create a new entity that could be saved. Assume my model class is called MyModel.
my_model = MyModel(key_name='mymodelkeyname',
kwarg1='first arg', kwarg2='second arg')
I'm now running into issues, but only in certain situations. Is my assumption about what this snippet does correct? Or should I always do the following?
my_model = MyModel.get_by_key_name('mymodelkeyname')
if not my_model:
my_model = MyModel(key_name='mymodelkeyname',
kwarg1='first arg', kwarg2='second arg')
else:
# do something with my_model
A:
The constructor, which is what you're using, always constructs a new entity. When you store it, it overwrites any other entity with the same key.
The alternate code you propose also has an issue: it's susceptible to race conditions. Two instances of that code running simultaneously could both determine that the entity does not exist, and each create it, resulting in one overwriting the work of the other.
What you want is the Model.get_or_insert method, which is syntactic sugar for this:
def get_or_insert(cls, key_name, **kwargs):
def _tx():
model = cls.get_by_key_name(key_name)
if not model:
model = cls(key_name=key_name, **kwargs)
model.put()
return model
return db.run_in_transaction(_tx)
Because the get operation and the conditional insert take place in a transaction, the race condition is not possible.
A:
Is this what you are looking for -> http://code.google.com/appengine/docs/python/datastore/modelclass.html#Model_get_or_insert
| Get existing or create new App Engine Syntax | I came across this syntax browsing through code for examples. From its surrounding code, it looked like would a) get the entity with the given keyname or b) if the entity did not exist, create a new entity that could be saved. Assume my model class is called MyModel.
my_model = MyModel(key_name='mymodelkeyname',
kwarg1='first arg', kwarg2='second arg')
I'm now running into issues, but only in certain situations. Is my assumption about what this snippet does correct? Or should I always do the following?
my_model = MyModel.get_by_key_name('mymodelkeyname')
if not my_model:
my_model = MyModel(key_name='mymodelkeyname',
kwarg1='first arg', kwarg2='second arg')
else:
# do something with my_model
| [
"The constructor, which is what you're using, always constructs a new entity. When you store it, it overwrites any other entity with the same key.\nThe alternate code you propose also has an issue: it's susceptible to race conditions. Two instances of that code running simultaneously could both determine that the e... | [
2,
1
] | [] | [] | [
"google_app_engine",
"modeling",
"models",
"python"
] | stackoverflow_0003490141_google_app_engine_modeling_models_python.txt |
Q:
How to make GtkListStore store object attribute in a row?
I'w trying to keep at ListStore non-text objects using snippet I found. These are the objects:
class Series(gobject.GObject, object):
def __init__(self, title):
super(Series, self).__init__()
self.title = title
gobject.type_register(Series)
class SeriesListStore(gtk.ListStore):
def __init__(self):
super(SeriesListStore, self).__init__(Series)
self._col_types = [Series]
def get_n_columns(self):
return len(self._col_types)
def get_column_type(self, index):
return self._col_types[index]
def get_value(self, iter, column):
obj = gtk.ListStore.get_value(self, iter, 0)
return obj
And now I'm trying to make TreeView display it:
...
liststore = SeriesListStore()
liststore.clear()
for title in full_conf['featuring']:
series = Series(title)
liststore.append([series])
def get_series_title(column, cell, model, iter):
cell.set_property('text', liststore.get_value(iter, column).title)
return
selected = builder.get_object("trvMain")
selected.set_model(liststore)
col = gtk.TreeViewColumn(_("Series title"))
cell = gtk.CellRendererText()
col.set_cell_data_func(cell, get_series_title)
col.pack_start(cell)
col.add_attribute(cell, "text", 0)
selected.append_column(col)
...
But it fails with errors:
GtkWarning:
gtk_tree_view_column_cell_layout_set_cell_data_func:
assertion info != NULL' failed
col.set_cell_data_func(cell,
get_series_title)
Warning: unable to set propertytext'
of type gchararray' from value of
typedata+TrayIcon+Series'
window.show_all()
Warning: unable to set property text'
of typegchararray' from value of
type `data+TrayIcon+Series'
gtk.main()gtk.main()
What should I do to make it work?
A:
Two mistakes in the second-to-last block.
GtkWarning: gtk_tree_view_column_cell_layout_set_cell_data_func: assertion `info != NULL'
In English, this means that the cell renderer is not in the column's list of cell renderers. You need to add the cell renderer to the column first before calling set_cell_data_func.
Warning: unable to set property `text' of type `gchararray' from value of `typedata+TrayIcon+Series'
This is because the add_attribute line causes GTK+ to try setting the cell text to a Series object, which of course fails. Just remove that line; the cell data func already takes care of setting the cell text.
In code:
col = gtk.TreeViewColumn(_("Series title"))
cell = gtk.CellRendererText()
col.pack_start(cell)
col.set_cell_data_func(cell, get_series_title)
| How to make GtkListStore store object attribute in a row? | I'w trying to keep at ListStore non-text objects using snippet I found. These are the objects:
class Series(gobject.GObject, object):
def __init__(self, title):
super(Series, self).__init__()
self.title = title
gobject.type_register(Series)
class SeriesListStore(gtk.ListStore):
def __init__(self):
super(SeriesListStore, self).__init__(Series)
self._col_types = [Series]
def get_n_columns(self):
return len(self._col_types)
def get_column_type(self, index):
return self._col_types[index]
def get_value(self, iter, column):
obj = gtk.ListStore.get_value(self, iter, 0)
return obj
And now I'm trying to make TreeView display it:
...
liststore = SeriesListStore()
liststore.clear()
for title in full_conf['featuring']:
series = Series(title)
liststore.append([series])
def get_series_title(column, cell, model, iter):
cell.set_property('text', liststore.get_value(iter, column).title)
return
selected = builder.get_object("trvMain")
selected.set_model(liststore)
col = gtk.TreeViewColumn(_("Series title"))
cell = gtk.CellRendererText()
col.set_cell_data_func(cell, get_series_title)
col.pack_start(cell)
col.add_attribute(cell, "text", 0)
selected.append_column(col)
...
But it fails with errors:
GtkWarning:
gtk_tree_view_column_cell_layout_set_cell_data_func:
assertion info != NULL' failed
col.set_cell_data_func(cell,
get_series_title)
Warning: unable to set propertytext'
of type gchararray' from value of
typedata+TrayIcon+Series'
window.show_all()
Warning: unable to set property text'
of typegchararray' from value of
type `data+TrayIcon+Series'
gtk.main()gtk.main()
What should I do to make it work?
| [
"Two mistakes in the second-to-last block.\n\nGtkWarning: gtk_tree_view_column_cell_layout_set_cell_data_func: assertion `info != NULL'\nIn English, this means that the cell renderer is not in the column's list of cell renderers. You need to add the cell renderer to the column first before calling set_cell_data_fun... | [
3
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0003488285_gtk_pygtk_python.txt |
Q:
Why does updating a set in a tuple cause an error?
I have just tried the following in Python 2.6:
>>> foo = (set(),)
>>> foo[0] |= set(range(5))
TypeError: 'tuple' object does not support item assignment
>>> foo
(set([0, 1, 2, 3, 4]),)
>>> foo[0].update(set(range(10)))
>>> foo
(set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),)
I have several questions here:
Why does foo[0] |= set(range(5)) update the set and throw an exception?
why does foo[0].update(set(range(10))) work without a problem? Should it not have the same result as the first statement?
Edit Many people have pointed out, that tuples are immutable. I am aware of that. They have also pointed out, that |= would create a new set object and assign it to the tuple. That is wrong. See this:
>>> foo = set()
>>> bar = foo
>>> foo is bar
True
>>> foo |= set(range(5))
>>> foo
set([0, 1, 2, 3, 4])
>>> bar
set([0, 1, 2, 3, 4])
>>> foo is bar
True
This means that no new object has been created, but the existing one was modified. This should work with the tuple. Please note also that, although my first code throws a TypeError, the set within the tuple is still updated. That is the effect I am interested in. Why the TypeError, when the operation obviously was successful?
A:
>>> def f():
... x = (set(),)
... y = set([0])
... x[0] |= y
... return
...
>>> import dis
>>> dis.dis(f)
2 0 LOAD_GLOBAL 0 (set)
3 CALL_FUNCTION 0
6 BUILD_TUPLE 1
9 STORE_FAST 0 (x)
3 12 LOAD_GLOBAL 0 (set)
15 LOAD_CONST 1 (0)
18 BUILD_LIST 1
21 CALL_FUNCTION 1
24 STORE_FAST 1 (y)
4 27 LOAD_FAST 0 (x)
30 LOAD_CONST 1 (0)
33 DUP_TOPX 2
36 BINARY_SUBSCR
37 LOAD_FAST 1 (y)
40 INPLACE_OR
41 ROT_THREE
42 STORE_SUBSCR
5 43 LOAD_CONST 0 (None)
46 RETURN_VALUE
This shows that the statement x[0] |= y is implemented by calling x[0].__ior__(y) and then assigning the returned value to x[0].
set implements in-place |= by having set.__ior__ return self. However, the assignment to x[0] still takes place. The fact that it's assigning the same value that was already there is irrelevant; it fails for the same reason that:
x = (set(),)
x[0] = x[0]
fails.
A:
In your example foo is a tuple. Tuples in python are inmutable, this means that you cannot change the reference of any tuple element - foo[0] in your case. Things like the following can't be done:
>>> x = ('foo','bar')
>>> x[0]='foo2'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>>
You could use a list instead
>>> foo = [set(),None]
>>> foo
[set([]), None]
>>> foo[0] |= set(range(5))
>>> foo
[set([0, 1, 2, 3, 4]), None]
>>>
A:
foo[0] |= set(range(5))
doesn't work, because what you wanted to achieve is:
foo[0] = foo[0] | set(range(5))
and you can't assign new elements to an old tuple, because they are immutable. For example you cant do this:
x = (0, 1, 2)
x[0] = 3
When you are running update, you don't change references in the tuple, but only object behind the reference. You could also do this like this:
x = set()
y = (x,)
x.update(set(range(5))
as you can see you don't change the tuple, but x (and y[0]) will be changed.
x |= y
and
x.update(y)
aren't the same, because update works in place and x |= y will create a new object (x | y) and store it under name x.
A:
Tuples are immutable. By trying to assign to foo[0], you are attempting to change a value that the tuple stores (a reference to a set). When you use the update() function, you are not changing the reference, but instead the actual set. Because the reference is the same, this is allowed.
A:
Tuples are immutable so u cannot reassign values to it. But if a tuple contains a mutable type such as list or set u can update them.
now in your case when u use '|=' u actually first update the set (which is a value in the tuple) then assign it to tuple which causes the exception.
Exception is thrown after the updation of the set.
In the next case u r simply updating the set so there is no exception.
Refer to http://docs.python.org/reference/datamodel.html
A:
"Why the TypeError, when the operation obviously was successful?".
Because there are multiple side-effects. Try to avoid that.
That's what the
foo[0] |= set(range(5)) update the set and throw an exception
Correct. First the set mutation is done.
Then the tuple mutation is attempted and fails.
foo[0].update(set(range(10))) work without a problem?
Correct. The set is mutated.
Should it not have the same result as the first statement?
No. The first statement involves explicit assignment -- changing the tuple -- which is forbidden.
The second statement updates a member of an immutable tuple, an operation that is not forbidden, but is suspicious as pushing the envelope.
But the Legalism Scholar argues, aren't they supposed to be the same? Or similar? No.
Updating the tuple object (via assignment) is forbidden.
Updating a member of an existing tuple object (via a mutator function) is not forbidden.
A:
The best way to explain this is to show it "algebraically":
foo[0] |= set(range(5))
foo[0] = set.__ior__(foo[0], set(range(5)))
tuple.__setitem__(foo, 0, set.__ior__(foo[0], set(range(5))))
foo[0].update(set(range(5)))
set.__ior__(foo[0], set(range(5)))
As you can see, the update form is not the same, it modifies foo[0] in place. __or__ generates a new set from the elements of the left and right operands. This is then assigned back to foo.
Note that for simplicity, the expansions that aren't helpful to the problem are not expanded (such as foo[0] -> tuple.__getitem__(foo, 0)).
The TypeError thrown is in tuple.__setitem__. tuple does not allow its items references to be replaced. The update form does not touch foo in any way (ie. it doesn't not invoke tuple.__setitem__).
A:
a |= b is equivalent to a = operator.ior(a, b).
s[i] |= b is equivalent to s[i] = operator.ior(s[i], b).
Item assignment on a tuple is forbidden by contract.
The set.__ior__ method calls set.update without creating a new instance.
That explains the behaviour you are observing.
The underlying problem, is that changing the value of a tuple is a violation of contract. You should not try doing it. Since you can have any object in a tuple, there are loopholes you can exploit, but then you get the kind of weird behaviour you are observing.
Tuple items should be frozenset instead of set. If you do this, you will get a consistent behaviour, and no unwanted side-effect on error.
| Why does updating a set in a tuple cause an error? | I have just tried the following in Python 2.6:
>>> foo = (set(),)
>>> foo[0] |= set(range(5))
TypeError: 'tuple' object does not support item assignment
>>> foo
(set([0, 1, 2, 3, 4]),)
>>> foo[0].update(set(range(10)))
>>> foo
(set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),)
I have several questions here:
Why does foo[0] |= set(range(5)) update the set and throw an exception?
why does foo[0].update(set(range(10))) work without a problem? Should it not have the same result as the first statement?
Edit Many people have pointed out, that tuples are immutable. I am aware of that. They have also pointed out, that |= would create a new set object and assign it to the tuple. That is wrong. See this:
>>> foo = set()
>>> bar = foo
>>> foo is bar
True
>>> foo |= set(range(5))
>>> foo
set([0, 1, 2, 3, 4])
>>> bar
set([0, 1, 2, 3, 4])
>>> foo is bar
True
This means that no new object has been created, but the existing one was modified. This should work with the tuple. Please note also that, although my first code throws a TypeError, the set within the tuple is still updated. That is the effect I am interested in. Why the TypeError, when the operation obviously was successful?
| [
">>> def f():\n... x = (set(),)\n... y = set([0])\n... x[0] |= y\n... return \n... \n>>> import dis\n>>> dis.dis(f)\n 2 0 LOAD_GLOBAL 0 (set)\n 3 CALL_FUNCTION 0\n 6 BUILD_TUPLE 1\n 9 STORE_FAST 0 (x)\n\n ... | [
11,
2,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"python",
"tuples"
] | stackoverflow_0003492216_python_tuples.txt |
Q:
Import all modules in django
In django is there way to import all modules
ex: from project.models import *
ex: from project1.models import *
Can this be done with one statement
A:
If you just want to do this when testing things in the shell, look into the shell_plus command provided by the django-extensions project.
This is a really neat extension, which starts a shell and automatically loads all the models in your project when you do ./manage.py shell_plus from the command line.
| Import all modules in django | In django is there way to import all modules
ex: from project.models import *
ex: from project1.models import *
Can this be done with one statement
| [
"If you just want to do this when testing things in the shell, look into the shell_plus command provided by the django-extensions project.\nThis is a really neat extension, which starts a shell and automatically loads all the models in your project when you do ./manage.py shell_plus from the command line.\n"
] | [
4
] | [] | [] | [
"django",
"django_settings",
"python"
] | stackoverflow_0003493204_django_django_settings_python.txt |
Q:
what is the next step?
When I type "python" it displays:
ActivePython 2.6.5.14 (ActiveState Software Inc.)
based on Python 2.6.5 (r265:79063, Jul 4 2010, 21:05:58)
[MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
This is what I get at the command line:
>>> python create-application.py
File "<stdin>", line 1
python create-application.py
^ SyntaxError: invalid syntax
What should I do to work in Qooxdoo.
A:
Apparently you are confusing between the Python REPL and the command line. You should be calling python create-application.py from the command line ("cmd" in Windows) and not from the REPL (which is what you get when you type python on the command line).
I suggest reading up on the basics before venturing further. Good Luck.
A:
You need to run the command python create-application.py from the command line, not from within the interpreter.
You have already started the Python interpreter, probably by typing python at the command line. (You can tell, because the >>> prompt is a Python standard.) This is a program that accepts Python code -- but python create-application.py isn't Python code, it's a system command. You run those from the command line.
I assume you're not planning to use Python to program (just to run this script) but if you are, I recommend Dive Into Python for a tutorial.
| what is the next step? | When I type "python" it displays:
ActivePython 2.6.5.14 (ActiveState Software Inc.)
based on Python 2.6.5 (r265:79063, Jul 4 2010, 21:05:58)
[MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
This is what I get at the command line:
>>> python create-application.py
File "<stdin>", line 1
python create-application.py
^ SyntaxError: invalid syntax
What should I do to work in Qooxdoo.
| [
"Apparently you are confusing between the Python REPL and the command line. You should be calling python create-application.py from the command line (\"cmd\" in Windows) and not from the REPL (which is what you get when you type python on the command line).\nI suggest reading up on the basics before venturing furt... | [
10,
3
] | [] | [] | [
"java",
"python",
"qooxdoo"
] | stackoverflow_0003493377_java_python_qooxdoo.txt |
Q:
matplotlib weirdness, it's not drawing my graph
What happened is I followed this demo, I modified it to suit my needs had it working, changed it to use a function to draw two graphs but now it doesn't work at all using plt.show() or plt.savefig()
here's my code
import csv
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
# I converted excel to a csv file
data = [x for x in csv.reader(open('ASS1_Q1.csv'))]
question1 = {}
question1['males'] = []
question1['females'] = []
for x in data:
if x[0].lower() == "male":
question1["males"].append(float(x[1]))
elif x[0].lower() == "female":
question1['females'].append(float(x[1]))
else:
print "Not a valid dataline", x
def plot_graph(data, filename):
fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, patches = ax.hist(np.array(data), bins=13, align='mid', facecolor='#888888')
ax.set_xlabel('Speed in kph')
ax.set_ylabel('Amount of Females')
ax.set_xlim(min(data, max(data)))
# plt.savefig(filename)
plt.show()
plot_graph(question1['males'], "ASS1Q1-males.eps")
#plot_graph(question1['females'], "ASSQ2-females.eps")
print summary(question1['males'])
print summary(question1['females'])
Can someone explain why this is happening? what am I doing wrong?
A:
Try removing
import matplotlib
matplotlib.use('Agg')
The command
python -c 'import matplotlib; matplotlib.use("")'
will show you the valid string arguments that can be sent to matplotlib.use.
On my machine, 'Agg' is listed as valid, though I get no output when this is set. If you are curious, you could just keep trying various options until you find one that works.
When you find the one that your prefer, you may also find it more convenient to set something like
backend : GtkAgg
in your ~/.matplotlib/matplotlibrc instead of using matplotlib.use(...).
| matplotlib weirdness, it's not drawing my graph | What happened is I followed this demo, I modified it to suit my needs had it working, changed it to use a function to draw two graphs but now it doesn't work at all using plt.show() or plt.savefig()
here's my code
import csv
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
# I converted excel to a csv file
data = [x for x in csv.reader(open('ASS1_Q1.csv'))]
question1 = {}
question1['males'] = []
question1['females'] = []
for x in data:
if x[0].lower() == "male":
question1["males"].append(float(x[1]))
elif x[0].lower() == "female":
question1['females'].append(float(x[1]))
else:
print "Not a valid dataline", x
def plot_graph(data, filename):
fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, patches = ax.hist(np.array(data), bins=13, align='mid', facecolor='#888888')
ax.set_xlabel('Speed in kph')
ax.set_ylabel('Amount of Females')
ax.set_xlim(min(data, max(data)))
# plt.savefig(filename)
plt.show()
plot_graph(question1['males'], "ASS1Q1-males.eps")
#plot_graph(question1['females'], "ASSQ2-females.eps")
print summary(question1['males'])
print summary(question1['females'])
Can someone explain why this is happening? what am I doing wrong?
| [
"Try removing\nimport matplotlib\nmatplotlib.use('Agg')\n\nThe command\npython -c 'import matplotlib; matplotlib.use(\"\")'\n\nwill show you the valid string arguments that can be sent to matplotlib.use. \nOn my machine, 'Agg' is listed as valid, though I get no output when this is set. If you are curious, you coul... | [
1
] | [] | [] | [
"graph",
"matplotlib",
"python"
] | stackoverflow_0003493409_graph_matplotlib_python.txt |
Q:
How to convert a binary file into a Long integer?
In python, long integers have an unlimited range. Is there a simple way to convert a binary file (e.g., a photo) into a single long integer?
A:
Here's one way to do it.
def file_to_number(f):
number = 0
for line in f:
for char in line:
number = ord(char) | (number << 8)
return number
You might get a MemoryError eventually.
A:
Using the bitstring module it's just:
bitstring.BitString(filename='your_file').uint
If you prefer you can get a signed integer using the int property.
Internally this is using struct.unpack to convert chunks of bytes, which is more efficient than doing it per byte.
| How to convert a binary file into a Long integer? | In python, long integers have an unlimited range. Is there a simple way to convert a binary file (e.g., a photo) into a single long integer?
| [
"Here's one way to do it.\ndef file_to_number(f):\n number = 0\n for line in f:\n for char in line:\n number = ord(char) | (number << 8)\n return number\n\nYou might get a MemoryError eventually.\n",
"Using the bitstring module it's just:\nbitstring.BitString(filename='your_file').uint\... | [
3,
3
] | [] | [] | [
"algorithm",
"long_integer",
"python"
] | stackoverflow_0003493781_algorithm_long_integer_python.txt |
Q:
An extended Bezier Library or Algorithms of bezier operations
Is there a library of data structures and operations for quadratic bezier curves? I need to implement:
bezier to bitmap converting with arbitrary quality
optimizing bezier curves
common operations like subtraction, extraction, rendering etc.
languages: c,c++,.net,python
Algorithms without implementation (pseudocode or etc) could be useful too. (especially optimization)
A:
A little bit of python lib is included in nodebox:
http://nodebox.net/code/index.php/Bezier
There are plenty of algorithms inside inkscape, but I did not digg the code yet to find, how easy they could be used outside if inkscape.
Update: Inkscape is using lib2geom:
lib2geom (2Geom in private life) was
initially a library developed for
Inkscape but will provide a robust
computational geometry framework for
any application. It is not a rendering
library, instead concentrating on high
level algorithms such as computing arc
length.
lib2geom is at http://lib2geom.sourceforge.net
A:
You might want to take a look at Cairo. I am not exactly sure if it covers all your requirements but it should be able to handle rendering at least.
| An extended Bezier Library or Algorithms of bezier operations | Is there a library of data structures and operations for quadratic bezier curves? I need to implement:
bezier to bitmap converting with arbitrary quality
optimizing bezier curves
common operations like subtraction, extraction, rendering etc.
languages: c,c++,.net,python
Algorithms without implementation (pseudocode or etc) could be useful too. (especially optimization)
| [
"A little bit of python lib is included in nodebox:\nhttp://nodebox.net/code/index.php/Bezier\nThere are plenty of algorithms inside inkscape, but I did not digg the code yet to find, how easy they could be used outside if inkscape.\nUpdate: Inkscape is using lib2geom:\n\nlib2geom (2Geom in private life) was\n ini... | [
4,
1
] | [] | [] | [
"algorithm",
"bezier",
"curve",
"python"
] | stackoverflow_0002568018_algorithm_bezier_curve_python.txt |
Q:
How can I convert the time in a datetime string from 24:00 to 00:00 in Python?
I have a lot of date strings like Mon, 16 Aug 2010 24:00:00 and some of them are in 00-23 hour format and some of them in 01-24 hour format. I want to get a list of date objects of them, but when I try to transform the example string into a date object, I have to transform it from Mon, 16 Aug 2010 24:00:00 to Tue, 17 Aug 2010 00:00:00. What is the easiest way?
A:
import email.utils as eutils
import time
import datetime
ntuple=eutils.parsedate('Mon, 16 Aug 2010 24:00:00')
print(ntuple)
# (2010, 8, 16, 24, 0, 0, 0, 1, -1)
timestamp=time.mktime(ntuple)
print(timestamp)
# 1282017600.0
date=datetime.datetime.fromtimestamp(timestamp)
print(date)
# 2010-08-17 00:00:00
print(date.strftime('%a, %d %b %Y %H:%M:%S'))
# Tue, 17 Aug 2010 00:00:00
Since you say you have a lot of these to fix, you should define a function:
def standardize_date(date_str):
ntuple=eutils.parsedate(date_str)
timestamp=time.mktime(ntuple)
date=datetime.datetime.fromtimestamp(timestamp)
return date.strftime('%a, %d %b %Y %H:%M:%S')
print(standardize_date('Mon, 16 Aug 2010 24:00:00'))
# Tue, 17 Aug 2010 00:00:00
| How can I convert the time in a datetime string from 24:00 to 00:00 in Python? | I have a lot of date strings like Mon, 16 Aug 2010 24:00:00 and some of them are in 00-23 hour format and some of them in 01-24 hour format. I want to get a list of date objects of them, but when I try to transform the example string into a date object, I have to transform it from Mon, 16 Aug 2010 24:00:00 to Tue, 17 Aug 2010 00:00:00. What is the easiest way?
| [
"import email.utils as eutils\nimport time\nimport datetime\n\nntuple=eutils.parsedate('Mon, 16 Aug 2010 24:00:00')\nprint(ntuple)\n# (2010, 8, 16, 24, 0, 0, 0, 1, -1)\ntimestamp=time.mktime(ntuple)\nprint(timestamp)\n# 1282017600.0\ndate=datetime.datetime.fromtimestamp(timestamp)\nprint(date)\n# 2010-08-17 00:00:0... | [
10
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0003493924_datetime_python.txt |
Q:
Getting started with Qooxdoo
i downloaded Qooxdoo, then ActivePython and installed it as in this tutorial http://qooxdoo.org/documentation/1.1/helloworld. When I follow the instructions I get the following results:
C:\qooxdoo-1.1-sdk\tool\bin\create-application.py
--name=custom --out=C: - this command opens a "create-application" wordfile.
cd C:\custom
inside c:\custom I typed generate.py source-all but I got the following error
'generate.py' is not recognized as an internal or external command, operable program or batch file.
What's gone wrong? I'm stuck.
A:
In order to execute .pys from the command line on Windows like that you'll need to add .py to your PATHEXT environment variable.
You might also need to make sure that ActivePython's bin directory is in your path. If it is, you can then equivalently run python generate.py.
| Getting started with Qooxdoo | i downloaded Qooxdoo, then ActivePython and installed it as in this tutorial http://qooxdoo.org/documentation/1.1/helloworld. When I follow the instructions I get the following results:
C:\qooxdoo-1.1-sdk\tool\bin\create-application.py
--name=custom --out=C: - this command opens a "create-application" wordfile.
cd C:\custom
inside c:\custom I typed generate.py source-all but I got the following error
'generate.py' is not recognized as an internal or external command, operable program or batch file.
What's gone wrong? I'm stuck.
| [
"In order to execute .pys from the command line on Windows like that you'll need to add .py to your PATHEXT environment variable.\nYou might also need to make sure that ActivePython's bin directory is in your path. If it is, you can then equivalently run python generate.py.\n"
] | [
2
] | [] | [] | [
"ajax",
"javascript",
"python",
"qooxdoo"
] | stackoverflow_0003493974_ajax_javascript_python_qooxdoo.txt |
Q:
Organizing files in tar bz2 file with python
I have about 200,000 text files that are placed in a bz2 file. The issue I have is that when I scan the bz2 file to extract the data I need, it goes extremely slow. It has to look through the entire bz2 file to fine the single file I am looking for. Is there anyway to speed this up?
Also, I thought about possibly organizing the files in the tar.bz2 so I can instead have it know where to look. Is there anyway to organize files that are put into a bz2?
More Info/Edit:
I need to query the compressed file for each textfile. Is there a better compression method that supports such a large number of files and is as thoroughly compressed?
A:
Do you have to use bzip2? Reading it's documentation, it's quite clear it's not designed to support random access. Perhaps you should use a compression format that more closely matches your requirements. The good old Zip format supports random access, but might compress worse, of course.
A:
Bzip2 compresses in large blocks (900 KiB by default, I believe). One method that would speed up the scanning of the tar file dramatically, but would reduce compression performance, would be to compress each file individually and then tar the results together. This is essentially what Zip-format files are (though using zlib compression rather than bzip2). But you could then easily grab the tar index and only have to decompress the specific file(s) you are looking for.
I don't think most tar programs offer much ability to organize files in any meaningful way, though you could write a program to do this for your special case (I know Python has tar-writing libraries though I've only used them once or twice). However, you'd still have the problem of having to decompress most of the data before you found what you were looking for.
| Organizing files in tar bz2 file with python | I have about 200,000 text files that are placed in a bz2 file. The issue I have is that when I scan the bz2 file to extract the data I need, it goes extremely slow. It has to look through the entire bz2 file to fine the single file I am looking for. Is there anyway to speed this up?
Also, I thought about possibly organizing the files in the tar.bz2 so I can instead have it know where to look. Is there anyway to organize files that are put into a bz2?
More Info/Edit:
I need to query the compressed file for each textfile. Is there a better compression method that supports such a large number of files and is as thoroughly compressed?
| [
"Do you have to use bzip2? Reading it's documentation, it's quite clear it's not designed to support random access. Perhaps you should use a compression format that more closely matches your requirements. The good old Zip format supports random access, but might compress worse, of course.\n",
"Bzip2 compresses in... | [
6,
0
] | [] | [] | [
"bzip2",
"python",
"tar",
"tarfile"
] | stackoverflow_0003494020_bzip2_python_tar_tarfile.txt |
Q:
python setuptool how can I add dependency for libxml2-dev and libxslt1-dev?
My application needs lxml >= 2.1,
but to install lxml its requied to install libxml2-dev libxslt1-dev
else it raises error while installing the lxml,
is there a way that using python setup tool I can give this as dependency in my setup.py....
A:
Not really ... setuptools only handle dependencies on package wich belongs already to pypi. So if you want these kind of dependencies, i think that you have to select the packaging technology brought by your favorite distribution.
But, you can override your setuptools build or install command to make extra check before installing the package.
To do so, please have a look of this answer.
| python setuptool how can I add dependency for libxml2-dev and libxslt1-dev? | My application needs lxml >= 2.1,
but to install lxml its requied to install libxml2-dev libxslt1-dev
else it raises error while installing the lxml,
is there a way that using python setup tool I can give this as dependency in my setup.py....
| [
"Not really ... setuptools only handle dependencies on package wich belongs already to pypi. So if you want these kind of dependencies, i think that you have to select the packaging technology brought by your favorite distribution.\nBut, you can override your setuptools build or install command to make extra check ... | [
2
] | [] | [] | [
"dependencies",
"libxml2",
"lxml",
"python",
"setuptools"
] | stackoverflow_0003493151_dependencies_libxml2_lxml_python_setuptools.txt |
Q:
getting all child nodes' values of the current node
I am trying to retrieve all of the values in the div.
For example:
<div>xyz <span> abc </span> def</div>
This is the code
the_page="<div>xyz <span> abc </span> def</div>"
doc = libxml2dom.parseString(the_page, html=1)
divs=doc.getElementsByTagName("div")
print divs[0].firstChild.nodeValue
This only prints "xyz". I tried to just do print divs[0].nodeValue, but that gives me an error.
I want all of the text. How would I get around this?
A:
for your:
divs=doc.getElementsByTagName("div")
use:
childs = divs[0].childNodes
then, you can crawl them. Each child contains a list of childs and nodeValue
for child in childs :
if child.childNode == []:
print child.nodeValue
else :
## Recurse
| getting all child nodes' values of the current node | I am trying to retrieve all of the values in the div.
For example:
<div>xyz <span> abc </span> def</div>
This is the code
the_page="<div>xyz <span> abc </span> def</div>"
doc = libxml2dom.parseString(the_page, html=1)
divs=doc.getElementsByTagName("div")
print divs[0].firstChild.nodeValue
This only prints "xyz". I tried to just do print divs[0].nodeValue, but that gives me an error.
I want all of the text. How would I get around this?
| [
"for your: \ndivs=doc.getElementsByTagName(\"div\")\n\nuse:\nchilds = divs[0].childNodes\n\nthen, you can crawl them. Each child contains a list of childs and nodeValue\nfor child in childs :\n if child.childNode == []:\n print child.nodeValue\n else :\n ## Recurse\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003488572_python.txt |
Q:
Why am I receiving these syntax errors in Python 3.1.2?
I have been receiving errors when trying to save and run this Python 3.1 script, and I'm not sure why. I'm new to python, and I've been trying some of the Project Euler problems (this is problem 2). I recieve a "invalid syntac" error on "evenfibsum(v)", and on the colon after "_____main_____". I'm not sure why this is as I wrote a script for the first Project Euler problem in this same fashion, and it worked fine. I understand that I could write a script without defining a function, but I'm still interested in why this is not working.
def evenfibsum(v):
a = 1
b = 2
r = 0
while b < v:
if b%2 == 0:
r = r + b
a, b = b, a+b
else:
a,b = b, a+b
print("The sum of the Fibonacci sequence is: ", r)
def main():
print("This program is designed to find the sum of all even")
print("numbers from the specificed Fibonacci sequence.")
v = int(input("What is the highest number you would like to evaluate in the sequence? ")
evenfibsum(v)
if __name__ == '__main__':
main()
A:
There is no closing bracket in v = int(...
A:
You are missing a closing parenthesis on the line assigning v.
| Why am I receiving these syntax errors in Python 3.1.2? | I have been receiving errors when trying to save and run this Python 3.1 script, and I'm not sure why. I'm new to python, and I've been trying some of the Project Euler problems (this is problem 2). I recieve a "invalid syntac" error on "evenfibsum(v)", and on the colon after "_____main_____". I'm not sure why this is as I wrote a script for the first Project Euler problem in this same fashion, and it worked fine. I understand that I could write a script without defining a function, but I'm still interested in why this is not working.
def evenfibsum(v):
a = 1
b = 2
r = 0
while b < v:
if b%2 == 0:
r = r + b
a, b = b, a+b
else:
a,b = b, a+b
print("The sum of the Fibonacci sequence is: ", r)
def main():
print("This program is designed to find the sum of all even")
print("numbers from the specificed Fibonacci sequence.")
v = int(input("What is the highest number you would like to evaluate in the sequence? ")
evenfibsum(v)
if __name__ == '__main__':
main()
| [
"There is no closing bracket in v = int(...\n",
"You are missing a closing parenthesis on the line assigning v.\n"
] | [
11,
0
] | [] | [] | [
"python"
] | stackoverflow_0003494780_python.txt |
Q:
How can I improve this long-winded Python code?
I have a data structure like this:
items = [
['Schools', '', '', '32'],
['Schools', 'Primary schools', '', '16'],
['Schools', 'Secondary schools', '', '16'],
['Schools', 'Secondary schools', 'Special ed', '8'],
['Schools', 'Secondary schools', 'Non-special ed', '8'],
]
It's a list of spending items. Some are aggregates, e.g. items[0] is aggregate spending on all schools, and items[2] is aggregate spending on secondary schools. Those that are not aggregates are items[1], items[3] and items[4].
How can I elegantly reduce the list so it only shows non-aggregate items? In pseudocode:
for each item in items
check if item[1] is blank, if it is
check if item[0] matches another item’s[0]
if it does and if that item’s[1] isn’t blank
delete item
check if item[2] is blank, if it is
check if item[1] matches another item’s[1]
if it does and if if that item’s[2] isn’t blank
delete item
Here's my (lame!) attempt so far:
for i in range(len(items)):
i -= 1
if items[i]:
if items[i][1] == "":
for other_item in items:
if items[i][0]==other_item[0] and other_item[1]!="":
items_to_remove.append(i)
continue
elif items[i][2]=="":
for other_item in items:
if items[i][1] == other_item[1] and other_item[2] != "":
items_to_remove.append(i)
continue
new_items = [ key for key,_ in groupby(items_to_remove)]
new_items.sort(reverse=True)
for number in new_items:
temp_item = items[number]
items.remove(temp_item)
This is just so ugly. What can I do better?
NB: I could use dictionaries instead of lists, if that would make life easier :)
A:
Firstly, I suggest your data structure should look more like this:
items = [
['Schools', None, None, 32],
['Schools', 'Primary schools', None, 16],
['Schools', 'Secondary schools', None, 8],
['Schools', 'Secondary schools', 'Special ed', 4],
['Schools', 'Secondary schools', 'Non-special ed', 4],
]
We can sort them into a dictionary like this:
result = {}
for item in items:
if not item[0] in result or not isinstance(result[item[0]], dict): result[item[0]] = {}
if not item[1] in result[item[0]] or not isinstance(result[item[0]][item[1]], dict): result[item[0]][item[1]] = {}
if not item[2] in result[item[0]][item[1]] or not isinstance(result[item[0]][item[1]][item[2]], dict): result[item[0]][item[1]][item[2]] = {}
if not item[0]:
result = item[3]
elif not item[1]:
result[item[0]] = item[3]
elif not item[2]:
result[item[0]][item[1]] = item[3]
else:
result[item[0]][item[1]][item[2]] = item[3]
And you should end up with a dictionary like:
result = {
'Schools': {
'Secondary schools': {
'Non-special ed': '4',
'Special ed': '4'
},
'Primary schools': '16'
}
}
My routine could probably be optimized and made recursive.
Also, the numbers total to 24 -- is this an error on your part?
A:
list_keys = [ "".join(x[:-1]) for x in items ]
for i in range(len(list_keys)-1):
if not list_keys[i+1].startswith(list_keys[i]):
print items[i]
print items[-1]
Here I find the "key" of each item, which is all entries in an item, concatenated, except the last value.
An aggregate item's key is always a prefix of succeeding items' keys, so we can use this test to detect aggregate items and dismiss them.
This alg. prints (on your input):
['Schools', 'Primary schools', '', '16']
['Schools', 'Secondary schools', 'Special ed', '4']
['Schools', 'Secondary schools', 'Non-special ed', '4'],
Note:
This assumes all items are ordered neatly in a tree structure (as your original data). If it's not, it'll be (slightly) more complicated as you'll have to sort the keys before the loop (and keep track of which key belongs to which item).
A:
How about making your items objects?
class School (object):
__init__(self, is_aggregate=false):
self.is_aggregate = is_aggregate
A:
I'm using a helper function that
makes a set of the entries with more fine-grained data
returns a function suitable for filter that removes aggregate items
Run your example data through this function, and it will give the desired output :)
def remove_aggregates(items):
def mk_pred(index_i, blank_i, items):
posts = set(x[index_i] for x in items if x[blank_i] != '')
def pred(item):
return not (item[blank_i] == '' and item[index_i] in posts)
return pred
items = filter(mk_pred(0,1,items), items)
items = filter(mk_pred(1,2,items), items)
return items
A:
You've asked how to do so elegantly, and further, how to do so better. Your nota bene suggests that the structure you're working with is still malleable. If you want to be able to do so more elegantly, I would suggest changing the way the data is stored. Some options are:
Include an additional field in each list, which indicates whether it is an aggregate value or not:
items = [
['Schools', '', '', '32', True],
['Schools', 'Primary schools', '', '16', False],
['Schools', 'Secondary schools', '', '8', True],
['Schools', 'Secondary schools', 'Special ed', '4', False],
['Schools', 'Secondary schools', 'Non-special ed', '4', False],
]
Split your data into two lists:
items = [
[
['Schools', '', '', '32'],
['Schools', 'Secondary schools', '', '8'],
],
[
['Schools', 'Primary schools', '', '16'],
['Schools', 'Secondary schools', 'Special ed', '4'],
['Schools', 'Secondary schools', 'Non-special ed', '4'],
],
]
Make the aggregate values contain a list of their children (although this still wouldn't be much fun to reduce):
items = [
['Schools', '', '', '32', [
['Schools', 'Primary schools', '', '16', []],
['Schools', 'Secondary schools', '', '8', [
['Schools', 'Secondary schools', 'Special ed', '4'],
['Schools', 'Secondary schools', 'Non-special ed', '4'],
],
],
]
I would say that the current structure of your data does not allow you to do anything elegant with it. You require logic along the lines of "if this index is blank but it isn't for another entry that has the same value at another of my indexes", and this has to be done twice per list entry, because that logic can occur at two separate pairs of index locations. Fix the way you store your information, and you will be able to write an elegant method of reducing that data.
For example, if you went with the first option I listed (using booleans to indicate whether the entry is aggregate), you could reduce the list with:
reduced = [item for item in items where item[4] == False]
A:
This attemp tries not to be dependend of sorting of the input:
items = [
['Schools', '', '', '32'],
['Schools', 'Primary schools', '', '16'],
['Schools', 'Secondary schools', '', '16'],
['Schools', 'Secondary schools', 'Special ed', '8'],
['Schools', 'Secondary schools', 'Non-special ed', '8'],
]
def path(item,upto=None):
return ".".join([p for p in item[:-1] if p][:upto])
from collections import defaultdict
children_counter = defaultdict(int)
for i in items:
children_counter[path(i,-1)] += 1
for i in items:
if children_counter[path(i)] == 0:
print i
| How can I improve this long-winded Python code? | I have a data structure like this:
items = [
['Schools', '', '', '32'],
['Schools', 'Primary schools', '', '16'],
['Schools', 'Secondary schools', '', '16'],
['Schools', 'Secondary schools', 'Special ed', '8'],
['Schools', 'Secondary schools', 'Non-special ed', '8'],
]
It's a list of spending items. Some are aggregates, e.g. items[0] is aggregate spending on all schools, and items[2] is aggregate spending on secondary schools. Those that are not aggregates are items[1], items[3] and items[4].
How can I elegantly reduce the list so it only shows non-aggregate items? In pseudocode:
for each item in items
check if item[1] is blank, if it is
check if item[0] matches another item’s[0]
if it does and if that item’s[1] isn’t blank
delete item
check if item[2] is blank, if it is
check if item[1] matches another item’s[1]
if it does and if if that item’s[2] isn’t blank
delete item
Here's my (lame!) attempt so far:
for i in range(len(items)):
i -= 1
if items[i]:
if items[i][1] == "":
for other_item in items:
if items[i][0]==other_item[0] and other_item[1]!="":
items_to_remove.append(i)
continue
elif items[i][2]=="":
for other_item in items:
if items[i][1] == other_item[1] and other_item[2] != "":
items_to_remove.append(i)
continue
new_items = [ key for key,_ in groupby(items_to_remove)]
new_items.sort(reverse=True)
for number in new_items:
temp_item = items[number]
items.remove(temp_item)
This is just so ugly. What can I do better?
NB: I could use dictionaries instead of lists, if that would make life easier :)
| [
"Firstly, I suggest your data structure should look more like this:\nitems = [\n ['Schools', None, None, 32],\n ['Schools', 'Primary schools', None, 16],\n ['Schools', 'Secondary schools', None, 8],\n ['Schools', 'Secondary schools', 'Special ed', 4],\n ['Schools', 'Secondary schools', 'Non-special e... | [
2,
1,
0,
0,
0,
0
] | [
"You could use a list comprehension, as follows:\nitems = [a for a in items if a[1] != '' and a[2] != '']\n\nOr, if an empty string in any position denotes an aggregate item:\nitems = [a for a in items if '' not in a]\n\nOf course, you don't necessarily need to assign the reduced list to items - you can use it howe... | [
-1
] | [
"python",
"refactoring"
] | stackoverflow_0003491877_python_refactoring.txt |
Q:
What's wrong with this code?
The code is to search for a substring...the code takes in 2 inputs...the 2nd string is used to search...i.e 2nd string is smaller in length.
a=input("Enter the 1st string") //Giving error here
b=input("Enter the second string")
com=""
for x in range(0,len(a)):
com=""
for j in range(x,len(b)+x):
com=com+a[j]
if(com==b):
print "Match Found at" + str(x)
else:
continue
The code doest compile....pls help
A:
If you are using Python 2.x, you need to use raw_input, not input. input tries to evaluate what you enter as though it is Python code. This is no longer true in Python 3.
Another obvious thing is that this:
if(com==b):
print "Match Found at" + str(x)
else:
continue
... needs to be indented like this:
if(com==b):
print "Match Found at" + str(x)
else:
continue
A:
b.find( a )
| What's wrong with this code? | The code is to search for a substring...the code takes in 2 inputs...the 2nd string is used to search...i.e 2nd string is smaller in length.
a=input("Enter the 1st string") //Giving error here
b=input("Enter the second string")
com=""
for x in range(0,len(a)):
com=""
for j in range(x,len(b)+x):
com=com+a[j]
if(com==b):
print "Match Found at" + str(x)
else:
continue
The code doest compile....pls help
| [
"If you are using Python 2.x, you need to use raw_input, not input. input tries to evaluate what you enter as though it is Python code. This is no longer true in Python 3.\nAnother obvious thing is that this:\nif(com==b):\nprint \"Match Found at\" + str(x)\nelse:\ncontinue\n\n... needs to be indented like this:\n... | [
4,
4
] | [] | [] | [
"python",
"search",
"substring"
] | stackoverflow_0003494914_python_search_substring.txt |
Q:
What is the fastest way to plot a 2d numpy array of pixel data with pygtk?
I have a numpy array of pixel data that I want to draw at interactive speeds in pygtk. Is there some simple, fast way to get my data onto the screen?
A:
I'm not aware of anything GTK specific, but have a look at glumpy and pygarrayimage for fast, OpenGL based visualization (and animation) of numpy arrays.
Pygarrayimage is focused more on just getting numpy arrays as an OpenGL texture. I don't know a ton about it, but it is somewhat widely used, as far as I can tell.
Glumpy, in particular, has some really neat demos that show its usage rather well. Unfortunately, the links to the screenshots on the homepage seem to be dead, but it's worth installing glumpy just to play around with the demos. It's a great option for making quick interactive animations.
| What is the fastest way to plot a 2d numpy array of pixel data with pygtk? | I have a numpy array of pixel data that I want to draw at interactive speeds in pygtk. Is there some simple, fast way to get my data onto the screen?
| [
"I'm not aware of anything GTK specific, but have a look at glumpy and pygarrayimage for fast, OpenGL based visualization (and animation) of numpy arrays. \nPygarrayimage is focused more on just getting numpy arrays as an OpenGL texture. I don't know a ton about it, but it is somewhat widely used, as far as I can ... | [
2
] | [] | [] | [
"gtk",
"numpy",
"pygtk",
"python"
] | stackoverflow_0003486354_gtk_numpy_pygtk_python.txt |
Q:
Font width returns incorrect values
The following code should return the width in pixels of the character 'a' in the default font; it doesn't:
import pygtk
gtk.require20()
import gtk
t = gtk.TextView()
print t.get_style().get_font().width("w") # Always returns -6
A:
gtk.Style.get_font() is deprecated, as evidenced by the DeprecationWarning you get when you try to call it; I assume that's why it's not working. On my PyGTK there isn't any such function as gtk.Style.string_width().
You should use Pango:
import pygtk
pygtk.require20()
import gtk
t = gtk.TextView()
print t.create_pango_layout('w').get_pixel_size()
| Font width returns incorrect values | The following code should return the width in pixels of the character 'a' in the default font; it doesn't:
import pygtk
gtk.require20()
import gtk
t = gtk.TextView()
print t.get_style().get_font().width("w") # Always returns -6
| [
"gtk.Style.get_font() is deprecated, as evidenced by the DeprecationWarning you get when you try to call it; I assume that's why it's not working. On my PyGTK there isn't any such function as gtk.Style.string_width().\nYou should use Pango:\nimport pygtk\npygtk.require20()\nimport gtk\n\nt = gtk.TextView()\nprint t... | [
1
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0003481972_pygtk_python.txt |
Q:
Format of activate_time in Gtk.Menu
What is the format of the parameter activate_time in Python GTK+ when using Gtk.Menu.popup() method?
I have tried using int(time.time()) but I get a traceback saying an integer is required...
A:
Not sure if it is a complete solution, but time.time() returns a float, try casting to an int and see what happens.
EDIT:
After consulting the source docs, I found this tidbit:
The button and activate_time values should be the mouse button that was pressed to trigger the menu popup and the time the button was pressed. These values can usually be retrieved from the "button_press_event".
Perhaps this will be more helpful than my first attempt.
I also found this C snipet in the C docs, it has popup() being called in a signal handler (that is how they get a "button_press_event".
A:
I found out I can use gtk.get_current_event_time() to get a reasonable timestamp matching what Gtk looks like it expects.
| Format of activate_time in Gtk.Menu | What is the format of the parameter activate_time in Python GTK+ when using Gtk.Menu.popup() method?
I have tried using int(time.time()) but I get a traceback saying an integer is required...
| [
"Not sure if it is a complete solution, but time.time() returns a float, try casting to an int and see what happens.\nEDIT:\nAfter consulting the source docs, I found this tidbit:\n\nThe button and activate_time values should be the mouse button that was pressed to trigger the menu popup and the time the button wa... | [
1,
1
] | [] | [] | [
"gtk",
"python"
] | stackoverflow_0003494587_gtk_python.txt |
Q:
How to get the last value of a list of tkinter Entry widgets
I have a list of n Entry widgets. Every widget accepts only one character, and then the focus is passed to the next one. I would like to ".get()" the values of the n widgets, but I can't get the last one. Here is the sample code:
import Tkinter as tk
def vf(event):
actual=entrylist.index(root.focus_get())
print "--",len(entrylist),actual
if event.char.upper() in ('V', 'F', ' '):
print event.char
if actual<len(entrylist)-1:
entrylist[actual+1].focus_set()
else:
#set focus to another widget?
for x in entrylist:
print "-",x.get(),"-"
#the last character is lost!
elif event.keysym not in ('Alt_r', 'Alt_L', 'F4'):
print event.keysym
return 'break'
root= tk.Tk()
entrylist=[]
for i in xrange(4):
e=tk.Entry(width=1)
e.grid()
e.bind("<KeyPress>",vf)
entrylist+=[e]
root.mainloop()
A:
The value you enter into the fourth Entry widget is only stored after the event has finished. That is, after the call to vf(event) is complete.
I have added a button which displays the contents of the Entry widgets when pressed. This will display the contents of all four widgets.
Otherwise access the contents of the Entry widgets after the call to vk is complete.
import Tkinter as tk
def vf(event):
actual = entrylist.index(root.focus_get())
print "--", len(entrylist), actual
if event.char.upper() in ('V', 'F', ' '):
print event.char
if actual < len(entrylist) - 1:
entrylist[actual + 1].focus_set()
else:
#set focus to another widget?
for x in entrylist:
print "-", x.get(), "-"
#the last character is lost!
def show():
for x in entrylist:
print '-', x.get(), '-'
root = tk.Tk()
entrylist = []
for i in xrange(4):
e = tk.Entry(root, width=10)
e.grid()
e.bind("<KeyPress>", vf)
entrylist.append(e)
b = tk.Button(root, text='show', command=show)
b.grid()
root.mainloop()
Edit
Answering the question in the comment.
It appears that the text is only stored in the Entry widget once the key has been released. Therefore, you can check for KeyRelease events in the fourth Entry. Then, at that point, you should be able to access the values stored in all four widgets. The following works (but I don't find it very elegant - there may be a simpler way of doing this).
import Tkinter as tk
def vf(event):
entry_index = entries.index(root.focus_get())
if event.char.upper() in ('V', 'F', ' '):
if entry_index < len(entries) - 1:
entries[entry_index + 1].focus_set()
elif event.keysym not in ('Alt_r', 'Alt_L', 'F4'):
print event.keysym
return 'break'
def show(event):
if entries[-1].get():
# only print the values if the last Entry contains text
for i, e in enumerate(entries):
print 'var %s: %s' % (i, e.get())
root = tk.Tk()
entries = []
for i in xrange(4):
e = tk.Entry(width=10)
e.grid()
e.bind("<KeyPress>", vf)
if i == 3:
# catch KeyRelease events on the last Entry widget
e.bind("<KeyRelease>", show)
entries.append(e)
root.mainloop()
| How to get the last value of a list of tkinter Entry widgets | I have a list of n Entry widgets. Every widget accepts only one character, and then the focus is passed to the next one. I would like to ".get()" the values of the n widgets, but I can't get the last one. Here is the sample code:
import Tkinter as tk
def vf(event):
actual=entrylist.index(root.focus_get())
print "--",len(entrylist),actual
if event.char.upper() in ('V', 'F', ' '):
print event.char
if actual<len(entrylist)-1:
entrylist[actual+1].focus_set()
else:
#set focus to another widget?
for x in entrylist:
print "-",x.get(),"-"
#the last character is lost!
elif event.keysym not in ('Alt_r', 'Alt_L', 'F4'):
print event.keysym
return 'break'
root= tk.Tk()
entrylist=[]
for i in xrange(4):
e=tk.Entry(width=1)
e.grid()
e.bind("<KeyPress>",vf)
entrylist+=[e]
root.mainloop()
| [
"The value you enter into the fourth Entry widget is only stored after the event has finished. That is, after the call to vf(event) is complete.\nI have added a button which displays the contents of the Entry widgets when pressed. This will display the contents of all four widgets.\nOtherwise access the contents of... | [
2
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0003494810_python_tkinter.txt |
Q:
Uninstall pysvn in Mac OSX 10.5
I installed the wrong version of pysvn in my system using the .dmg. I realized the mistake and removed the pysvn folder from /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/. I don't see pysvn anywhere else on my system.
Now when I try to install the correct (older) version of pysvn the installation process stops with the message "A newer version of pysvn is already installed." Where else do I need to remove the previous installation of pysvn?
A:
In case anyone else needs an answer to this I'll post the solution that worked for me. This link was what I was looking for. Deleting the pysvn .pkg file from /Library/Receipts allowed me to install the older version.
| Uninstall pysvn in Mac OSX 10.5 | I installed the wrong version of pysvn in my system using the .dmg. I realized the mistake and removed the pysvn folder from /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/. I don't see pysvn anywhere else on my system.
Now when I try to install the correct (older) version of pysvn the installation process stops with the message "A newer version of pysvn is already installed." Where else do I need to remove the previous installation of pysvn?
| [
"In case anyone else needs an answer to this I'll post the solution that worked for me. This link was what I was looking for. Deleting the pysvn .pkg file from /Library/Receipts allowed me to install the older version.\n"
] | [
2
] | [] | [] | [
"macos",
"pysvn",
"python"
] | stackoverflow_0003479331_macos_pysvn_python.txt |
Q:
python interpreter with ellipsis _ function?
>>> type(_)
<type 'ellipsis'>
>>> 1 + 1
2
>>> _
2
>>>
what's the usefulness of this _ function?
A:
It just makes it easier to track intermediate values or to operate on the previously returned value.
>>> [x*x for x in range(5)]
[0, 1, 4, 9, 16]
>>> sum(_) # instead of having to type sum([0,1,4,9,16]) by hand
30
A:
in case you use ipython it's part of ipythons [output caching system] - it just stores the previous output.
edit: oh, it seems to be implemented for the default python interpreter as well.
| python interpreter with ellipsis _ function? | >>> type(_)
<type 'ellipsis'>
>>> 1 + 1
2
>>> _
2
>>>
what's the usefulness of this _ function?
| [
"It just makes it easier to track intermediate values or to operate on the previously returned value.\n>>> [x*x for x in range(5)]\n[0, 1, 4, 9, 16]\n>>> sum(_) # instead of having to type sum([0,1,4,9,16]) by hand\n30\n\n",
"in case you use ipython it's part of ipythons [output caching system] - it just stores t... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003495248_python.txt |
Q:
The best way to use python as a server scripting language for use on localhost
relatively long-time PHP user here. I could install XAMPP in my sleep at this point to the point where I can get a PHP script running in the browser at "localhost", but in my searches to find a similar path using Python, I've run out of Googling ideas. I've discovered the mod_python Apache mod, but then I also discovered that it's been discontinued. I'd greatly prefer to do my Python learning in a browser as opposed to the command prompt, so if anybody could point me along the proper path, I'd be very grateful.
Thanks!
A:
well mod_python has been retired. So in order to host python apps you want mod_wsgi
http://code.google.com/p/modwsgi/
But python isn't really like php(as in you mix it with html to get output, if I understand your question correctly). In learning python, using the command line/repl will probably be much more useful/straight forward I would think. If you are looking for python as primarily web development you should look into django (http://www.djangoproject.com/) as that might be closer to what you are looking for..
A:
Most Python webframeworks have a built-in minimal development server:
Flask
Turbogears
Django
Pylons
web.py
web2py
But don't be afraid of the command line. Python has a great interactive console (just run python) and there's an even better one: IPython.
A:
Many options, here are a couple:
mod_wsgi is an Apache module that is suitable for production environments
SimpleHTTPServer ships with Python and is easy to use
frameworks like Django or Twisted
| The best way to use python as a server scripting language for use on localhost | relatively long-time PHP user here. I could install XAMPP in my sleep at this point to the point where I can get a PHP script running in the browser at "localhost", but in my searches to find a similar path using Python, I've run out of Googling ideas. I've discovered the mod_python Apache mod, but then I also discovered that it's been discontinued. I'd greatly prefer to do my Python learning in a browser as opposed to the command prompt, so if anybody could point me along the proper path, I'd be very grateful.
Thanks!
| [
"well mod_python has been retired. So in order to host python apps you want mod_wsgi \nhttp://code.google.com/p/modwsgi/\nBut python isn't really like php(as in you mix it with html to get output, if I understand your question correctly). In learning python, using the command line/repl will probably be much more u... | [
5,
4,
2
] | [] | [] | [
"localhost",
"python",
"xampp"
] | stackoverflow_0003495290_localhost_python_xampp.txt |
Q:
sqlite SQL query for unprocessed rows
I'm not quite even sure where / what to search for - so apologies if this is a trivial thing that has been asked before!
I have two tables in sqlite:
table_A = [id, value1, value2]
table_A$foo = [id, foo(value1), foo(value2)]
table_A$bar = [id, bar(value1), bar(value2)]
Where foo() / bar() are arbitrary functions not really relevant here
Now at the moment, I do:
select * from table_A
And use this cursor to compute all the rows for each of the derivative tables.
If something goes wrong (or I add new rows to table_A), i'd like a way to be able to compute (within SQL, rather than in python) which rows are already present in table_A$foo etc. and so just select the remaining (so like a AND NOT)to compute foo() and bar() - i should be able to do this on the ID col, as these remain the same.
Wondering if there is a way to do this in sqlite, which I imagine would be quicker than trying to rig this up in python.
Many thanks!
A:
I don't understand if you consider a match based on value1 columns matching, or a combination of all three columns...
Using EXISTS to find those that are already present:
SELECT *
FROM TABLE_A a
WHERE EXISTS(SELECT NULL
FROM TABLE_A$foo f
WHERE a.id = f.id
AND a.value1 = f.value1
AND a.value2 = f.value2)
Using EXISTS to find those that are not present:
SELECT *
FROM TABLE_A a
WHERE NOT EXISTS(SELECT NULL
FROM TABLE_A$foo f
WHERE a.id = f.id
AND a.value1 = f.value1
AND a.value2 = f.value2)
| sqlite SQL query for unprocessed rows | I'm not quite even sure where / what to search for - so apologies if this is a trivial thing that has been asked before!
I have two tables in sqlite:
table_A = [id, value1, value2]
table_A$foo = [id, foo(value1), foo(value2)]
table_A$bar = [id, bar(value1), bar(value2)]
Where foo() / bar() are arbitrary functions not really relevant here
Now at the moment, I do:
select * from table_A
And use this cursor to compute all the rows for each of the derivative tables.
If something goes wrong (or I add new rows to table_A), i'd like a way to be able to compute (within SQL, rather than in python) which rows are already present in table_A$foo etc. and so just select the remaining (so like a AND NOT)to compute foo() and bar() - i should be able to do this on the ID col, as these remain the same.
Wondering if there is a way to do this in sqlite, which I imagine would be quicker than trying to rig this up in python.
Many thanks!
| [
"I don't understand if you consider a match based on value1 columns matching, or a combination of all three columns...\nUsing EXISTS to find those that are already present:\nSELECT *\n FROM TABLE_A a\n WHERE EXISTS(SELECT NULL\n FROM TABLE_A$foo f\n WHERE a.id = f.id\n ... | [
1
] | [] | [] | [
"python",
"sql",
"sqlite"
] | stackoverflow_0003495524_python_sql_sqlite.txt |
Q:
Check ports with SNMP (net-snmp)
Is there a way to monitor server ports using SNMP (I'm using net-snmp-python to check this with python).
So far I've checked pretty simple with "nc" command, however I want to see if I can do this with SNMP.
Thank you for your answers and patience.
A:
Well if you want to use SNMP to see exactly what ports are listening, you should be able to use the following OIDS and walk the table
"1.3.6.1.2.1.6.13.1.1" tcpConnState
"1.3.6.1.2.1.7.5.1.1" udpLocalAddress
Walking UDP would give you something like this:
snmpwalk -cpublic 192.168.1.13 1.3.6.1.2.1.7.5.1.1
UDP-MIB::udpLocalAddress.0.0.0.0.68 = IpAddress: 0.0.0.0
UDP-MIB::udpLocalAddress.0.0.0.0.161 = IpAddress: 0.0.0.0
UDP-MIB::udpLocalAddress.0.0.0.0.32908 = IpAddress: 0.0.0.0
UDP-MIB::udpLocalAddress.0.0.0.0.33281 = IpAddress: 0.0.0.0
UDP-MIB::udpLocalAddress.0.0.0.0.33795 = IpAddress: 0.0.0.0
UDP-MIB::udpLocalAddress.0.0.0.0.34822 = IpAddress: 0.0.0.0
UDP-MIB::udpLocalAddress.0.0.0.0.44782 = IpAddress: 0.0.0.0
UDP-MIB::udpLocalAddress.192.168.1.13.9950 = IpAddress: 192.168.1.13
and TCP like:
snmpwalk -cpublic 192.168.1.13 1.3.6.1.2.1.6.13.1.1
TCP-MIB::tcpConnState.0.0.0.0.21.0.0.0.0.0 = INTEGER: listen(2)
TCP-MIB::tcpConnState.0.0.0.0.23.0.0.0.0.0 = INTEGER: listen(2)
TCP-MIB::tcpConnState.0.0.0.0.80.0.0.0.0.0 = INTEGER: listen(2)
Walking the tables will show you what ports are listening, and could provide you with some information.
Now if you just want to check to see if specific ports that you listed in your question are listening you can use the following OIDS to check.
ftp -- 1.3.6.1.2.1.6.13.1.1.0.0.0.0.21.0.0.0.0.0
ssh -- 1.3.6.1.2.1.6.13.1.1.0.0.0.0.22.0.0.0.0.0
http -- 1.3.6.1.2.1.6.13.1.1.0.0.0.0.80.0.0.0.0.0
https -- 1.3.6.1.2.1.6.13.1.1.0.0.0.0.443.0.0.0.0.0
bind -- 1.3.6.1.2.1.7.5.1.1.0.0.0.0.53
the above OIDS assume that the server is bound to the default address (0.0.0.0). But they could be bound to the server IP address only (depends on config). In that case assuming your Server IP is 192.168.10.1 you would get
1.3.6.1.2.1.7.5.1.1.192.168.10.1.53 for bind
so all that being said I think if you wanted to tell if http was listening on the default address on host 192.168.10.1, using the python net snmp bindings you would have something like this.
import netsnmp
oid = netsmp.Varbind('1.3.6.1.2.1.6.13.1.1.0.0.0.0.80.0.0.0.0.0')
result = netsnmp.snmp(oid,
Version = 2,
DestHost="192.168.10.1",
Community="public")
I am not 100% sure if the Varbind is required as I don't do any snmp stuff in python,and some examples I found had it, and some didn't. But try it either way. in the above query, if the server isn't listening it will return a no such OID, if it is open and listening result should Integer(2).
A:
It's hard to see where SNMP might fit in.
The best way to monitor would be to use a protocol specific client (i.e., run a simple query v.s. MySQL, retrieve a test file using FTP, etc.)
If that doesn't work, you can open a TCP or UDP socket to the ports and see if anyone is listening.
A:
You might try running nmap against the ports you want to check, but that won't necessarily give you an indication that the server process on the other side of an open port is alive.
| Check ports with SNMP (net-snmp) | Is there a way to monitor server ports using SNMP (I'm using net-snmp-python to check this with python).
So far I've checked pretty simple with "nc" command, however I want to see if I can do this with SNMP.
Thank you for your answers and patience.
| [
"Well if you want to use SNMP to see exactly what ports are listening, you should be able to use the following OIDS and walk the table\n \"1.3.6.1.2.1.6.13.1.1\" tcpConnState \n \"1.3.6.1.2.1.7.5.1.1\" udpLocalAddress\n\nWalking UDP would give you something like this: \nsnmpwalk -cpublic 192.168.1.13 1.3.6.1.2.1... | [
4,
0,
0
] | [] | [] | [
"networking",
"python",
"snmp"
] | stackoverflow_0003485203_networking_python_snmp.txt |
Q:
How to organize GUI Code for a PyQt project?
i am looking for something similar to
Organizing GUI code, but for Python and PyQt4. Especially, I am looking at tips and examples of how to handle and store the configuration data, general state etc.
EDIT:
I have found some hints regarding older versions under: http://www.commandprompt.com/community/pyqt/
A:
Here's an overview of what we did w/some example names and their functions (we have a lot more in the actual app.)
ProjectFolder/
- src/
- my_project/
- model/
- preference.py # Interact with config params
- api.py # Interact with our REST api
- controller/
- startup.py # Initialization code
- login.py # Login a user
- view/
- main_window.py # Application container
- login_widget.py # Login form
- main.py # Application entry point.
- tests/
- my_project_tests/
- model/
- view/
- controller/
- resources/
- ui/ # The files match basically one to one with the modules in the view directory.
- main_window.ui
- login_widget.ui
- images/
- logo.png
- setup.py # Script to build the application (calling into the build_py2exe, etc. files below)
- build_py2exe.py # Build the py2exe exe
- build_py2app.py # Build the py2app app
- build_win_installer.iss # Package up the py2exe into an installer (Using inno setup).
- build_dmg.py #Package up the py2app into a DMG
- runtests.py # Run the tests
| How to organize GUI Code for a PyQt project? | i am looking for something similar to
Organizing GUI code, but for Python and PyQt4. Especially, I am looking at tips and examples of how to handle and store the configuration data, general state etc.
EDIT:
I have found some hints regarding older versions under: http://www.commandprompt.com/community/pyqt/
| [
"Here's an overview of what we did w/some example names and their functions (we have a lot more in the actual app.)\nProjectFolder/\n - src/\n - my_project/\n - model/\n - preference.py # Interact with config params\n - api.py # Interact with our REST api\n\n - controller/\n ... | [
15
] | [] | [] | [
"code_organization",
"pyqt4",
"python"
] | stackoverflow_0003495703_code_organization_pyqt4_python.txt |
Q:
Compression types for a specific use in Python
I actually partially asked this in this thread
Organizing files in tar bz2 file with python
But it mad eme rethink what I was doing.
Now I think it might be a good idea to change the compression method I am using. I am currently using tar.bz2 compression. What I need to be able to do is access the compressed files one at a time, and specifically by name, to build them into a different file. Zip compression is supposed to support this well, but the number of files I am compressing, 200,000 txt files, seem to be to large for that file type. Zips can only support 64k files, or something like that. Does anyone have any idea of what compression type I should use?
Also, it would help if there was a python library built for it, such as tarfile, zipfile etc.
A:
You could compress the individual files and put those into a tar (or ar) container.
| Compression types for a specific use in Python | I actually partially asked this in this thread
Organizing files in tar bz2 file with python
But it mad eme rethink what I was doing.
Now I think it might be a good idea to change the compression method I am using. I am currently using tar.bz2 compression. What I need to be able to do is access the compressed files one at a time, and specifically by name, to build them into a different file. Zip compression is supposed to support this well, but the number of files I am compressing, 200,000 txt files, seem to be to large for that file type. Zips can only support 64k files, or something like that. Does anyone have any idea of what compression type I should use?
Also, it would help if there was a python library built for it, such as tarfile, zipfile etc.
| [
"You could compress the individual files and put those into a tar (or ar) container.\n"
] | [
1
] | [] | [] | [
"compression",
"python"
] | stackoverflow_0003495978_compression_python.txt |
Q:
What is the difference between a parameterized class and a metaclass (code examples in Python please)?
Hello Stack Overflow contributers,
I'm a novice programmer learning Python right now, and I came upon this site which helps explain object-oriented paradigms. I know that metaclasses are classes of classes (like how meta-directories are directories of directories, etc. etc.), but I'm having trouble with something: What is the actual difference between a metaclass and a parameterized class, according to the website's definition?
If you can, please include code examples in Python that illustrate the differences between the two. Thank you for your help!
A:
Python doesn't have (or need) "parameterized classes", so it's hard to provide examples of them in Python;-). A metaclass is simply "the class of a class": normally type (as long, in Py2, as you remember to make the class new-style by inheriting from object, or some other built-in type or other new-style class -- old-style classes are a legacy artefact in Py2, fortunately disappeared in Py3, and you should ideally just forget about them). You can make a custom metaclass (usually subclassing type) for several advanced purposes, but it's unlikely that you'll ever need to (esp. considering that, since python 2.6, much of what used to require a custom metaclass can now be done more simply with a class decorator).
Given any class C, type(C) is its metaclass.
A parameterized class is a completely different concept. Closest you can come to it in Python is probably a factory function that makes and returns a class based on its arguments:
def silly(n):
class Silly(object):
buh = ' '.join(n * ['hello'])
return Silly
Silly1 = silly(1)
Silly2 = silly(2)
a = Silly1()
print(a.buh)
b = Silly2()
print(b.buh)
will print
hello
hello hello
Again, it's definitely not something you'll need often — making several classes that differ just by one or a few arguments. Anyway, as you can see, it has absolutely nothing to do with the classes' class (AKA metaclass), which is always type in this example (and in almost every more realistic example I could think of — I just chose to give a simple example, where the point of doing this is hard to discern, rather than a realistic and therefore necessarily very complex one ;-).
A:
This write up may be of help. And this one is an oldie but worth a read as well. I know that this doesn't fully answer your question but I hope it gives you food for thought.
| What is the difference between a parameterized class and a metaclass (code examples in Python please)? | Hello Stack Overflow contributers,
I'm a novice programmer learning Python right now, and I came upon this site which helps explain object-oriented paradigms. I know that metaclasses are classes of classes (like how meta-directories are directories of directories, etc. etc.), but I'm having trouble with something: What is the actual difference between a metaclass and a parameterized class, according to the website's definition?
If you can, please include code examples in Python that illustrate the differences between the two. Thank you for your help!
| [
"Python doesn't have (or need) \"parameterized classes\", so it's hard to provide examples of them in Python;-). A metaclass is simply \"the class of a class\": normally type (as long, in Py2, as you remember to make the class new-style by inheriting from object, or some other built-in type or other new-style clas... | [
17,
0
] | [] | [] | [
"class",
"metaclass",
"parameterized",
"python"
] | stackoverflow_0003496029_class_metaclass_parameterized_python.txt |
Q:
How to run all test-cases from several modules?
I have several modules full of test-cases and would like to create one module that runs them all. I tried loading the tests in each of the modules using TestLoader.loadTestFromModule, but it always returns empty test-suites. What is the easiest way to achieve this?
A:
Have a look at nose. It can also be called programmatically, and it may thus be used to call your tests once you've configured it.
A:
Ok, the problem there was that I handed in the modules-names as strings, when I should have been handing in module-objects like this:
import unittest
import SomeTestModule
loader = unittest.TestLoader()
loader.loadTestsFromModule(SomeTestModule)
Really a beginners mistake.
| How to run all test-cases from several modules? | I have several modules full of test-cases and would like to create one module that runs them all. I tried loading the tests in each of the modules using TestLoader.loadTestFromModule, but it always returns empty test-suites. What is the easiest way to achieve this?
| [
"Have a look at nose. It can also be called programmatically, and it may thus be used to call your tests once you've configured it.\n",
"Ok, the problem there was that I handed in the modules-names as strings, when I should have been handing in module-objects like this:\nimport unittest\nimport SomeTestModule\n\... | [
0,
0
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0003452846_python_unit_testing.txt |
Q:
How to map one list to another in python?
['a','a','b','c','c','c']
to
[2, 2, 1, 3, 3, 3]
and
{'a': 2, 'c': 3, 'b': 1}
A:
>>> x=['a','a','b','c','c','c']
>>> map(x.count,x)
[2, 2, 1, 3, 3, 3]
>>> dict(zip(x,map(x.count,x)))
{'a': 2, 'c': 3, 'b': 1}
>>>
A:
This coding should give the result:
from collections import defaultdict
myDict = defaultdict(int)
for x in mylist:
myDict[x] += 1
Of course if you want the list inbetween result, just get the values from the dict (mydict.values()).
A:
On Python ≥2.7 or ≥3.1, we have a built-in data structure collections.Counter to tally a list
>>> l = ['a','a','b','c','c','c']
>>> Counter(l)
Counter({'c': 3, 'a': 2, 'b': 1})
It is easy to build [2, 2, 1, 3, 3, 3] afterwards.
>>> c = _
>>> [c[i] for i in l] # or map(c.__getitem__, l)
[2, 2, 1, 3, 3, 3]
A:
Use a set to only count each item once, use the list method count to count them, store them in a dict with the item as key and the occurrence is value.
l=["a","a","b","c","c","c"]
d={}
for i in set(l):
d[i] = l.count(i)
print d
Output:
{'a': 2, 'c': 3, 'b': 1}
A:
a = ['a','a','b','c','c','c']
b = [a.count(x) for x in a]
c = dict(zip(a, b))
I've included Wim answer. Great idea
A:
Second one could be just
dict(zip(['a','a','b','c','c','c'], [2, 2, 1, 3, 3, 3]))
A:
For the first one:
l = ['a','a','b','c','c','c']
map(l.count,l)
A:
d=defaultdict(int)
for i in list_to_be_counted: d[i]+=1
l = [d[i] for i in list_to_be_counted]
| How to map one list to another in python? | ['a','a','b','c','c','c']
to
[2, 2, 1, 3, 3, 3]
and
{'a': 2, 'c': 3, 'b': 1}
| [
">>> x=['a','a','b','c','c','c']\n>>> map(x.count,x)\n[2, 2, 1, 3, 3, 3]\n>>> dict(zip(x,map(x.count,x)))\n{'a': 2, 'c': 3, 'b': 1}\n>>>\n\n",
"This coding should give the result:\nfrom collections import defaultdict\n\nmyDict = defaultdict(int)\n\nfor x in mylist:\n myDict[x] += 1\n\nOf course if you want the l... | [
41,
12,
7,
6,
5,
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0002401885_python.txt |
Q:
Worst practices in Django you have ever seen
What are the worst mistakes made using Django framework, that you have noticed? Have you seen some real misuses, that maybe should go as warnings to the Django docs?
A:
Too much logic in views.
I used to write views that would struggle to fit in 40 lines. Now I consider more than 2-3 indentation levels, 10 or so LOC or a handful of inline comments in a view to be code smells.
The temptation is to write minimal models, figure out your url routing, then do everything else in the view. In reality, you should be using model methods, managers, template tags, context processors, class-based views with abstract base views... anything to keep the view code simple and readable. Logic around saving forms should go in Form.save(). Logic repeated at the start or end of multiple views should go in decorators. Reused display logic should go in included templates, template tags, and filters.
Long views are hard to read, understand, and debug. Learn to use the other tools in you toolkit any you'll save yourself and your team a lot of pain.
A:
Not splitting stuff up into multiple applications. It's not so much about reusability as it is about having a dozen models, and over 100 views in one app, it's damned unreadable. Plus I like to be able to scan my urls.py file easily to see where a URL points, when I have 100 URLs that gets harder.
A:
I tried to append items to my session without copying them out, appending the items, and then adding the list back to the session.
This mistake is on a NewbieMistakes page, so hopefully I'm in good company.
This is the correct way to do it, in case anyone is curious.
sessionlist = request.session['my_list']
sessionlist.append(new_object)
request.session['my_list'] = sessionlist
A:
I think the biggest problem is that people try to code as if this were Java/C: They try to create overly generic applications that need never be changed when future requirements change (which is necessary for Java/C because those apps aren't so easy to change/redesign). What results is a hideously complicated application, which is inflexible and impossible to maintain.
It's just not necessary in Django: just write for today's requirements, build reusable apps with defined, specific tasks and make changes when needed. More and more often I find myself trying to write things as simply as possible, avoiding overly complicated designs at all costs.
A:
Monkeying around with pre-save and post-save events.
If you can't simply do it in save, you should probably rethink what you're trying to do. After all, it's just a relational database under the hood. If what you're doing gets too complex, you'll have ORM mapping issues.
Trying to write uber-generic -- one view does it all -- functionality. View functions are functions for a reason. They can use modules, packages, objects, other functions, etc. They can be short and similar without it being a code smell.
If you need to use 10 lines of code to construct the uber-generic-do-it-all object and it would have been a 12-line view function without the uber-generic-do-it-all object, then the uber-object isn't helping.
Imposing too much super-sophisticated object class design on the ORM model classes. If it requires abstract base classes or metaclasses, it won't do well in the ORM layer.
Failing to make use of tests.py and the test client to create complete unit tests of whatever it's claimed that the application does.
A:
Worst facepalm moment...returning an unlimited query, which happened to be several hundred thousand rows long. It was in a rarely used bit of code, so didn't happen often, but when it did it brought down the server.
Always make sure your query results are limited, i.e.:
results = MyModel.query.all()[:100]
not:
results = MyModel.query.all()
or use an iterator:
for result in MyModel.query.iterator():
A:
Not using raw_id fields for a key to 10000+ objects, then wondering why visiting the Admin brings a server to its knees
A:
I've experienced a worst practice : use something else that the default id as primary key of model.
It looked as a good idea but it caused some problems in the administration web site and it was difficult to restore the id as primary key on an existing database.
I think that there is no specific case that are specific enough to cause these problems. I recommend to keep the id of your model as it is by default.
See What is the best approach to change primary keys in an existing Django app? for details
A:
My worst mistake was using absolute imports like <project_name>.<app_name>.models rather than <app_name>.models. This way when I made a branch and wanted to check it out in different directory (like having and -stable of my project), it wouldn't run. I managed to revert in one project and use only relative imports in one project, but in another, larger one, we have to stick with it (we have there both absolute and relative). I won't make this mistake again.
A:
I first and fore most mistake start writing python code without reading PEP.
The worst thing i would quote are
NOTE: Things I am quoting here are DONT'S
1
foo = bar
foobar = bar
foobarbuz = bar
2
foo = "foo"
bar = "bar"
foobar = foo + bar //string concat
3
foo = [1,2,3,4,5,6]
foo_ = []
for bar in foo:
foo_.append(bar)
4
writing import statements with project name
from projectname.appname.models import model
5
Trying to use view like normal python functions
Update: or having too much logic in the view rather moving something to the helper(utils), I dint mean here its a bad practice to make a redirect, There are people who write helper functions in the view.
6
Function/method without a docstring and using namespace no way connected to the context.
| Worst practices in Django you have ever seen | What are the worst mistakes made using Django framework, that you have noticed? Have you seen some real misuses, that maybe should go as warnings to the Django docs?
| [
"Too much logic in views. \nI used to write views that would struggle to fit in 40 lines. Now I consider more than 2-3 indentation levels, 10 or so LOC or a handful of inline comments in a view to be code smells.\nThe temptation is to write minimal models, figure out your url routing, then do everything else in the... | [
27,
12,
11,
9,
5,
5,
5,
4,
3,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002058532_django_python.txt |
Q:
What's the simplest way to pass a file as an argument in a simple shell script?
The following works fine on Mac OS X:
#!/bin/bash
R CMD Sweave myfile.Rnw
pdflatex myfile.tex
open myfile.pdf
Now, I realize that these 3 lines of code are really helpful for my work – independently of some particular file. Thus I'd like to use the file as an argument. I know how to use an argument itself but have problems splitting the input after the string and concat it afterwards. If I was able to split the filename argument like:
split($1,".") # return some array or list ("name","ext")
Or is there a simpler, completely different way than using Python within a shell script?
Thx in advance for any general advice and examples as well !
A:
I do all my shell scripting in python.
It's easier to read, more powerful and works on windows as well.
A:
You could just take the base name as an argument and use $1.Rnw, $1.tex, and $1.pdf. Python is great for shell scripts, but I usually stick with bash for things less than 10 lines long.
If you really want to take a file name, you can use cut -f 1 -d '.' $1.
A:
The Python one liner would be:
python -c "print '$1'.split('.')[0]"
But Nathon's idea "Use the base name as the argument." is IMHO the best solution.
Edit:
You use "backticks" to use text that a program put on the standard output, like so:
eike@lixie:~> FOO="test.foo"
eike@lixie:~> BAR=`python -c "print '$FOO'.split('.')[0]"`
eike@lixie:~> echo $BAR
This should result in:
test
A:
I agree with Gerald's suggestion to use Makefiles, but his downside comment (dedicated makefile for each project) isn't quite correct, as Makefiles can be made more generic.
Replace $(FILE) with $@ and then invoke with "make foo".
I'd leave this as a comment to Gerald's answer but do not have the points to do so.
A:
Python is certainly a good choice for shell scripting, however for a simple example as yours using bash is easier. Yet again, for compiling LaTeX I'd recommend a makefile and using GNU make. In case you haven't heard of it, you can do sth like this:
FILE = your_tex_filename
INCLUDES = preface.tex introduction.tex framework.tex abbreviations.tex
all: $(FILE).pdf
$(FILE).pdf: $(FILE).tex $(INCLUDES) $(FILE).aux index bibliography
pdflatex $(FILE).tex
index: $(FILE).tex
makeindex $(FILE).idx
bibliography: $(FILE).bib $(FILE).aux
bibtex $(FILE)
$(FILE).aux: $(FILE).tex
pdflatex $(FILE).tex
# bbl and blg contain the bibliography
# idx and ind contain the index
.PHONY : clean
clean:
rm *.aux *.bak $(FILE).bbl $(FILE).blg \
*.flc *.idx *.ind *.log *.lof *.lot *.toc core \
*.backup *.ilg *.out *~
and then simply compile your source document w/
make
or clean up after building w/
make clean
A downside is that you'd need a dedicated makefile for each of your projects, but w/ a template that is not much of an issue.
hth
PS: A great introduction to string manipulation w/ the bash shell can be found at http://www.faqs.org/docs/abs/HTML/string-manipulation.html.
| What's the simplest way to pass a file as an argument in a simple shell script? | The following works fine on Mac OS X:
#!/bin/bash
R CMD Sweave myfile.Rnw
pdflatex myfile.tex
open myfile.pdf
Now, I realize that these 3 lines of code are really helpful for my work – independently of some particular file. Thus I'd like to use the file as an argument. I know how to use an argument itself but have problems splitting the input after the string and concat it afterwards. If I was able to split the filename argument like:
split($1,".") # return some array or list ("name","ext")
Or is there a simpler, completely different way than using Python within a shell script?
Thx in advance for any general advice and examples as well !
| [
"I do all my shell scripting in python.\nIt's easier to read, more powerful and works on windows as well.\n",
"You could just take the base name as an argument and use $1.Rnw, $1.tex, and $1.pdf. Python is great for shell scripts, but I usually stick with bash for things less than 10 lines long.\nIf you really wa... | [
6,
6,
2,
1,
0
] | [] | [] | [
"python",
"shell"
] | stackoverflow_0003496628_python_shell.txt |
Q:
Find what is in a PYC file
This may be a noobie questions, but...
So I have a pyc file that I need to use, but I don't have any documentation on it. Is there a way to find out what classes and functions are in it and what variables they take? I don't need to code, just how to run it.
Thanks
A:
As long as you can import the file, you can inspect it; it doesn't matter whether it comes from a .py or .pyc.
>>> import getopt
>>> dir(getopt)
['GetoptError', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'do_longs', 'do_shorts', 'error', 'getopt', 'gnu_getopt', 'long_has_args', 'os', 'short_has_arg']
>>> type(getopt.getopt)
<type 'function'>
>>> inspect.getargspec(getopt.getopt)
ArgSpec(args=['args', 'shortopts', 'longopts'], varargs=None, keywords=None, defaults=([],))
>>> help(getopt.getopt)
Help on function getopt in module getopt:
...
A:
if you stick it on your import path and import it by name, you can use dir
import foo
dir(foo)
you can also use `help'
help(foo)
to get the docstring. Both of these can be used on anything that foo contains as well. Note that bytecode changes between releases so it may or may not work for your version of python. If this is the case, the best that I can say is to try different versions until one works.
If you need to recover the arguments for a function, you first get the argcount
argcount = f.func_code.co_argcount
the arguments are then the first argcount variables of
f.func_code.co_varnames
This doesn't tell you what the function expects them to be and is only really useful if it doesn't have a docstring but it can be done.
A:
Easiest way http://depython.com
A:
If the code itself has docstrings, and it wasn't generated with optimizations that remove docstrings, you can import the module and peek around:
for foo.pyc
import foo
dir(foo)
help(foo)
If you decide you do need code, there's decompyle.
| Find what is in a PYC file | This may be a noobie questions, but...
So I have a pyc file that I need to use, but I don't have any documentation on it. Is there a way to find out what classes and functions are in it and what variables they take? I don't need to code, just how to run it.
Thanks
| [
"As long as you can import the file, you can inspect it; it doesn't matter whether it comes from a .py or .pyc.\n>>> import getopt\n>>> dir(getopt)\n['GetoptError', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'do_longs', 'do_shorts', 'error', 'getopt', 'gnu_getopt', 'long_has_args',... | [
9,
4,
1,
0
] | [] | [] | [
"pyc",
"python"
] | stackoverflow_0003497075_pyc_python.txt |
Q:
Tkinter: Why is one Frame overlaying another?
I am trying to build a GUI in Python using Tkinter. My idea is to build several Frames inside the root Frame. I can get 2 Frames to appear, but the third Frame overlays the second Frame. I've tried both pack() and grid() as the layout manager in the root Frame.
I want to have a "Stuff At The Top" Frame and a "Stuff At The Bottom" Frame with 1 Cat1 Frame and 1 to 8 Cat2 Frames in between. The GUI needs to be able to be dynamically rebuilt as the application discovers how many Cat2 widgets it's controlling.
(One other minor problem. Since I introduced the Cat2Frame class and moved the tkFont variables to global scope, my 12 point font is still only 9 point.)
Here's my sanitized code snippet. (Haven't gotten to the Bottom Frame yet.)
def anchor(widget, rows=0, cols=0):
"""Takes care of anchoring/stretching widgets via grid 'sticky'"""
for r in range(rows):
widget.rowconfigure(r, weight=1)
for c in range(cols):
widget.columnconfigure(c, weight=1)
font_ = None
bold_ = None
bold_12 = None
class TkinterGui():
"""Tkinter implementation of the GUI"""
def __init__(self):
"""Create the Tkinter GUI"""
self._top_level = None
self._top_row = None
self._buildGui(_TITLE)
def _buildGui(self, title):
"""Build the Tkinter GUI"""
self._top_level = Tkinter.Tk()
font_ = tkFont.Font(family='FreeSans', size=9)
bold_ = tkFont.Font(family='FreeSans', size=9, weight='bold')
bold_12 = tkFont.Font(family='FreeSans', size=12, weight='bold')
anchor(self._top_level, 4, 1)
self._top_row = 0
self._buildTop()
self._top_row = 1
self._buildCat1()
t1 = Cat2Frame(self._top_level, "Cat2 1")
self._top_row = 2
t1.place_frame(self._top_row)
t5 = Cat2Frame(self._top_level, "Cat2 5")
self._top_row = 3
t5.place_frame(self._top_row)
self._top_level.title(title)
def _buildTop(self):
"""Private method to build the Top frame of the GUI."""
top_frame = Tkinter.Frame(self._top_level, name='top_frame')
anchor(top_frame, 1, 3)
top_frame.columnconfigure(0, weight=2)
top_frame.columnconfigure(1, weight=5)
col1_label = Tkinter.Label(top_frame
, name='col1_label'
, text="Col1"
, font=bold_12
, width=20
).grid(row=0
, column=0
, sticky=N+E+W+S
)
col2_label = Tkinter.Label(top_frame
, name='col2_label'
, text="Col2"
, font=bold_12
, width=40
).grid(row=0
, column=1
, sticky=N+E+W+S
)
top_button = Tkinter.Button(top_frame
, name='top_button'
, text='Top Button'
, font=bold_
).grid(row=0
, column=2
, sticky=E
)
top_frame.grid(row=self._top_row, column=0, sticky=N+W)
def _buildCat1(self):
"""Private method to build the Cat1 frame of the GUI"""
cat1_frame = Tkinter.Frame(self._top_level, name='cat1_frame')
anchor(cat1_frame, 3, 3)
cur_row = 0
cat1_frame.columnconfigure(2, weight=6)
Tkinter.Label(cat1_frame
, name='cat1_label'
, text='Cat1'
, font=bold_
).grid(row=cur_row, column=0, sticky=N+E+W+S)
cat1_size = Tkinter.Text(cat1_frame
, name='cat1_size'
, state=DISABLED
, font=font_
, height=1
, width=10
).grid(row=cur_row
, column=1
, sticky=E
)
cat1_status = Tkinter.Text(cat1_frame
, name='cat1_status'
, state=DISABLED
, font=font_
, height=3
, width=72
).grid(row=cur_row
, column=2
, rowspan=3
, sticky=N+E+W+S
)
cur_row += 1
cat1_model = Tkinter.Text(cat1_frame
, name='cat1_model'
, state=DISABLED
, font=font_
, height=1
, width=30
).grid(row=cur_row
, column=0
, columnspan=2
, sticky=N+W
)
cur_row += 1
cat1_serial = Tkinter.Text(cat1_frame
, name='cat1_serial'
, state=DISABLED
, font=font_
, height=1
, width=30
).grid(row=cur_row
, column=0
, columnspan=2
, sticky=N+W
)
cat1_frame.grid(row=self._top_row, column=0, sticky=N+W)
class Cat2Frame():
"""Class encapsulation for a Cat2 Frame in the GUI"""
def __init__(self, parent, t_label):
"""Initialize a Cat2 Frame in the GUI"""
self._frame = Tkinter.Frame(parent, name='cat2_frame')
anchor(self._frame, 3, 4)
self.cur_row = 0
self._frame.columnconfigure(2, weight=5)
self._label = Tkinter.Label(self._frame
, name='cat2_label'
, text=t_label
, font=bold_
)
self._size = Tkinter.Text(self._frame
, name='cat2_size'
, state=DISABLED
, font=font_
, height=1
, width=10
)
self._status = Tkinter.Text(self._frame
, name='cat2_status'
, state=DISABLED
, font=font_
, height=3
, width=60
)
self._control = Tkinter.IntVar()
self._enabled = Tkinter.Radiobutton(self._frame
, name='cat2_enabled'
, variable=self._control
, text='Enabled'
, font=bold_
, value=1
)
self._model = Tkinter.Text(self._frame
, name='cat2_model'
, state=DISABLED
, font=font_
, height=1
, width=30
)
self._disabled = Tkinter.Radiobutton(self._frame
, name='cat2_disabled'
, variable=self._control
, text='Disabled'
, font=bold_
, value=0
)
self._serial = Tkinter.Text(self._frame
, name='cat2_serial'
, state=DISABLED
, font=font_
, height=1
, width=30
)
def place_frame(self, top_row):
self._label.grid(row=self.cur_row, column=0, sticky=N+E+S+W)
self._size.grid(row=self.cur_row, column=1, sticky=E)
self._status.grid(row=self.cur_row, column=2, rowspan=3, sticky=N+E+W+S)
self._enabled.grid(row=self.cur_row, column=3, sticky=W)
self.cur_row += 1
self._model.grid(row=self.cur_row, column=0, columnspan=2, sticky=N+W)
self._disabled.grid(row=self.cur_row, column=3, sticky=W)
self.cur_row += 1
self._serial.grid(row=self.cur_row, column=0, columnspan=2, sticky=N+W)
self.cur_row += 1
self._frame.grid(row=top_row, column=0, sticky=N+W)
A:
The short answer to your code is that you're giving the same name to both of your Cat2Frame objects. Either give them unique names, or don't use the name attribute for the frame.
Also, might I suggest you reconsider your programming style a bit? The way you have written your code it is very difficult to read. I've found that separating the layout from the widget creation helps immensely, and might have made finding this bug easier (by virtue of being able to see all of the layout at a glance in order to determine it is correct).
Here's a quick hack to show how you might refactor your code to be more readable. I'm not saying this is the best way to refactor the code, I'm just tossing it out as food for thought.
I'm assuming that you want all your rows to be laid out in a single grid, so each "Frame" of yours (Cat1Frame, Cat2Frame) isn't an actual frame since it is difficult to align the cells in separate widgets. If this isn't the case (ie: if each "Frame" is truly a standalone widget) the code could be made even simpler.
I didn't take the time to create the top row, nor did I take time to get all the row and column resizing exactly right. I also gave each of the text widgets a background so you can see how they are laid out. I find that solving layout problems is much simpler when you can see the boundaries of the widgets.
import Tkinter
from Tkinter import DISABLED
_TITLE="This is the title"
class TkinterGui():
def __init__(self):
self._buildGui(_TITLE)
self.last_row = 0
def _buildGui(self, title):
self._top_level = Tkinter.Tk()
self._top_level.title(title)
Cat1(self._top_level, label="Cat 1", row=1)
Cat2(self._top_level, label="Cat 2.1", row=4)
Cat2(self._top_level, label="Cat 2.2", row=7)
class Cat1:
def __init__(self, parent, label=None, row=0):
self._label = Tkinter.Label(parent, text=label)
self._size = Tkinter.Text(parent, state=DISABLED, height=1, width=10, background="bisque")
self._status = Tkinter.Text(parent, state=DISABLED, height=3, width=72, background="bisque")
self._model = Tkinter.Text(parent, state=DISABLED, height=1, width=30, background="bisque")
self._serial = Tkinter.Text(parent, state=DISABLED, height=1, width=30, background="bisque")
self._label.grid( row=row, column=0, sticky="nsew")
self._size.grid( row=row, column=1, sticky="nsew")
self._status.grid(row=row, column=2, rowspan=3, sticky="nsew")
self._model.grid( row=row+1, column=0, columnspan=2, sticky="nsew")
self._serial.grid(row=row+2, column=0, columnspan=2, sticky="nsew")
class Cat2:
def __init__(self, parent, label=None, row=0):
self._control = Tkinter.IntVar()
self._label = Tkinter.Label(parent, text=label)
self._size = Tkinter.Text(parent, state=DISABLED, height=1, width=10, background="bisque")
self._status = Tkinter.Text(parent, state=DISABLED, height=3, width=72, background="bisque")
self._model = Tkinter.Text(parent, state=DISABLED, height=1, width=30, background="bisque")
self._serial = Tkinter.Text(parent, state=DISABLED, height=1, width=30, background="bisque")
self._enabled = Tkinter.Radiobutton(parent, variable=self._control, text="Enabled", value=1)
self._disabled = Tkinter.Radiobutton(parent, variable=self._control, text="Disabled", value=0)
self._label.grid( row=row, column=0, sticky="nsew")
self._size.grid( row=row, column=1, sticky="nsew")
self._status.grid( row=row, column=2, rowspan=3, sticky="nsew")
self._model.grid( row=row+1, column=0, columnspan=2, sticky="nsew")
self._serial.grid( row=row+2, column=0, columnspan=2, sticky="nsew")
self._enabled.grid( row=row, column=3, sticky="nsew")
self._disabled.grid(row=row+1, column=3, sticky="nsew")
if __name__ == "__main__":
gui=TkinterGui()
gui._top_level.mainloop()
| Tkinter: Why is one Frame overlaying another? | I am trying to build a GUI in Python using Tkinter. My idea is to build several Frames inside the root Frame. I can get 2 Frames to appear, but the third Frame overlays the second Frame. I've tried both pack() and grid() as the layout manager in the root Frame.
I want to have a "Stuff At The Top" Frame and a "Stuff At The Bottom" Frame with 1 Cat1 Frame and 1 to 8 Cat2 Frames in between. The GUI needs to be able to be dynamically rebuilt as the application discovers how many Cat2 widgets it's controlling.
(One other minor problem. Since I introduced the Cat2Frame class and moved the tkFont variables to global scope, my 12 point font is still only 9 point.)
Here's my sanitized code snippet. (Haven't gotten to the Bottom Frame yet.)
def anchor(widget, rows=0, cols=0):
"""Takes care of anchoring/stretching widgets via grid 'sticky'"""
for r in range(rows):
widget.rowconfigure(r, weight=1)
for c in range(cols):
widget.columnconfigure(c, weight=1)
font_ = None
bold_ = None
bold_12 = None
class TkinterGui():
"""Tkinter implementation of the GUI"""
def __init__(self):
"""Create the Tkinter GUI"""
self._top_level = None
self._top_row = None
self._buildGui(_TITLE)
def _buildGui(self, title):
"""Build the Tkinter GUI"""
self._top_level = Tkinter.Tk()
font_ = tkFont.Font(family='FreeSans', size=9)
bold_ = tkFont.Font(family='FreeSans', size=9, weight='bold')
bold_12 = tkFont.Font(family='FreeSans', size=12, weight='bold')
anchor(self._top_level, 4, 1)
self._top_row = 0
self._buildTop()
self._top_row = 1
self._buildCat1()
t1 = Cat2Frame(self._top_level, "Cat2 1")
self._top_row = 2
t1.place_frame(self._top_row)
t5 = Cat2Frame(self._top_level, "Cat2 5")
self._top_row = 3
t5.place_frame(self._top_row)
self._top_level.title(title)
def _buildTop(self):
"""Private method to build the Top frame of the GUI."""
top_frame = Tkinter.Frame(self._top_level, name='top_frame')
anchor(top_frame, 1, 3)
top_frame.columnconfigure(0, weight=2)
top_frame.columnconfigure(1, weight=5)
col1_label = Tkinter.Label(top_frame
, name='col1_label'
, text="Col1"
, font=bold_12
, width=20
).grid(row=0
, column=0
, sticky=N+E+W+S
)
col2_label = Tkinter.Label(top_frame
, name='col2_label'
, text="Col2"
, font=bold_12
, width=40
).grid(row=0
, column=1
, sticky=N+E+W+S
)
top_button = Tkinter.Button(top_frame
, name='top_button'
, text='Top Button'
, font=bold_
).grid(row=0
, column=2
, sticky=E
)
top_frame.grid(row=self._top_row, column=0, sticky=N+W)
def _buildCat1(self):
"""Private method to build the Cat1 frame of the GUI"""
cat1_frame = Tkinter.Frame(self._top_level, name='cat1_frame')
anchor(cat1_frame, 3, 3)
cur_row = 0
cat1_frame.columnconfigure(2, weight=6)
Tkinter.Label(cat1_frame
, name='cat1_label'
, text='Cat1'
, font=bold_
).grid(row=cur_row, column=0, sticky=N+E+W+S)
cat1_size = Tkinter.Text(cat1_frame
, name='cat1_size'
, state=DISABLED
, font=font_
, height=1
, width=10
).grid(row=cur_row
, column=1
, sticky=E
)
cat1_status = Tkinter.Text(cat1_frame
, name='cat1_status'
, state=DISABLED
, font=font_
, height=3
, width=72
).grid(row=cur_row
, column=2
, rowspan=3
, sticky=N+E+W+S
)
cur_row += 1
cat1_model = Tkinter.Text(cat1_frame
, name='cat1_model'
, state=DISABLED
, font=font_
, height=1
, width=30
).grid(row=cur_row
, column=0
, columnspan=2
, sticky=N+W
)
cur_row += 1
cat1_serial = Tkinter.Text(cat1_frame
, name='cat1_serial'
, state=DISABLED
, font=font_
, height=1
, width=30
).grid(row=cur_row
, column=0
, columnspan=2
, sticky=N+W
)
cat1_frame.grid(row=self._top_row, column=0, sticky=N+W)
class Cat2Frame():
"""Class encapsulation for a Cat2 Frame in the GUI"""
def __init__(self, parent, t_label):
"""Initialize a Cat2 Frame in the GUI"""
self._frame = Tkinter.Frame(parent, name='cat2_frame')
anchor(self._frame, 3, 4)
self.cur_row = 0
self._frame.columnconfigure(2, weight=5)
self._label = Tkinter.Label(self._frame
, name='cat2_label'
, text=t_label
, font=bold_
)
self._size = Tkinter.Text(self._frame
, name='cat2_size'
, state=DISABLED
, font=font_
, height=1
, width=10
)
self._status = Tkinter.Text(self._frame
, name='cat2_status'
, state=DISABLED
, font=font_
, height=3
, width=60
)
self._control = Tkinter.IntVar()
self._enabled = Tkinter.Radiobutton(self._frame
, name='cat2_enabled'
, variable=self._control
, text='Enabled'
, font=bold_
, value=1
)
self._model = Tkinter.Text(self._frame
, name='cat2_model'
, state=DISABLED
, font=font_
, height=1
, width=30
)
self._disabled = Tkinter.Radiobutton(self._frame
, name='cat2_disabled'
, variable=self._control
, text='Disabled'
, font=bold_
, value=0
)
self._serial = Tkinter.Text(self._frame
, name='cat2_serial'
, state=DISABLED
, font=font_
, height=1
, width=30
)
def place_frame(self, top_row):
self._label.grid(row=self.cur_row, column=0, sticky=N+E+S+W)
self._size.grid(row=self.cur_row, column=1, sticky=E)
self._status.grid(row=self.cur_row, column=2, rowspan=3, sticky=N+E+W+S)
self._enabled.grid(row=self.cur_row, column=3, sticky=W)
self.cur_row += 1
self._model.grid(row=self.cur_row, column=0, columnspan=2, sticky=N+W)
self._disabled.grid(row=self.cur_row, column=3, sticky=W)
self.cur_row += 1
self._serial.grid(row=self.cur_row, column=0, columnspan=2, sticky=N+W)
self.cur_row += 1
self._frame.grid(row=top_row, column=0, sticky=N+W)
| [
"The short answer to your code is that you're giving the same name to both of your Cat2Frame objects. Either give them unique names, or don't use the name attribute for the frame.\nAlso, might I suggest you reconsider your programming style a bit? The way you have written your code it is very difficult to read. I'v... | [
3
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0003496819_python_tkinter.txt |
Q:
How do I access base class variables through an instance of a child class in Python?
I wanted to know how to access to the super class’s variables with a object of child class
If it makes any sense I add that some of the variables are defined in this __variable name way. Any time I want to access the variables with a child object. Python says the object with the type CHILE CLASS TYPE here is not defined. I wanted to know how I can solve this?
I also want to add that the super class is not explicitly defined and it is just imported from a module.
class AcuExcelSheet ( Worksheet ): ## super class which is imported from module
def __init__(self):
Worksheet.__init__(self)
sheet = AcuExcelSheet()
for row_index in range(sheet.nrows):
for col_index in range(sheet.ncols):
print sheet.cell(row_index,col_index).value
for row_index in range(sheet.nrows):
AttributeError: 'AcuExcelSheet' object has no attribute 'nrows'
I want to know about the syntax of this class variable’s call. Because I can see that attribute nrow has been defined in the constructor of Worksheet class.
A:
Something is wrong, but not with the code you've shown. If Worksheet truly defines .nrows, then your AcuExcelSheet will have access to it. There are a few possibilities:
Worksheet doesn't define nrows. You mention double-underscore names. Are you sure it isn't __nrows?
Worksheet defines nrows, but only for some code paths, and your invocation of the constructor doesn't hit those code paths.
A:
Forgive me if I'm misunderstanding something, but doesn't the child class automatically inherit the methods of the super class? See this for example:
>>> class A(object):
... def __init__(self):
... self.data = "GIMME TEH DATA"
...
>>> a = A()
>>> a.data
'GIMME TEH DATA'
>>> class B(A):
... pass
...
>>> b = B()
>>> b.data
'GIMME TEH DATA'
So the superclass A's init method sets the data attribute. B is the child class, and an instance of B has automatically the same data attribute initialised.
What I mean to say from this is that this part seems entirely unnecessary to me:
def __init__(self):
Worksheet.__init__(self)
(As for the rest I agree with the commenter that you'd need to either use introspection or find documentation to find out what attributes Worksheet has -- something along the lines of
>>> a = Worksheet()
>>> print dir(a)
.)
A:
There's no separated base class instance dictionary in object instances. As line
Worksheet.__init__(self)
says objects of AcuExcelSheet are initialized by Worksheet class. All may you need - to access base class method, that was redefined, you can do it just by
super(AcuExcelSheet,self).method_name
expression. So if you can't find some attributes in child class instance, maybe it needs some additional initialization.
| How do I access base class variables through an instance of a child class in Python? | I wanted to know how to access to the super class’s variables with a object of child class
If it makes any sense I add that some of the variables are defined in this __variable name way. Any time I want to access the variables with a child object. Python says the object with the type CHILE CLASS TYPE here is not defined. I wanted to know how I can solve this?
I also want to add that the super class is not explicitly defined and it is just imported from a module.
class AcuExcelSheet ( Worksheet ): ## super class which is imported from module
def __init__(self):
Worksheet.__init__(self)
sheet = AcuExcelSheet()
for row_index in range(sheet.nrows):
for col_index in range(sheet.ncols):
print sheet.cell(row_index,col_index).value
for row_index in range(sheet.nrows):
AttributeError: 'AcuExcelSheet' object has no attribute 'nrows'
I want to know about the syntax of this class variable’s call. Because I can see that attribute nrow has been defined in the constructor of Worksheet class.
| [
"Something is wrong, but not with the code you've shown. If Worksheet truly defines .nrows, then your AcuExcelSheet will have access to it. There are a few possibilities: \n\nWorksheet doesn't define nrows. You mention double-underscore names. Are you sure it isn't __nrows?\nWorksheet defines nrows, but only fo... | [
4,
2,
0
] | [] | [] | [
"inheritance",
"python"
] | stackoverflow_0003494006_inheritance_python.txt |
Q:
making paint in pyqt or qt
i have just received a task to implement a software that paints over pictures (pretty much like microsoft paint )
i have no idea where to start or how to do that. do anyone have a good reference or idea for painting in qt or pyqt ?
this will be highly appreciated
thanks in advance
A:
You'll be working with the QImage class, which represents bitmap images. It has methods for changing the colour at a given pixel using setPixel. There is am Image Viewer Example provided with Qt and PyQT should come with the same example in Python. However it uses a Qlabel to display the image so you may want to use a different widget, perhaps a custom QWidget subclass. You can start with that and add functionality to detect the mouse position in the , mouse clicks, etc and change the colours.
A:
Check out Qt painting class QPainter:
https://doc.qt.io/archives/qt-4.7/qpainter.html
A:
Have you looked at the scribble example included in PyQt? It does basic drawing, saving, loading, etc.
| making paint in pyqt or qt | i have just received a task to implement a software that paints over pictures (pretty much like microsoft paint )
i have no idea where to start or how to do that. do anyone have a good reference or idea for painting in qt or pyqt ?
this will be highly appreciated
thanks in advance
| [
"You'll be working with the QImage class, which represents bitmap images. It has methods for changing the colour at a given pixel using setPixel. There is am Image Viewer Example provided with Qt and PyQT should come with the same example in Python. However it uses a Qlabel to display the image so you may want to u... | [
4,
1,
0
] | [] | [] | [
"paint",
"pyqt",
"python",
"qt"
] | stackoverflow_0003179469_paint_pyqt_python_qt.txt |
Q:
How can I properly use multidimensional dictionaries in Cheetah for Python?
I have the following dictionary:
{0: {'Shortname': 'cabling', 'Name': 'CAT5 Cabling', 'MSRP': '$45.00'}, 1: {'Shortname': 'antenna', 'Name': 'Radio Antenna', 'MSRP': '$35.00'}}
And using Cheetah, the following section of template:
#for $item in $items
<tr>
<td>$item.Name</td>
<td>$item.MSRP</td>
</tr>
#end for
When I run the code, I get this error:
<class 'Cheetah.NameMapper.NotFound'>: cannot find 'Name'
args = ("cannot find 'Name'",)
message = "cannot find 'Name'"
In the template, line 1, in the #for declaration, I have tried separating out the key value, such as:
#for $key, $value in $items
However, I still cannot iterate over the values to get the necessary information.
Am I doing something blatantly wrong?
A:
First off, I had problems using items as the variable name in Cheetah. Might be a reserved word or something.
Something less generic might be better to use.
Secondly, since you use an outer dict with an integer as key, $item will be that integer.
Which means you look for Name in an integer. So in your case with a dict like that, you might do (with a different name of the dict too):
#for $item in $products
<td>$products[$item].Name</td>
...
#end for
A list like this would work with your template.
products = [{'Name':'prod1', ...}, {'Name': 'prod2', ...}]
| How can I properly use multidimensional dictionaries in Cheetah for Python? | I have the following dictionary:
{0: {'Shortname': 'cabling', 'Name': 'CAT5 Cabling', 'MSRP': '$45.00'}, 1: {'Shortname': 'antenna', 'Name': 'Radio Antenna', 'MSRP': '$35.00'}}
And using Cheetah, the following section of template:
#for $item in $items
<tr>
<td>$item.Name</td>
<td>$item.MSRP</td>
</tr>
#end for
When I run the code, I get this error:
<class 'Cheetah.NameMapper.NotFound'>: cannot find 'Name'
args = ("cannot find 'Name'",)
message = "cannot find 'Name'"
In the template, line 1, in the #for declaration, I have tried separating out the key value, such as:
#for $key, $value in $items
However, I still cannot iterate over the values to get the necessary information.
Am I doing something blatantly wrong?
| [
"First off, I had problems using items as the variable name in Cheetah. Might be a reserved word or something.\nSomething less generic might be better to use.\nSecondly, since you use an outer dict with an integer as key, $item will be that integer.\nWhich means you look for Name in an integer. So in your case with... | [
2
] | [] | [] | [
"cheetah",
"dictionary",
"python",
"templates"
] | stackoverflow_0003496530_cheetah_dictionary_python_templates.txt |
Q:
Defining path to module's configuration files
A Python module I'm developing has a master configuration file in /path/to/module/conf.conf. The /path/to/module/ depends on the platform (for instance, /Users/me/module in OS X, /home/me/module in Linux, etc).
Currently I define the /path/to/module in __init__.py, where I use logic:
if sys.platform == 'darwin':
ROOT = '/Users/me/module'
elif sys.platform == 'linux':
ROOT = '/home/me/module'
# et cetera
Once I have the configuration file root directory, I can open conf.conf anywhere I want.
Do you have a better methodology?
A:
Inside of your __init__.py, you could get the directory where the __init_.py script lives using the __file__ magic variable like so:
from os.path import dirname
ROOT = dirname(__file__)
Then you know that conf.conf will be located at os.path.join(ROOT, 'conf.conf').
| Defining path to module's configuration files | A Python module I'm developing has a master configuration file in /path/to/module/conf.conf. The /path/to/module/ depends on the platform (for instance, /Users/me/module in OS X, /home/me/module in Linux, etc).
Currently I define the /path/to/module in __init__.py, where I use logic:
if sys.platform == 'darwin':
ROOT = '/Users/me/module'
elif sys.platform == 'linux':
ROOT = '/home/me/module'
# et cetera
Once I have the configuration file root directory, I can open conf.conf anywhere I want.
Do you have a better methodology?
| [
"Inside of your __init__.py, you could get the directory where the __init_.py script lives using the __file__ magic variable like so:\nfrom os.path import dirname\nROOT = dirname(__file__)\n\nThen you know that conf.conf will be located at os.path.join(ROOT, 'conf.conf').\n"
] | [
2
] | [] | [] | [
"configuration",
"cross_platform",
"python"
] | stackoverflow_0003497270_configuration_cross_platform_python.txt |
Q:
Proper way to include files
I am trying to keep a somewhat organized directory structure as I plan to add more and more scripts. So lets say I have a structure like this:
/src/main.py
/src/db/<all my DB conn & table manipulation scripts>
/src/api/<all my scripts that call different APIs>
My main.py script will include certain classes from db & api folders as needed. I have the blank _____init_____.py files in each folder so they are included fine. But say I want to include a class from the db folder in a script in the api folder? Like I would need to back up one dir somehow? The api scripts fail when I have a line like this in them:
from db.Conn import QADB
I am on v2.6.
Update: I have tried a relative import, but get this?
from ..db.Conn import QADB
^ SyntaxError:
invalid syntax
A:
The way you have it setup is creating three different modules - this may or may not be what you want to do. If you want a common module which can manage different tasks you could arrange it as follows:
mymodule
|- __init__.py
|--database
| |- __init__.py
| |- dbclasses.py
|
|--api
| |- __init__.py
| |- apiclasses.py
|
|--other
[etc]
If you have it like this and want to use the API and database functionalities, you can start by saying:
from mymodule.database.dbclasses import MyDBClass
from mymodule.api.apiclasses import MyAPIClass
Notice the way you had it: the name of your top "module" was src (it was not a module because it did not have an __init__.py file).
If you use many common functionalities in the top module (from either submodule) you can include them in the top __init__.py and simply call from mymodule import MyDBClass, MyAPIClass.
Contents of top __init__.py:
from mymodule.database.dbclasses import MyDBClass
from mymodule.api.apiclasses import MyAPIClass
__all__ = ['MyDBClass', 'MyAPIClass']
A:
Use relative imports:
from ..db.Conn import QADB
A:
FWIW, I don't like that structure. Base your structure on what scripts do. What if you want to write a script that calls an external database API. Does that go in the API directory or the db directory?
And yeah, use relative inputs as awesomo suggested.
A:
Move everything under a common package:
mypkg/main.py
mypkg/db/...
mypkg/api/..
then use the absolute import
from mypkg.db.stuff import somestuff
This way you can also distribute mypkg as an egg.
| Proper way to include files | I am trying to keep a somewhat organized directory structure as I plan to add more and more scripts. So lets say I have a structure like this:
/src/main.py
/src/db/<all my DB conn & table manipulation scripts>
/src/api/<all my scripts that call different APIs>
My main.py script will include certain classes from db & api folders as needed. I have the blank _____init_____.py files in each folder so they are included fine. But say I want to include a class from the db folder in a script in the api folder? Like I would need to back up one dir somehow? The api scripts fail when I have a line like this in them:
from db.Conn import QADB
I am on v2.6.
Update: I have tried a relative import, but get this?
from ..db.Conn import QADB
^ SyntaxError:
invalid syntax
| [
"The way you have it setup is creating three different modules - this may or may not be what you want to do. If you want a common module which can manage different tasks you could arrange it as follows:\nmymodule\n |- __init__.py\n |--database\n | |- __init__.py\n | |- dbclasses.py\n | \n |--api\n | |- __init... | [
3,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003497520_python.txt |
Q:
Python: output of scapy cannot be stored in a text file?
When runnning scapy from command prompt (windows XP), the output cannot be stored. When the following command is executed in command prompt:
scapy >C:\dir.txt
The following error shows up:
C:\automation\atg\GeneralFiles_AC\ScapyExe>scapy >C:\dir.txt INFO:
Can't import python gnuplot wrapper . Won't be able to plot. INFO:
Can't import PyX. Won't be able to use psdump() or pdfdump(). INFO: No
IPv6 support in kernel WARNING: No route found for IPv6 destination :: (no default route?)
C:\Python26\lib\site-packages\scapy\crypto\cert.py:6:
DeprecationWarning?: the sh a module is deprecated; use the hashlib module instead
import os, sys, math, socket, struct, sha, hmac, string, time
C:\Python26\lib\site-packages\scapy\crypto\cert.py:7: DeprecationWarning?: The popen2 module is deprecated. Use the subprocess module.
import random, popen2, tempfile
Traceback (most recent call last):
File "C:\Python26\Scripts\\scapy", line 25, in <module>
interact()
File "C:\Python26\lib\site-packages\scapy\main.py", line 293, in interact
readline.read_history_file(conf.histfile)
File "C:\Python26\lib\site-packages\pyreadline\rlmain.py", line 183, in read_history_file
self._history.read_history_file(filename)
File "C:\Python26\lib\site-packages\pyreadline\lineeditor\history.py", line 70, in read_history_file
self.add_history(lineobj.ReadLineTextBuffer?(ensure_unicode(line.rstrip())))
File "C:\Python26\lib\site-packages\pyreadline\unicode_helper.py", line 20, in ensure_unicode
return text.decode(pyreadline_codepage, "replace")
TypeError?: decode() argument 1 must be string, not None
C:\automation\atg\GeneralFiles_AC\ScapyExe>
system specifications:
OS: windows XP
scapy version: 2.1.1-dev (using scapy-7a97e2f3db67.zip)
Python: 2.6 (PythonWin?)
| Python: output of scapy cannot be stored in a text file? | When runnning scapy from command prompt (windows XP), the output cannot be stored. When the following command is executed in command prompt:
scapy >C:\dir.txt
The following error shows up:
C:\automation\atg\GeneralFiles_AC\ScapyExe>scapy >C:\dir.txt INFO:
Can't import python gnuplot wrapper . Won't be able to plot. INFO:
Can't import PyX. Won't be able to use psdump() or pdfdump(). INFO: No
IPv6 support in kernel WARNING: No route found for IPv6 destination :: (no default route?)
C:\Python26\lib\site-packages\scapy\crypto\cert.py:6:
DeprecationWarning?: the sh a module is deprecated; use the hashlib module instead
import os, sys, math, socket, struct, sha, hmac, string, time
C:\Python26\lib\site-packages\scapy\crypto\cert.py:7: DeprecationWarning?: The popen2 module is deprecated. Use the subprocess module.
import random, popen2, tempfile
Traceback (most recent call last):
File "C:\Python26\Scripts\\scapy", line 25, in <module>
interact()
File "C:\Python26\lib\site-packages\scapy\main.py", line 293, in interact
readline.read_history_file(conf.histfile)
File "C:\Python26\lib\site-packages\pyreadline\rlmain.py", line 183, in read_history_file
self._history.read_history_file(filename)
File "C:\Python26\lib\site-packages\pyreadline\lineeditor\history.py", line 70, in read_history_file
self.add_history(lineobj.ReadLineTextBuffer?(ensure_unicode(line.rstrip())))
File "C:\Python26\lib\site-packages\pyreadline\unicode_helper.py", line 20, in ensure_unicode
return text.decode(pyreadline_codepage, "replace")
TypeError?: decode() argument 1 must be string, not None
C:\automation\atg\GeneralFiles_AC\ScapyExe>
system specifications:
OS: windows XP
scapy version: 2.1.1-dev (using scapy-7a97e2f3db67.zip)
Python: 2.6 (PythonWin?)
| [] | [] | [
"Check out the documentation on installing optional packages for Windows here.\n"
] | [
-1
] | [
"python",
"scapy",
"windows"
] | stackoverflow_0003497746_python_scapy_windows.txt |
Q:
matplotlib plot and imshow
The behavior of matplotlib's plot and imshow is confusing to me.
import matplotlib as mpl
import matplotlib.pyplot as plt
If I call plt.show() prior to calling plt.imshow(i), then an error results. If I call plt.imshow(i) prior to calling plt.show(), then everything works perfectly. However, if I close the first figure that gets opened, and then call plt.imshow(i), a new figure is displayed without ever calling plt.show().
Can someone explain this?
A:
If I call plt.show() prior to calling
plt.imshow(i), then an error results.
If I call plt.imshow(i) prior to
calling plt.show(), then everything
works perfectly.
plt.show() displays the figure (and enters the main loop of whatever gui backend you're using). You shouldn't call it until you've plotted things and want to see them displayed.
plt.imshow() draws an image on the current figure (creating a figure if there isn't a current figure). Calling plt.show() before you've drawn anything doesn't make any sense. If you want to explictly create a new figure, use plt.figure().
... a new figure is displayed without ever
calling plt.show().
That wouldn't happen unless you're running the code in something similar to ipython's pylab mode, where the gui backend's main loop will be run in a separate thread...
Generally speaking, plt.show() will be the last line of your script. (Or will be called whenever you want to stop and visualize the plot you've made, at any rate.)
Hopefully that makes some more sense.
| matplotlib plot and imshow | The behavior of matplotlib's plot and imshow is confusing to me.
import matplotlib as mpl
import matplotlib.pyplot as plt
If I call plt.show() prior to calling plt.imshow(i), then an error results. If I call plt.imshow(i) prior to calling plt.show(), then everything works perfectly. However, if I close the first figure that gets opened, and then call plt.imshow(i), a new figure is displayed without ever calling plt.show().
Can someone explain this?
| [
"\nIf I call plt.show() prior to calling\nplt.imshow(i), then an error results.\nIf I call plt.imshow(i) prior to\ncalling plt.show(), then everything\nworks perfectly.\n\nplt.show() displays the figure (and enters the main loop of whatever gui backend you're using). You shouldn't call it until you've plotted thin... | [
40
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0003497578_matplotlib_python.txt |
Q:
python try/finally for flow control
I'm sure this concept has come up before but I can't find a good, simple answer. Is using try/finally a bad way to handle functions with multiple returns? For example I have
try:
if x:
return update(1)
else:
return update(2)
finally:
notifyUpdated()
This just seems nicer than storing update() commands in a temporary variable and returning that.
A:
I wouldn't recommend it. First because notifyUpdated() will be called even if the code in either branch throws an exception. You would need something like this to really get the intended behavior:
try:
if x:
return update(1)
else:
return update(2)
except:
raise
else:
notifyUpdated()
Secondly, because try blocks generally indicate you're doing some kind of exception handling, and you aren't, you're just using them for convenience. So this construct will confuse people.
For example, I don't think either of the first two people (at least one of which deleted their answer) to answer your question realized what you were really trying to do. Confusing code is bad, no matter how convenient and clever it seems.
A:
I would not use try/finally for flow that doesn't involve exceptions. It's too tricky for its own good.
This is better:
if x:
ret = update(1)
else:
ret = update(2)
notifyUpdated()
return ret
A:
I think you mean you want to use try/finally as an alternative to this:
if x:
result = update(1)
else:
result = update(2)
notifyUpdated()
return result
I guess this is a matter of style. For me I like to reserve try for handling exceptional conditional. I won't use it as a flow control statement.
A:
I think this is asking for trouble. What happens later, when you change your code to the following?
try:
if x:
return update(1)
elif y:
return update(2)
else:
return noUpdateHere()
finally:
notifyUpdated() # even if noUpdateHere()!
At best, it's a stumbling point for most readers of your code (probably even you in six months), because it's using try/finally for a purpose that differs from the normal use patterns. And the typing it saves is minimal, anyway.
A:
I think a decorator is a better idea here
def notifyupdateddecorator(f):
def inner(*args, **kw):
retval = f(*args, **kw)
notifyUpdated()
return retval
return inner
@notifyupdateddecorator
def f(x):
if x:
return update(1)
else:
return update(2)
@notifyupdateddecorator
def g(x):
return update(1 if x else 2)
A:
from http://docs.python.org/library/contextlib.html:
from contextlib import closing
import urllib
with closing(urllib.urlopen('http://www.python.org')) as page:
for line in page:
print line
so you can create a similar function and use it
| python try/finally for flow control | I'm sure this concept has come up before but I can't find a good, simple answer. Is using try/finally a bad way to handle functions with multiple returns? For example I have
try:
if x:
return update(1)
else:
return update(2)
finally:
notifyUpdated()
This just seems nicer than storing update() commands in a temporary variable and returning that.
| [
"I wouldn't recommend it. First because notifyUpdated() will be called even if the code in either branch throws an exception. You would need something like this to really get the intended behavior:\ntry:\n if x:\n return update(1)\n else:\n return update(2)\nexcept:\n raise\nelse:\n noti... | [
11,
11,
3,
3,
3,
0
] | [] | [] | [
"control_flow",
"python",
"try_catch_finally"
] | stackoverflow_0003497371_control_flow_python_try_catch_finally.txt |
Q:
Why can't I write all the data from sys.stdin to a file in Windows?
I am trying to read binary data from sys.stdin using Python 2.7 on Windows XP. The binary data is a WAV file decoded by foobar2000. Normally, this data is sent to a command-line encoder such as lame.exe on stdin, where it is processed and written to an output file whose name is provided in the command-line arguments. I am trying to intercept the WAV data that is output and send it to another file. However, I can only get a few KB from stdin before the pipeline apparently collapses, and so I am left with only a very short (about 75 KB) WAV file, instead of the several tens of megabytes that I am expecting. What might be causing this? I have been careful to open both sys.stdin and the output file as binary files.
from __future__ import print_function
import os
import os.path
import sys
sys.stdin = os.fdopen(sys.stdin.fileno(), 'rb', 0) # Make sys.stdin binary
wave_fname = os.path.join(os.environ['USERPROFILE'], 'Desktop',
'foobar_test.wav')
try:
os.remove(wave_fname)
except Exception:
pass
CHUNKSIZE = 8192
wave_f = open(wave_fname, 'wb')
try:
bytes_read = sys.stdin.read(CHUNKSIZE)
while bytes_read:
for b in bytes_read:
wave_f.write(b)
bytes_read = sys.stdin.read(CHUNKSIZE)
finally:
pass
wave_f.close()
A:
Suggestion: maybe you need to use msvcrt.setmode(fd, flags) where fd is sys.stdin.fileno()
| Why can't I write all the data from sys.stdin to a file in Windows? | I am trying to read binary data from sys.stdin using Python 2.7 on Windows XP. The binary data is a WAV file decoded by foobar2000. Normally, this data is sent to a command-line encoder such as lame.exe on stdin, where it is processed and written to an output file whose name is provided in the command-line arguments. I am trying to intercept the WAV data that is output and send it to another file. However, I can only get a few KB from stdin before the pipeline apparently collapses, and so I am left with only a very short (about 75 KB) WAV file, instead of the several tens of megabytes that I am expecting. What might be causing this? I have been careful to open both sys.stdin and the output file as binary files.
from __future__ import print_function
import os
import os.path
import sys
sys.stdin = os.fdopen(sys.stdin.fileno(), 'rb', 0) # Make sys.stdin binary
wave_fname = os.path.join(os.environ['USERPROFILE'], 'Desktop',
'foobar_test.wav')
try:
os.remove(wave_fname)
except Exception:
pass
CHUNKSIZE = 8192
wave_f = open(wave_fname, 'wb')
try:
bytes_read = sys.stdin.read(CHUNKSIZE)
while bytes_read:
for b in bytes_read:
wave_f.write(b)
bytes_read = sys.stdin.read(CHUNKSIZE)
finally:
pass
wave_f.close()
| [
"Suggestion: maybe you need to use msvcrt.setmode(fd, flags) where fd is sys.stdin.fileno() \n"
] | [
2
] | [] | [] | [
"binary_data",
"io",
"python",
"windows"
] | stackoverflow_0003497879_binary_data_io_python_windows.txt |
Q:
Python List Help
I have a list of lists that looks like:
floodfillque = [[1,1,e],[1,2,w], [1,3,e], [2,1,e], [2,2,e], [2,3,w]]
for each in floodfillque:
if each[2] == 'w':
floodfillque.remove(each)
else:
tempfloodfill.append(floodfillque[each[0+1][1]])
That is a simplified, but I think relevant part of the code.
Does the floodfillque[each[0+1]] part do what I think it is doing and taking the value at that location and adding one to it or no? The reason why I ask is I get this error:
TypeError: 'int' object is unsubscriptable
And I think I am misunderstanding what that code is actually doing or doing it wrong.
A:
In addition to the bug in your code that other answers have already spotted, you have at least one more:
for each in floodfillque:
if each[2] == 'w':
floodfillque.remove(each)
don't add or remove items from the very container you're looping on. While such a bug will usually be diagnosed only for certain types of containers (not including lists), it's just as terrible for lists -- it will end up altering your intended semantics by skipping some items or seeing some items twice.
If you can't substantially alter and enhance your logic (generally by building a new, separate container rather than mucking with the one you're looping on), the simplest workaround is usually to loop on a copy of the container you must alter:
for each in list(floodfillque):
Now, your additions and removals won't alter what you're actually looping on (because what you're looping on is a copy, a "snapshot", made once and for all at loop's start) so your semantics will work as intended.
Your specific approach to altering floodfillque also has a performance bug -- it behaves quadratically, while sound logic (building a new container rather than altering the original one) would behave linearly. But, that bug is harder to fix without refactoring your code from the current not-so-nice logic to the new, well-founded one.
A:
Here's what's happening:
On the first iteration of the loop, each is [1, 1, 'e']. Since each[2] != 'w', the else is executed.
In the else, you take each[0+1][1], which is the same as (each[0+1])[1]. each[0+1] is 1, and so you are doing (1)[1]. int objects can't be indexed, which is what's raising the error.
A:
Does the floodfillque[each[0+1] part
do what I think it is doing and taking
the value at that location and adding
one to it or no?
No, it sounds like you want each[0] + 1.
Either way, the error you're getting is because you're trying to take the second item of an integer... each[0+1][1] resolves to each[1][1] which might be something like 3[1], which doesn't make any sense.
A:
The other posters are correct. However, there is another bug in this code, which is that you are modifying floodfillque as you are iterating over it. This will cause problems, because Python internally maintains a counter to handle the loop, and deleting elements does not modify the counter.
The safe way to do this is to iterate of a copy of the loop:
for each in floodfillque[ : ]:
([ : ] is Python's notation for a copy.)
A:
Here is how I understand NoahClark's intentions:
Remove those sublists whose third element is 'w'
For the remaining sublist, add 1 to the second item
If this is the case, the following will do:
# Here is the original list
floodfillque = [[1,1,'e'], [1,2,'w'], [1,3,'e'], [2,1,'e'], [2,2,'e'], [2,3,'w']]
# Remove those sublists which have 'w' as the third element
# For the rest, add one to the second element
floodfillque = [[a,b+1,c] for a,b,c in floodfillque if c != 'w']
This solution works fine, but it is not the most efficient: it creates a new list instead of patching up the original one.
| Python List Help | I have a list of lists that looks like:
floodfillque = [[1,1,e],[1,2,w], [1,3,e], [2,1,e], [2,2,e], [2,3,w]]
for each in floodfillque:
if each[2] == 'w':
floodfillque.remove(each)
else:
tempfloodfill.append(floodfillque[each[0+1][1]])
That is a simplified, but I think relevant part of the code.
Does the floodfillque[each[0+1]] part do what I think it is doing and taking the value at that location and adding one to it or no? The reason why I ask is I get this error:
TypeError: 'int' object is unsubscriptable
And I think I am misunderstanding what that code is actually doing or doing it wrong.
| [
"In addition to the bug in your code that other answers have already spotted, you have at least one more:\nfor each in floodfillque:\n if each[2] == 'w':\n floodfillque.remove(each)\n\ndon't add or remove items from the very container you're looping on. While such a bug will usually be diagnosed only for... | [
5,
4,
3,
3,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0003494615_list_python.txt |
Q:
How to implement substring algorithm
I am trying to implement an algorithm to take a string of length n and returns all substrings with a length of 2 or greater.
If the user inputs a string e.g "abcd", then the output should be
ab, bc, cd, abc, bcd, abcd.
a=input("Ente the input")
list=[]
com=""
for k in range(2,len(a)+1):
for x in range(k,len(a)+1):
com=""
for j in range(x-k,k);
com=com+a[j]
print com
list1.append(com)
print list1
A:
>>> [ a[ index : index + length ] for index in range( len( a ) - 1 ) for length in range( 2, len( a ) - index + 1 ) ]
['ab', 'abc', 'abcd', 'bc', 'bcd', 'cd']
If you need the list sorted:
>>> sorted( [ a[ index : index + length ] for index in range( len( a ) - 1 ) for length in range( 2, len( a ) - index + 1 ) ], key = len )
['ab', 'bc', 'cd', 'abc', 'bcd', 'abcd']
There is something seriously wrong with your algorithm, because it should only take two loops to do this (one for starting index and one for length of substring). I don't understand what you were trying to do, though, so I can't attempt to fix it.
EDIT: I get it -- you're copying the strings character by character! Are you a C programmer by any chance? =p You don't have to do that sort of thing in Python; it's a higher-level language. If you slice a string (a[1:3]) you will get a substring of it, which you can append to a list or otherwise store. In the above, we iterate first over all indices up to the end of the string (minus one because "d" is not a valid substring) and then over all lengths of substring that will 'fit'. This yields all possible substrings; we can use list comprehension notation to make a list of them very easily.
A:
from itertools import combinations
map(lambda i: a[i[0]:i[1]+1],combinations(range(len(a)),2))
A:
minlength = 2
def sub(string):
return [string[start:start+length]
for length in xrange(minlength, len(string) + 1)
for start in xrange(len(string) - length + 1) ]
print sub('abcd')
['ab', 'bc', 'cd', 'abc', 'bcd', 'abcd']
A:
If you want to output the results from shortest to longest
>>> s="abcd"
>>> for substrlength in range(2, len(s)+1):
... for start in range(len(s)+1-substrlength):
... print s[start:start+substrlength]
...
ab
bc
cd
abc
bcd
abcd
To store the results in a list
>>> s="abcd"
>>> resultlist=[]
>>> for substrlength in range(2, len(s)+1):
... for start in range(len(s)+1-substrlength):
... resultlist.append(s[start:start+substrlength])
...
>>> print resultlist
['ab', 'bc', 'cd', 'abc', 'bcd', 'abcd']
A:
Here is a bug fixed version of your code to compare, but there are better ways to write it here
a=raw_input("Enter the input")
list1=[]
com=""
for k in range(2,len(a)+1):
for x in range(k,len(a)+1):
com=""
for j in range(x-k,x):
com=com+a[j]
print com
list1.append(com)
print list1
A:
In python 2.6 they added some cool functions that makes this quite easy:
from itertools import combinations
def substrings(text, length=2):
textlen = len(text)
for low, hi in combinations(range(textlen), 2):
if hi-low >= length:
yield text[low:hi]
s = raw_input("Enter the input: ")
for substr in substrings(s):
print len(substr), repr(substr)
Note that substrings() is a generator (see the yield statement), which is more memory efficient, but if you really need a list, you can say mylist = list(substrings('foo'))
I've also added an argument to substrings if you ever want to generate substrings of some other length.
A:
A concise, recursive version, for good measure:
def substr(s, min_len):
if len(s) < min_len:
return []
return [s[i:i+min_len] for i in range(len(s) - min_len + 1)] + substr(s, min_len + 1)
| How to implement substring algorithm | I am trying to implement an algorithm to take a string of length n and returns all substrings with a length of 2 or greater.
If the user inputs a string e.g "abcd", then the output should be
ab, bc, cd, abc, bcd, abcd.
a=input("Ente the input")
list=[]
com=""
for k in range(2,len(a)+1):
for x in range(k,len(a)+1):
com=""
for j in range(x-k,k);
com=com+a[j]
print com
list1.append(com)
print list1
| [
">>> [ a[ index : index + length ] for index in range( len( a ) - 1 ) for length in range( 2, len( a ) - index + 1 ) ]\n['ab', 'abc', 'abcd', 'bc', 'bcd', 'cd']\n\nIf you need the list sorted:\n>>> sorted( [ a[ index : index + length ] for index in range( len( a ) - 1 ) for length in range( 2, len( a ) - index + 1 ... | [
2,
2,
1,
0,
0,
0,
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0003496047_algorithm_python.txt |
Q:
In Python is it bad to create an attribute called 'id'?
I know that there's a function called id so I wouldn't create a function or a variable called id, but what about an attribute on an object?
A:
That's ok, and is pretty common. For example, objects mapped to a database record will often have an "id" attribute mapped to the database "id" column value.
Attributes are always "namespaced" so you have to refer to them via self.id or obj.id so there's no conflict with the built-in function.
A:
I do this frequently for classes that abstract database tables where there is often a field called id because there is no reasonable chance of a name conflict. Be advised that some synatax highlighters will mark it as a builtin function.
A:
As others have said, it's perfectly fine to have an id attribute, although many consider a bad practice for database design. But that's another question.
If you care about conventions in general, you should check out pylint. This tool analyses your code for errors and also convention problems.
http://www.logilab.org/857
| In Python is it bad to create an attribute called 'id'? | I know that there's a function called id so I wouldn't create a function or a variable called id, but what about an attribute on an object?
| [
"That's ok, and is pretty common. For example, objects mapped to a database record will often have an \"id\" attribute mapped to the database \"id\" column value.\nAttributes are always \"namespaced\" so you have to refer to them via self.id or obj.id so there's no conflict with the built-in function.\n",
"I do ... | [
40,
7,
1
] | [] | [] | [
"python"
] | stackoverflow_0003497883_python.txt |
Q:
Python: openssl segmentation fault
I followed the instrunction on this site http://paltman.com/2007/nov/15/getting-ssl-support-in-python-251/ to install openssl.
When I go to test i get this as the output:
test_rude_shutdown ...
test_basic ...
Segmentation fault
How would I resolve this?
A:
First, make sure which python returns /usr/local/bin/python. If not, use the Python you just built instead of your system copy! If it does, try creating a crash dump.
Before running the tests:
ulimit -c unlimited
Then run the crashy test again. Take the file which materializes in your current directory. It's a crash dump. Open a bug report, attach the dump, and ask the Python folks for help.
| Python: openssl segmentation fault | I followed the instrunction on this site http://paltman.com/2007/nov/15/getting-ssl-support-in-python-251/ to install openssl.
When I go to test i get this as the output:
test_rude_shutdown ...
test_basic ...
Segmentation fault
How would I resolve this?
| [
"First, make sure which python returns /usr/local/bin/python. If not, use the Python you just built instead of your system copy! If it does, try creating a crash dump.\nBefore running the tests:\nulimit -c unlimited\nThen run the crashy test again. Take the file which materializes in your current directory. It'... | [
1
] | [] | [] | [
"openssl",
"python"
] | stackoverflow_0003498263_openssl_python.txt |
Q:
organising classes and modules in python
I'm getting a bit of a headache trying to figure out how to organise modules and classes together. Coming from C++, I'm used to classes encapsulating all the data and methods required to process that data. In python there are modules however and from code I have looked at, some people have a lot of loose functions stored in modules, whereas others almost always bind their functions to classes as methods.
For example say I have a data structure and would like to write it to disk.
One way would be to implement a save method for that object so that I could just type
MyObject.save(filename)
or something like that. Another method I have seen in equal proportion is to have something like
from myutils import readwrite
readwrite.save(MyObject,filename)
This is a small example, and I'm not sure how python specific this problem is at all, but my general question is what is the best pythonic practice in terms of functions vs methods organisation?
A:
It seems like loose functions bother you. This is the python way. It makes sense because a module in python is really just an object on the same footing as any other object. It does have language level support for loading it from a file but other than that, it's just an object.
so if I have a module foo.py:
import pprint
def show(obj):
pprint(obj)
Then the when I import it from bar.py
import foo
class fubar(object):
#code
def method(self, obj):
#more stuff
foo.show(obj)
I am essentially accessing a method on the foo object. The data attributes of the foo module are just the globals that are defined in foo. A module is the language level implementation of a singleton without the need to prepend self to every methods argument list.
I try to write as many module level functions as possible. If some function will only work with an instance of a particular class, I will make it a method on the class. Otherwise, I try to make it work on instances of every class that is defined in the module for which it would make sense.
The rational behind the exact example that you gave is that if each class has a save method, then if you later change how you are saving data (from say filesystem to database or remote XML file) then you have to change every class. If each class implements an interface to yield that data that it wants saved, then you can write one function to save instances of every class and only change that function once. This is known as the Single Responsibility Principle: Each class should have only one reason to change.
A:
If you have a regular old class you want to save to disk, I would just make it an instance method. If it were a serialization library that could handle different types of objects I would do the second way.
| organising classes and modules in python | I'm getting a bit of a headache trying to figure out how to organise modules and classes together. Coming from C++, I'm used to classes encapsulating all the data and methods required to process that data. In python there are modules however and from code I have looked at, some people have a lot of loose functions stored in modules, whereas others almost always bind their functions to classes as methods.
For example say I have a data structure and would like to write it to disk.
One way would be to implement a save method for that object so that I could just type
MyObject.save(filename)
or something like that. Another method I have seen in equal proportion is to have something like
from myutils import readwrite
readwrite.save(MyObject,filename)
This is a small example, and I'm not sure how python specific this problem is at all, but my general question is what is the best pythonic practice in terms of functions vs methods organisation?
| [
"It seems like loose functions bother you. This is the python way. It makes sense because a module in python is really just an object on the same footing as any other object. It does have language level support for loading it from a file but other than that, it's just an object.\nso if I have a module foo.py:\nimpo... | [
16,
3
] | [] | [] | [
"class",
"module",
"oop",
"python"
] | stackoverflow_0003498200_class_module_oop_python.txt |
Q:
Help with multiline regex match
I am trying to have a regular expression match a value that spans multiple lines. I am using the re.S flag, but still get no results. Any ideas why?
This is the text that I am searching through:
<File id="abc.txt" EngRev="74">
<Identifier id="STRING_ID" isArray="1" goesWith="3027253">
<EngTranslation>"Value 1","Value 2","Value 3","Value 4","Value 5",</EngTranslation>
<LangTranslation filename="abc.txt" key="STRING_ID 0">Value 1</LangTranslation>
<array filename="abc.txt" key="STRING_ID 1">Value 2</array>
<array filename="abc.txt" key="STRING_ID 2">Value 3</array>
<array filename="abc.txt" key="STRING_ID 3">Value 4</array>
<array filename="abc.txt" key="STRING_ID 4">Value 5</array>
</Identifier>
<Identifier id="STRING_ID2" isArray="0" goesWith="3027253">
<EngTranslation>"Value 1"</EngTranslation>
<LangTranslation filename="abc.txt" key="STRING_ID2">Value 1</LangTranslation>
</Identifier>
</File>
This is the code I am using to obtain a match:
def updateToArray(matchobj):
return matchobj.group(0).replace('LangTranslation','array')
outXML = re.sub(r'<Identifier.*?<array.*?</Identifier>', updateToArray, outXML, re.S)
A:
I strongly urge you to not use regular expressions for parsing XML. SO has a lot of question/answer threads explaining why. For instance see this classic.
Since you are using Python why not use libraries like BeautifulSoup or Lxml to do the job much more cleanly and concisely?
A:
You're missing an argument:
re.sub(pattern, repl, string[, count, flags])
The flags appear to be integers, so it's treating re.S as the count argument. Using zero for count preserves the default behavior and allows you to pass the flags as the fifth argument.
| Help with multiline regex match | I am trying to have a regular expression match a value that spans multiple lines. I am using the re.S flag, but still get no results. Any ideas why?
This is the text that I am searching through:
<File id="abc.txt" EngRev="74">
<Identifier id="STRING_ID" isArray="1" goesWith="3027253">
<EngTranslation>"Value 1","Value 2","Value 3","Value 4","Value 5",</EngTranslation>
<LangTranslation filename="abc.txt" key="STRING_ID 0">Value 1</LangTranslation>
<array filename="abc.txt" key="STRING_ID 1">Value 2</array>
<array filename="abc.txt" key="STRING_ID 2">Value 3</array>
<array filename="abc.txt" key="STRING_ID 3">Value 4</array>
<array filename="abc.txt" key="STRING_ID 4">Value 5</array>
</Identifier>
<Identifier id="STRING_ID2" isArray="0" goesWith="3027253">
<EngTranslation>"Value 1"</EngTranslation>
<LangTranslation filename="abc.txt" key="STRING_ID2">Value 1</LangTranslation>
</Identifier>
</File>
This is the code I am using to obtain a match:
def updateToArray(matchobj):
return matchobj.group(0).replace('LangTranslation','array')
outXML = re.sub(r'<Identifier.*?<array.*?</Identifier>', updateToArray, outXML, re.S)
| [
"I strongly urge you to not use regular expressions for parsing XML. SO has a lot of question/answer threads explaining why. For instance see this classic.\nSince you are using Python why not use libraries like BeautifulSoup or Lxml to do the job much more cleanly and concisely? \n",
"You're missing an argument:\... | [
7,
1
] | [] | [] | [
"python",
"regex",
"xml"
] | stackoverflow_0003495700_python_regex_xml.txt |
Q:
Upload an image file using python
Is there a way of uploading an image file using python ?. Im able to upload files from a simple html page consisting of the code below.But i would like to be able to do that from a python program. Can it be done using urllib2 module ?. Any example i can refer to ?
Please help.
Thank You.
<form action="http://somesite.com/handler.php" method="post" enctype="multipart/form-data">
<table>
<tr><td>File:</td><td><input type="file" name="file" /></td></tr>
<tr><td><input type="submit" value="Upload" /></td></tr>
</table>
</form>
A:
You can use pycurl package for that.
from StringIO import StringIO
from pycurl import *
c = Curl()
d = StringIO()
h = StringIO()
c.setopt(URL, "http://somesite.com/handler.php")
c.setopt(POST, 1)
c.setopt(HTTPPOST, [('file', (FORM_FILE, '/path/to/file')), ('submit', 'Upload')])
c.setopt(WRITEFUNCTION, d.write)
c.setopt(HEADERFUNCTION, h.write)
c.perform()
c.close()
A:
You need to do multipart:
http://code.activestate.com/recipes/146306-http-client-to-post-using-multipartform-data/
| Upload an image file using python | Is there a way of uploading an image file using python ?. Im able to upload files from a simple html page consisting of the code below.But i would like to be able to do that from a python program. Can it be done using urllib2 module ?. Any example i can refer to ?
Please help.
Thank You.
<form action="http://somesite.com/handler.php" method="post" enctype="multipart/form-data">
<table>
<tr><td>File:</td><td><input type="file" name="file" /></td></tr>
<tr><td><input type="submit" value="Upload" /></td></tr>
</table>
</form>
| [
"You can use pycurl package for that.\nfrom StringIO import StringIO\nfrom pycurl import *\nc = Curl()\nd = StringIO()\nh = StringIO()\nc.setopt(URL, \"http://somesite.com/handler.php\")\nc.setopt(POST, 1)\nc.setopt(HTTPPOST, [('file', (FORM_FILE, '/path/to/file')), ('submit', 'Upload')])\nc.setopt(WRITEFUNCTION, d... | [
6,
0
] | [] | [] | [
"python"
] | stackoverflow_0003497969_python.txt |
Q:
How to filter columns in two tables with many-to-many relation?
I have this table:
channel_items = Table(
"channel_items",
metadata,
Column("channel_id", Integer, ForeignKey("channels.id")),
Column("media_item_id", Integer, ForeignKey("media_items.id"))
)
class Channel(rdb.Model):
"""Set up channels table in the database"""
rdb.metadata(metadata)
rdb.tablename("channels")
id = Column("id", Integer, primary_key=True)
title = Column("title", String(100))
items = relationship("MediaItem", secondary=channel_items, order_by="MediaItem.titleView", backref="channels")
class MediaItem(rdb.Model):
"""Set up items table in the database"""
rdb.metadata(metadata)
rdb.tablename("media_items")
id = Column("id", Integer, primary_key=True)
title = Column("title", String(100))
type = Column("type", String(50))
I'd like to make a query, but filtering the second table. Something like:
channels = session.query(Channel).options(eagerload("item")).filter(MediaItem == "jpg").all()
Thanks in advance!
A:
You just reference it through relation name. Also, its 'items' in your scheme, not 'item'.
channels = session.query(Channel).options(eagerload("items")).filter(Channel.items.type == "jpg").all()
| How to filter columns in two tables with many-to-many relation? | I have this table:
channel_items = Table(
"channel_items",
metadata,
Column("channel_id", Integer, ForeignKey("channels.id")),
Column("media_item_id", Integer, ForeignKey("media_items.id"))
)
class Channel(rdb.Model):
"""Set up channels table in the database"""
rdb.metadata(metadata)
rdb.tablename("channels")
id = Column("id", Integer, primary_key=True)
title = Column("title", String(100))
items = relationship("MediaItem", secondary=channel_items, order_by="MediaItem.titleView", backref="channels")
class MediaItem(rdb.Model):
"""Set up items table in the database"""
rdb.metadata(metadata)
rdb.tablename("media_items")
id = Column("id", Integer, primary_key=True)
title = Column("title", String(100))
type = Column("type", String(50))
I'd like to make a query, but filtering the second table. Something like:
channels = session.query(Channel).options(eagerload("item")).filter(MediaItem == "jpg").all()
Thanks in advance!
| [
"You just reference it through relation name. Also, its 'items' in your scheme, not 'item'.\nchannels = session.query(Channel).options(eagerload(\"items\")).filter(Channel.items.type == \"jpg\").all()\n\n"
] | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0003497912_python_sqlalchemy.txt |
Q:
Using Linux redirect to overwrite file from Python script
I have a simple python script that just takes in a filename, and spits out a modified version of that file. I would like to redirect stdout (using '>' from the command line) so that I can use my script to overwrite a file with my modifications, e.g. python myScript.py test.txt > test.txt
When I do this, the resulting test.txt does not contain any text from the original test.txt - just the additions made by myScript.py. However, if I don't redirect stdout, then the modifications come out correctly.
To be more specific, here's an example:
myScript.py:
#!/usr/bin/python
import sys
fileName = sys.argv[1]
sys.stderr.write('opening ' + fileName + '\n')
fileHandle = file(fileName)
currFile = fileHandle.read()
fileHandle.close()
sys.stdout.write('MODIFYING\n\n' + currFile + '\n\nMODIFIED!\n')
test.txt
Hello World
Result of python myScript.py test.txt > test.txt:
MODIFYING
MODIFIED!
A:
The reason it works that way is that, before Python even starts, Bash interprets the redirection operator and opens an output stream to write stdout to the file. That operation truncates the file to size 0 - in other words, it clears the contents of the file. So by the time your Python script starts, it sees an empty input file.
The simplest solution is to redirect stdout to a different file, and then afterwards, rename it to the original filename.
python myScript.py test.txt > test.out && mv test.out test.txt
Alternatively, you could alter your Python script to write the modified data back to the file itself, so you wouldn't have to redirect standard output at all.
A:
Try redirecting it to a new file, the redirect operator probably deletes the file just before appending.
A:
The utility sponge present in the moreutils package in Debian can handle this gracefully.
python myScript.py test.txt | sponge test.txt
As indicated by its name, sponge will drain its standard input completely before opening test.txt and writing out the full contents of stdin.
You can get the latest version of sponge here. The moreutils home page is here.
| Using Linux redirect to overwrite file from Python script | I have a simple python script that just takes in a filename, and spits out a modified version of that file. I would like to redirect stdout (using '>' from the command line) so that I can use my script to overwrite a file with my modifications, e.g. python myScript.py test.txt > test.txt
When I do this, the resulting test.txt does not contain any text from the original test.txt - just the additions made by myScript.py. However, if I don't redirect stdout, then the modifications come out correctly.
To be more specific, here's an example:
myScript.py:
#!/usr/bin/python
import sys
fileName = sys.argv[1]
sys.stderr.write('opening ' + fileName + '\n')
fileHandle = file(fileName)
currFile = fileHandle.read()
fileHandle.close()
sys.stdout.write('MODIFYING\n\n' + currFile + '\n\nMODIFIED!\n')
test.txt
Hello World
Result of python myScript.py test.txt > test.txt:
MODIFYING
MODIFIED!
| [
"The reason it works that way is that, before Python even starts, Bash interprets the redirection operator and opens an output stream to write stdout to the file. That operation truncates the file to size 0 - in other words, it clears the contents of the file. So by the time your Python script starts, it sees an em... | [
7,
1,
1
] | [] | [] | [
"linux",
"python",
"redirect",
"shell"
] | stackoverflow_0003498106_linux_python_redirect_shell.txt |
Q:
how to write a Python debugger/editor
Sorry for the kind of general question. More details about what I want:
I want the user to be able to write some Python code and execute it. Once there is an exception which is not handled, I want the debugger to pause the execution, show information about the current state/environment/stack/exception and make it possible to edit the code.
I only want to have the special code block editable where the exception occurred and nothing else (for now). I.e. if it occurred inside a for loop, I only want to have the code block inside the for loop editable. It should be the latest/most recent code block which is in the user editor scope (and not inside some other libs or the Python libs). Under this conditions, it is always clear what code block to edit.
I already tried to investigate a bit how to do this, though I feel a bit lost.
The Python traceback doesn't give me directly the code block, just the function and the code line. I could calculate that back but that seems a bit hacky to me. Better (and more natural) would be if I could somehow get a reference to the code block in the AST of the code.
To get the AST (and operate on it, i.e. manipulate/edit), I probably will use the compiler (which is deprecated?) and/or the parser module. Or the ast module. Not sure though how I could recompile special nodes / code blocks in the AST. Or if I only can recompile whole functions.
A:
Playing around with ast and compile (built-in) it seems that you could possibly use the NodeTransformer to modify some nodes... You can also edit them manually if you know what you're looking for.
test.py
print 'Dumb Guy'
x = 4 + 4
print x * 3
change.py
import ast
with open('test.py') as f:
expr = f.read()
e = ast.parse(expr)
e.body[0].values[0].s = 'Cool Guy' # Replace the string
e.body[1].targets[0].id = 'herring' # Change x to herring
e.body[2].values[0].left.id = 'herring' # Change reference to x to reference to herring
c = compile(e, '<string>', 'exec')
exec(c)
Ouput of change.py:
Cool Guy
24
You can also add code to the body this way (or replace elements in the usual way of replacing list elements):
p = ast.parse('print "Sweet!"', mode='single')
e.body.extend(p)
and then just recompile and exec:
c = compile(e, '<string>', 'exec')
exec(c)
You can replace function definitions or single lines that way. A function definition will have its own body, so if you added some function (or loop) you could access it with
e.body[N].body # Replace N with the index of the FunctionDef object
However, the only way that I know of to execute a single ast object (_ast.Print or _ast.Assign or whatever) is to do something like this:
e2 = ast.parse('', mode='exec')
e2.body.append(e.body[0])
exec(compile(e2, '<string>', 'exec'))
which seems a bit hackish to me. As far as lines go - each object in the AST has a lineno attribute, so if you can retrieve the line number from the exception you can fairly easily figure out which statement threw the exception.
Of course this doesn't really solve the problem of rewinding the stack to the pre-exception state, which is what you really want to do, it sounds like. However, it might be possible to do such a thing via pdb.
A:
I wonder if the HAP Remote Debugger for Python might be of any use to you? I don't think that they have live editing, but some of the debugging aspects might be useful nonetheless.
A:
From what I have figured out in the meantime, this is not possible. At least not block-wise. It is possible to recompile the code per function but not per code-block because Python generates the code objects per function.
So the only way is to write an own Python compiler.
| how to write a Python debugger/editor | Sorry for the kind of general question. More details about what I want:
I want the user to be able to write some Python code and execute it. Once there is an exception which is not handled, I want the debugger to pause the execution, show information about the current state/environment/stack/exception and make it possible to edit the code.
I only want to have the special code block editable where the exception occurred and nothing else (for now). I.e. if it occurred inside a for loop, I only want to have the code block inside the for loop editable. It should be the latest/most recent code block which is in the user editor scope (and not inside some other libs or the Python libs). Under this conditions, it is always clear what code block to edit.
I already tried to investigate a bit how to do this, though I feel a bit lost.
The Python traceback doesn't give me directly the code block, just the function and the code line. I could calculate that back but that seems a bit hacky to me. Better (and more natural) would be if I could somehow get a reference to the code block in the AST of the code.
To get the AST (and operate on it, i.e. manipulate/edit), I probably will use the compiler (which is deprecated?) and/or the parser module. Or the ast module. Not sure though how I could recompile special nodes / code blocks in the AST. Or if I only can recompile whole functions.
| [
"Playing around with ast and compile (built-in) it seems that you could possibly use the NodeTransformer to modify some nodes... You can also edit them manually if you know what you're looking for.\ntest.py\nprint 'Dumb Guy'\nx = 4 + 4\nprint x * 3\n\nchange.py\nimport ast\nwith open('test.py') as f:\n expr = f.... | [
2,
1,
1
] | [] | [] | [
"abstract_syntax_tree",
"compiler_construction",
"parsing",
"python",
"stack_trace"
] | stackoverflow_0003229102_abstract_syntax_tree_compiler_construction_parsing_python_stack_trace.txt |
Q:
How do you find the filename that you pass to open()?
I'm trying to open a file with Python, but I'm unsure how to find the correct filename to use.
A:
Access the name attribute.
fh = open('spam.txt')
print fh.name
A:
You can specify the path to the file in either a complete way (e.g. 'c:/wher/ever/the.txt'), also known as "absolute" because it's taken exactly as you specify it, or a partial one (e.g., just "the.txt", or "ever/the.txt", or "../ever/the.txt", and so on), also known as "relative" because it's taken relatively to the current working directory of your process. If you don't know that working directory, an absolute path is usually simplest to find and specify.
So, find out where the file lives (e.g. c:/wher/ever) and use that absolute path (with "rightside up slashes", instead of windows-style backslashes, as I just explained in another answer) to open the file in question.
| How do you find the filename that you pass to open()? | I'm trying to open a file with Python, but I'm unsure how to find the correct filename to use.
| [
"Access the name attribute.\nfh = open('spam.txt')\nprint fh.name\n\n",
"You can specify the path to the file in either a complete way (e.g. 'c:/wher/ever/the.txt'), also known as \"absolute\" because it's taken exactly as you specify it, or a partial one (e.g., just \"the.txt\", or \"ever/the.txt\", or \"../ever... | [
2,
2
] | [] | [] | [
"file",
"python"
] | stackoverflow_0003498587_file_python.txt |
Q:
Error when adding value to array
with open('file00.txt') as f00:
for line in f00:
farr=array.append(float(line))
print "farr= ",farr
i get:
farr=array.append(float(line))
AttributeError: 'module' object has no attribute 'append'
does anyone know why I get this? do I have to import something? am I doing it completely wrong?
thanks
A:
To append to an array, you must create the array (as an instance of the array.array type with the appropriate type code), giving it a name, and call append on that name - that is, on the instance, definitely not on the module.
So, for example:
>>> import array
>>> x = array.array('d') # array of double-precision floats
>>> x.append(1.23)
>>> x
array('d', [1.23])
>>>
and so on. Of course, you could also use a list instead of the array.array('d') (precious if you want to append values of different types, or of non-elementary types), but the principles are identical: you make an instance of list, then call append on the instance (through the name you gave it on creation), definitely not on any module!
A:
I am assuming that you want to do something like this instead:
values = []
with open('file00.txt') as f00:
for line in f00:
value = float(line)
values.append(value)
print "farr= ", value
That way the values list will contain all values.
| Error when adding value to array | with open('file00.txt') as f00:
for line in f00:
farr=array.append(float(line))
print "farr= ",farr
i get:
farr=array.append(float(line))
AttributeError: 'module' object has no attribute 'append'
does anyone know why I get this? do I have to import something? am I doing it completely wrong?
thanks
| [
"To append to an array, you must create the array (as an instance of the array.array type with the appropriate type code), giving it a name, and call append on that name - that is, on the instance, definitely not on the module.\nSo, for example:\n>>> import array\n>>> x = array.array('d') # array of double-precisi... | [
1,
0
] | [] | [] | [
"append",
"arrays",
"debugging",
"python"
] | stackoverflow_0003498479_append_arrays_debugging_python.txt |
Q:
I'm having trouble opening a Python file :(
I saved a file as DictionaryE.txt in a Modules folder I created within Python. Then I type:
fh = open("DictionaryE.txt")
I get this error message:
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
fh = open("DictionaryE.txt")
IOError: [Errno 2] No such file or directory: 'DictionaryE.txt'
What am I doing wrong? Could someone please describe a specific, detailed step-by-step instruction on what to do? Thanks.
A:
As other answers suggested, you need to specify the file's path, not just the name.
For example, if you know the file is in C:\Blah\Modules, use
fh = open('c:/Blah/Modules/DictionaryE.txt')
Note that I've turned the slashes "the right way up" (Unix-style;-) rather than "the Windows way". That's optional, but Python (and actually the underlying C runtime library) are perfectly happy with it, and it saves you trouble on many occasions (since \, in Python string literals just as in C ones, is an "escape marker", once in a while, if you use it, the string value you've actually entered is not the one you think -- with '/' instead, zero problems).
A:
Use the full path to the file? You are trying to open the file in the current working directory.
A:
probably something like:
import os
dict_file = open(os.path.join(os.path.dirname(__file__), 'Modules', 'DictionaryE.txt'))
It's hard to know without knowing your project structure and the context of your code. Fwiw, when you just "open" a file, it will be looking in whatever directory you're running the python program in, and __file__is the full path to ... the python file.
A:
To complement Alex's answer, you can be more specific and explicit with what you want to do with DictionaryE.txt. The basics:
READ (this is default):
fh = open("C:/path/to/DictionaryE.txt", "r")
WRITE:
fh = open("C:/path/to/DictionaryE.txt", "w")
APPEND:
fh = open("C:/path/to/DictionaryE.txt", "a")
More info can be found here: Built-in Functions - open()
| I'm having trouble opening a Python file :( | I saved a file as DictionaryE.txt in a Modules folder I created within Python. Then I type:
fh = open("DictionaryE.txt")
I get this error message:
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
fh = open("DictionaryE.txt")
IOError: [Errno 2] No such file or directory: 'DictionaryE.txt'
What am I doing wrong? Could someone please describe a specific, detailed step-by-step instruction on what to do? Thanks.
| [
"As other answers suggested, you need to specify the file's path, not just the name.\nFor example, if you know the file is in C:\\Blah\\Modules, use\nfh = open('c:/Blah/Modules/DictionaryE.txt')\n\nNote that I've turned the slashes \"the right way up\" (Unix-style;-) rather than \"the Windows way\". That's optiona... | [
3,
1,
0,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0003498688_file_python.txt |
Q:
Using numpy's flatten_dtype with structured dtypes that have titles
I usually don't post questions on these forums, but I've searched all over the place and I haven't found anything about this issue.
I am working with structured arrays to store experimental data. I'm using titles to store information about my fields, in this case the units of measure. When I call numpy.lib.io.flatten_dtype() on my dtype, I get:
ValueError: too many values to unpack
File "c:\Python25\Lib\site-packages\numpy\lib\_iotools.py", line 78, in flatten_dtype
(typ, _) = ndtype.fields[field]
I wouldn't really care, except that numpy.genfromtxt() calls numpy.lib.io.flatten_dtype(), and I need to be able to import my data from text files.
I'm wondering if I've done something wrong. Is flatten_dtype() not meant to support titles? Is there a work-around for genfromtxt()?
Here's a snippet of my code:
import numpy
fname = "C:\\Somefile.txt"
dtype = numpy.dtype([(("Amps","Current"),"f8"),(("Volts","Voltage"),"f8")])
myarray = numpy.genfromtxt(fname,dtype)
A:
Here is a possible workaround:
Since your custom dtype causes a problem, supply a flattened dtype instead:
In [77]: arr=np.genfromtxt('a',dtype='f8,f8')
In [78]: arr
Out[78]:
array([(1.0, 2.0), (3.0, 4.0)],
dtype=[('f0', '<f8'), ('f1', '<f8')])
Then use astype to convert to your desired dtype:
In [79]: arr=np.genfromtxt('a',dtype='f8,f8').astype(dtype)
In [80]: arr
Out[80]:
array([(1.0, 2.0), (3.0, 4.0)],
dtype=[(('Amps', 'Current'), '<f8'), (('Volts', 'Voltage'), '<f8')])
Edit: Another alternative is to monkey-patch numpy.lib.io.flatten_dtype:
import numpy
import numpy.lib.io
def flatten_dtype(ndtype):
"""
Unpack a structured data-type.
"""
names = ndtype.names
if names is None:
return [ndtype]
else:
types = []
for field in names:
typ_fields = ndtype.fields[field]
flat_dt = flatten_dtype(typ_fields[0])
types.extend(flat_dt)
return types
numpy.lib.io.flatten_dtype=flatten_dtype
| Using numpy's flatten_dtype with structured dtypes that have titles | I usually don't post questions on these forums, but I've searched all over the place and I haven't found anything about this issue.
I am working with structured arrays to store experimental data. I'm using titles to store information about my fields, in this case the units of measure. When I call numpy.lib.io.flatten_dtype() on my dtype, I get:
ValueError: too many values to unpack
File "c:\Python25\Lib\site-packages\numpy\lib\_iotools.py", line 78, in flatten_dtype
(typ, _) = ndtype.fields[field]
I wouldn't really care, except that numpy.genfromtxt() calls numpy.lib.io.flatten_dtype(), and I need to be able to import my data from text files.
I'm wondering if I've done something wrong. Is flatten_dtype() not meant to support titles? Is there a work-around for genfromtxt()?
Here's a snippet of my code:
import numpy
fname = "C:\\Somefile.txt"
dtype = numpy.dtype([(("Amps","Current"),"f8"),(("Volts","Voltage"),"f8")])
myarray = numpy.genfromtxt(fname,dtype)
| [
"Here is a possible workaround:\nSince your custom dtype causes a problem, supply a flattened dtype instead:\nIn [77]: arr=np.genfromtxt('a',dtype='f8,f8')\n\nIn [78]: arr\nOut[78]: \narray([(1.0, 2.0), (3.0, 4.0)], \n dtype=[('f0', '<f8'), ('f1', '<f8')])\n\nThen use astype to convert to your desired dtype:\n... | [
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0003498603_numpy_python.txt |
Q:
Software Validation Server in Python?
I have been working on a huge project for work for a while now, and it is almost done. However, in an effort to prevent the program was being pirated (I already know there is pretty much no method that can't be cracked ), the software needs to be able to validate. I'm not exactly sure how to do this. Could some sort of software validation server be written in Python? How would the software communicate with the server? Would the softwre check each time it is launched to see if it is valid? The program requires internet access to run anyway, so checking for validation at each launch might not be so bad.
I am programming in Python 2.6 on Windows 7. Any help would be great!
A:
The software, when starting, should launch an https (so it can't just be sniffed easily;-) request to your server, identifying itself (however it is that you choose to identify, e.g. a serial number or whatever), and the server's response will tell it what to do (run normally, or terminate, or ask the user to register -- whatever).
Of course, any competent hacker will find and disable the part of your code where you're sending the request and dispatching on the answer, but then you already do know that everything can easily be cracked;-).
A less-easily crackable approach would be to keep some crucial part of the functionality on your server, so that the client's basically useless (or at least less useful) if it hasn't checked in with your server and obtained a token to be used in other "functionality requests" during a session.
Hard to tell, without knowing a lot more about your app, if there are bits and pieces of functionality in your app that lend themselves well to this treatment, but for example you could delegate in this way any kind of cryptographic functionality (encrypting, decrypting, signing, ...) -- if only your server knows the secret/private keys to be used for such purposes, and only performs the functionality for application sessions that have properly registered and been authorized, suddenly it's become very hard for even a good hacker to work around your registration and authorization system.
A:
I would really urge you not to do this. As you said, whatever you do will be broken, and you may actually cause more copies of your software to be pirated by including this barrier. Asking your users nicely not to steal may do better...
That said, implementing this in a way that discourages the most casual piracy is easy: just have the program send a serial number encrypted with the server's public key to your validation script, and have the server return a version of the number encrypted using its private key. Instant validation. Yes, this server could be written in Python easily.
| Software Validation Server in Python? | I have been working on a huge project for work for a while now, and it is almost done. However, in an effort to prevent the program was being pirated (I already know there is pretty much no method that can't be cracked ), the software needs to be able to validate. I'm not exactly sure how to do this. Could some sort of software validation server be written in Python? How would the software communicate with the server? Would the softwre check each time it is launched to see if it is valid? The program requires internet access to run anyway, so checking for validation at each launch might not be so bad.
I am programming in Python 2.6 on Windows 7. Any help would be great!
| [
"The software, when starting, should launch an https (so it can't just be sniffed easily;-) request to your server, identifying itself (however it is that you choose to identify, e.g. a serial number or whatever), and the server's response will tell it what to do (run normally, or terminate, or ask the user to regi... | [
2,
0
] | [] | [] | [
"python",
"validation",
"windows"
] | stackoverflow_0003498904_python_validation_windows.txt |
Q:
python package get imported automatically when importing a global from a module
Let's say I have these files:
- package1/
- __init__.py
- package2/
- __init__.py
- module1.py
Content of package1/__init__.py:
from package2.module1 import var1
print package2
Empty package1/package2/__init__.py
Content of package1/package2/module1.py:
var1 = 123
The question is why would package2 get imported? Running pylint against package1/__init__.py will actually give error Undefined variable 'package2', but the code works.
A:
When you import a module from within a package the package is always imported (loaded, if it's not already in sys.modules) first -- which may have the side effect of binding the package's name in the importing module, though that's not guaranteed (depends on the Python implementation and version).
And, importing something "from inside a module" (a practice I personally abhor, but that's another issue) must also ensure the module is loaded (if it's already in sys.modules it doesn't of course need to be loaded again, but if it isn't, it must get loaded and put in sys.modules).
Both of these behaviors (the guaranteed parts;-) are all about the "integrity" of packages and modules: when you write a module you can be sure that, even if somebody misguidedly tries to pick and choose which bits to import, they'll be affecting only the name bindings in their own module, but your module will always get loaded as a whole. And similarly for somebody importing a module from within your package (a perfectly OK practice, BTW): you know your package's __init__.py will get loaded first, before anything happens. This gives you the chance to do all needed checks and initializations, of course!
| python package get imported automatically when importing a global from a module | Let's say I have these files:
- package1/
- __init__.py
- package2/
- __init__.py
- module1.py
Content of package1/__init__.py:
from package2.module1 import var1
print package2
Empty package1/package2/__init__.py
Content of package1/package2/module1.py:
var1 = 123
The question is why would package2 get imported? Running pylint against package1/__init__.py will actually give error Undefined variable 'package2', but the code works.
| [
"When you import a module from within a package the package is always imported (loaded, if it's not already in sys.modules) first -- which may have the side effect of binding the package's name in the importing module, though that's not guaranteed (depends on the Python implementation and version).\nAnd, importing ... | [
1
] | [] | [] | [
"import",
"python"
] | stackoverflow_0003498929_import_python.txt |
Q:
What is the working of web Crawler?
Will web crawler crawl the web and create a database of the web or it will just create a searchable index of web? If suppose it creates an index, who will exactly will gather the data of web pages and store it in database?
A:
Though the question is slightly vague Let me puts some words to clarify.
Crawler makes http request of a URL and analyse the information of that web page. Say for example it makes a http req. http://www.example.com it retrieves the content of the page.
Once it gets the content of the page it analyse it. Now comes the importance of H1, H2 , P tages base on these tags it gets a clue of what the web page is all about.
Identifies the important/prominent words called keywords and summarise the page content and puts it in its index
Also it gets hyperlinks to other websites from that page that will be used in its next jump to those website and it proceeds further. It is a never ending story.
So whenever a keyword is being asked it looks from the keyword database and it shows in the result.
Sometimes the crawler itself dumps the copy of the web pages in a special database called cache database so that it can be used as alternate copy of the original data.
| What is the working of web Crawler? | Will web crawler crawl the web and create a database of the web or it will just create a searchable index of web? If suppose it creates an index, who will exactly will gather the data of web pages and store it in database?
| [
"Though the question is slightly vague Let me puts some words to clarify.\n\nCrawler makes http request of a URL and analyse the information of that web page. Say for example it makes a http req. http://www.example.com it retrieves the content of the page.\nOnce it gets the content of the page it analyse it. Now co... | [
2
] | [] | [] | [
"php",
"python"
] | stackoverflow_0003498962_php_python.txt |
Q:
Google app engine images API - get image size
How can I get the size of an image transformed with the app engine images API?
Note: I mean the size in bytes, not the dimensions.
A:
execute_transforms returns a str (bytestring), so you can just call len(image_str).
| Google app engine images API - get image size | How can I get the size of an image transformed with the app engine images API?
Note: I mean the size in bytes, not the dimensions.
| [
"execute_transforms returns a str (bytestring), so you can just call len(image_str).\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"image",
"python",
"upload"
] | stackoverflow_0003499060_google_app_engine_image_python_upload.txt |
Q:
How should I structure a video streaming web app?
I want a user to be able to create an account and upload a video to the site.
How should I structure this web app, how should I start thinking about the project, how should I store the videos, and what stack would you recommend for this project? How should I think about the front-end, the server, and the database?
The more detail, the better! Also, any code that people might give me or point me to would be greatly appreciated. I'm looking for code for the following:
user accounts
uploading videos
storing videos
categorizing the videos upon upload
displaying videos in thumbnail form
I'm probably not thinking of some things, so anything I'm forgetting, please let me know! And remember, the more detail the better!
A:
I'd start by breaking it down into more manageable chunks.
A python web framework to work in:
Django
Pylons
Google App Engine (webapp)
Video storage solution:
Amazon S3
Amazon CloudFront (for proper H.264 streaming instead of progressive download)
Google Storage
CacheFly
Etc.
Video metadata and thumbnail retrieval:
FFmpeg
Data storage solution:
PostgreSQL
MySQL
MongoDB (if using Pylons)
You've asked for code samples of things like user accounts, but the frameworks listed provide helpful tutorials (Django, Pylons, App Engine) for the basics. If you are unable to adapt the concepts in their tutorials from their respective examples to a system for managing user accounts, I would suggest reading up on database design and architecture a bit first.
As for how you should think about the front-end, database, etc., that again tends to rely on the web framework you choose to go with. They all have their own conventions that you'll benefit from by adhering to.
My general suggestion would be for you to pick a web framework, then go through its various tutorials and user guides. You'll learn a lot about how the framework structures its files, how it prefers (or forces) its databases to be structured, etc. In doing so, you'll learn about a lot of the things you've asked for examples of — video categorization, relating images to videos, and so forth.
Because there are so many different options for you to go with, it is extremely hard to just provide a few samples of code that do some of the things you've asked for. The code would have to come with a list of pre-requisites, and would only lessen your ability to evaluate the various choices and pick the one that you feel will work best for you.
| How should I structure a video streaming web app? | I want a user to be able to create an account and upload a video to the site.
How should I structure this web app, how should I start thinking about the project, how should I store the videos, and what stack would you recommend for this project? How should I think about the front-end, the server, and the database?
The more detail, the better! Also, any code that people might give me or point me to would be greatly appreciated. I'm looking for code for the following:
user accounts
uploading videos
storing videos
categorizing the videos upon upload
displaying videos in thumbnail form
I'm probably not thinking of some things, so anything I'm forgetting, please let me know! And remember, the more detail the better!
| [
"I'd start by breaking it down into more manageable chunks.\n\nA python web framework to work in:\n\n\nDjango\nPylons\nGoogle App Engine (webapp)\n\nVideo storage solution:\n\n\nAmazon S3\nAmazon CloudFront (for proper H.264 streaming instead of progressive download)\nGoogle Storage\nCacheFly\nEtc.\n\nVideo metadat... | [
16
] | [] | [] | [
"python",
"video",
"video_streaming",
"web_applications"
] | stackoverflow_0003499227_python_video_video_streaming_web_applications.txt |
Q:
Referencing list entries within a for loop without indexes, possible?
A question of particular interest about python for loops. Engineering programs often require values at previous or future indexes, such as:
for i in range(0,n):
value = 0.3*list[i-1] + 0.5*list[i] + 0.2*list[i+1]
etc...
However I rather like the nice clean python syntax:
for item in list:
#Do stuff with item in list
or for a list of 2d point data:
for [x,y] in list:
#Process x, y data
I like the concept of looping over a list without explicitly using an index to reference the items in the list. I was wondering if there was a clean way to grab the previous or next item without looping over the index (or without keeping track of the index independently)?
EDIT:
Thanks Andrew Jaffe (and by proxy Mark Byers) and gnibbler for the simple, extendable examples. I wasn't aware of the itertools or nwise modules till now. John Machin - thanks for the very complex example of what NOT to do. You put a lot of effort into this example, obviously the somewhat recursive algorithm I presented cannot produce a list with the same number of elements as the input list and it presents problems if not using explicit indexes. An algorithm like this would commonly occur in signal processing.
A:
Here's a recipe, based on the itertools pairwise code, which does general n-wise grouping:
import itertools
def nwise(iterable, n=2):
"s->(s_0,s_1, ..., s_n), (s_1,s_2,..., s_n+1), ... "
ntup = itertools.tee(iterable, n)
for i, item in enumerate(ntup):
for ii in range(i):
next(item, None)
return itertools.izip(*ntup)
Which can be used thusly:
>>> import nwise
>>> ll = range(10)
>>> for tup in nwise.nwise(ll,3): print tup
...
(0, 1, 2)
(1, 2, 3)
(2, 3, 4)
(3, 4, 5)
(4, 5, 6)
(5, 6, 7)
(6, 7, 8)
(7, 8, 9)
[Thanks to Mark Byers' answer for the idea]
A:
To have access to an element and the next one you can use the pairwise recipe that is shown in the itertools documentation:
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return izip(a, b)
This could be adapted to allow access to three neighbouring elements instead of just two.
A:
>>> from itertools import islice, izip
>>> seq = range(10)
>>> for x,y,z in izip(*(islice(seq,i,None) for i in range(3))):
... print x,y,z
...
0 1 2
1 2 3
2 3 4
3 4 5
4 5 6
5 6 7
6 7 8
7 8 9
this can be trivially extended beyond 3 items.
If you need it to work with any iterable, Andrew's answer is suitable, or you can do it like this
>>> from itertools import izip, islice, tee
>>> seq=(x for x in range(10))
>>> for x,y,z in izip(*(islice(j,i,None) for i,j in enumerate(tee(seq,3)))):
... print x,y,z
...
0 1 2
1 2 3
2 3 4
3 4 5
4 5 6
5 6 7
6 7 8
7 8 9
A:
If you want to use zip, here's how NOT to do it (stuffed, needlessly) and how not to check it (stuffed x 2.5), with those deficiencies corrected.
vector = [2**i for i in range(1,6)]
print "vector", vector
value = []
for i in range(1,len(vector)-1):
value.append(0.3*vector[i-1] + 0.5*vector[i] + 0.2*vector[i+1])
print "value", len(value), value
value2=[0.3*before + 0.5* this + 0.2 * after
for before,this,after in zip(vector,vector[1:]+[0], vector[2:]+[0,0])
]
# above +[0] and +[0,0] needlessly extend the answer by two items
print "value2", len(value2), value2
print "bad check bad values", not any([x-y for x,y in zip(value,value2) if x-y > 1e-7])
# the bad check doesn't check for length
# the bad check doesn't use abs(actual - expected)
# the bad check has a unnecessary if test in it
# the bad check uses a list comprehension when a generator would do
print "good check bad values", (
len(value2) == len(value)
and
not any(abs(x-y) > 1e-7 for x,y in zip(value,value2))
)
value2=[0.3*before + 0.5* this + 0.2 * after
for before,this,after in zip(vector,vector[1:], vector[2:])
]
print "fixed value2", len(value2), value2
print "good check good values", (
len(value2) == len(value)
and
not any(abs(x-y) > 1e-7 for x,y in zip(value,value2))
)
| Referencing list entries within a for loop without indexes, possible? | A question of particular interest about python for loops. Engineering programs often require values at previous or future indexes, such as:
for i in range(0,n):
value = 0.3*list[i-1] + 0.5*list[i] + 0.2*list[i+1]
etc...
However I rather like the nice clean python syntax:
for item in list:
#Do stuff with item in list
or for a list of 2d point data:
for [x,y] in list:
#Process x, y data
I like the concept of looping over a list without explicitly using an index to reference the items in the list. I was wondering if there was a clean way to grab the previous or next item without looping over the index (or without keeping track of the index independently)?
EDIT:
Thanks Andrew Jaffe (and by proxy Mark Byers) and gnibbler for the simple, extendable examples. I wasn't aware of the itertools or nwise modules till now. John Machin - thanks for the very complex example of what NOT to do. You put a lot of effort into this example, obviously the somewhat recursive algorithm I presented cannot produce a list with the same number of elements as the input list and it presents problems if not using explicit indexes. An algorithm like this would commonly occur in signal processing.
| [
"Here's a recipe, based on the itertools pairwise code, which does general n-wise grouping:\nimport itertools\n\ndef nwise(iterable, n=2):\n \"s->(s_0,s_1, ..., s_n), (s_1,s_2,..., s_n+1), ... \"\n ntup = itertools.tee(iterable, n)\n for i, item in enumerate(ntup):\n for ii in range(i):\n ... | [
4,
2,
1,
0
] | [] | [] | [
"indexing",
"loops",
"python"
] | stackoverflow_0003499130_indexing_loops_python.txt |
Q:
Convert Hexadecimal MAC address to user readable formatting (Python)
I'm receiving from the socket a MAC address in this format:
0024e865a023 (hex converted from binary with received-string.encode("hex"))
I would like to convert it to a user readable format like this :
00-24-e8-65-a0-23
Any easy way to do so?
A:
You can break apart the MAC address into an array of each block, and then join them on -:
mac = '0024e865a023'
blocks = [mac[x:x+2] for x in xrange(0, len(mac), 2)]
macFormatted = '-'.join(blocks)
| Convert Hexadecimal MAC address to user readable formatting (Python) | I'm receiving from the socket a MAC address in this format:
0024e865a023 (hex converted from binary with received-string.encode("hex"))
I would like to convert it to a user readable format like this :
00-24-e8-65-a0-23
Any easy way to do so?
| [
"You can break apart the MAC address into an array of each block, and then join them on -:\nmac = '0024e865a023'\nblocks = [mac[x:x+2] for x in xrange(0, len(mac), 2)]\nmacFormatted = '-'.join(blocks)\n\n"
] | [
6
] | [] | [] | [
"bin",
"hex",
"macos",
"python"
] | stackoverflow_0003499510_bin_hex_macos_python.txt |
Q:
Erase whole array Python
How do I erase a whole array, leaving it with no items?
I want to do this so I can store new values in it (a new set of 100 floats) and find the minimum.
Right now my program is reading the minimum from sets before I think because it is appending itself with the previous set still in there. I use .append by the way.
A:
Note that list and array are different classes. You can do:
del mylist[:]
This will actually modify your existing list. David's answer creates a new list and assigns it to the same variable. Which you want depends on the situation (e.g. does any other variable have a reference to the same list?).
Try:
a = [1,2]
b = a
a = []
and
a = [1,2]
b = a
del a[:]
Print a and b each time to see the difference.
A:
It's simple:
array = []
will set array to be an empty list. (They're called lists in Python, by the way, not arrays)
If that doesn't work for you, edit your question to include a code sample that demonstrates your problem.
A:
Well yes arrays do exist, and no they're not different to lists when it comes to things like del and append:
>>> from array import array
>>> foo = array('i', range(5))
>>> foo
array('i', [0, 1, 2, 3, 4])
>>> del foo[:]
>>> foo
array('i')
>>> foo.append(42)
>>> foo
array('i', [42])
>>>
Differences worth noting: you need to specify the type when creating the array, and you save storage at the expense of extra time converting between the C type and the Python type when you do arr[i] = expression or arr.append(expression), and lvalue = arr[i]
A:
Now to answer the question that perhaps you should have asked, like "I'm getting 100 floats form somewhere; do I need to put them in an array or list before I find the minimum?"
Answer: No, if somewhere is a iterable, instead of doing this:
temp = []
for x in somewhere:
temp.append(x)
answer = min(temp)
you can do this:
answer = min(somewhere)
Example:
answer = min(float(line) for line in open('floats.txt'))
| Erase whole array Python | How do I erase a whole array, leaving it with no items?
I want to do this so I can store new values in it (a new set of 100 floats) and find the minimum.
Right now my program is reading the minimum from sets before I think because it is appending itself with the previous set still in there. I use .append by the way.
| [
"Note that list and array are different classes. You can do:\ndel mylist[:]\n\nThis will actually modify your existing list. David's answer creates a new list and assigns it to the same variable. Which you want depends on the situation (e.g. does any other variable have a reference to the same list?).\nTry:\na =... | [
57,
35,
9,
1
] | [] | [] | [
"arrays",
"erase",
"python"
] | stackoverflow_0003499233_arrays_erase_python.txt |
Q:
find value of forloop at which event occurred Python
hey guys, this is very confusing...
i am trying to find the minimum of an array by:
for xpre in range(100): #used pre because I am using vapor pressures with some x molarity
xvalue=xarray[xpre]
for ppre in range(100): #same as xpre but vapor pressures for pure water, p
pvalue=parray[p]
d=math.fabs(xvalue-pvalue) #d represents the difference(due to vapor pressure lowering, a phenomenon in chemistry)
darray.append(d) #darray stores the differences
mini=min(darray) #mini is the minimum value in darray
darr=[] #this is to make way for a new set of floats
all the arrays (xarr,parr,darr)are already defined and what not. they have 100 floats each
so my question is how would I find the pvap and the xvap @ which min(darr) is found?
edit
have changed some variable names and added variable descriptions, sorry guys
A:
A couple things:
Try enumerate
Instead of darr being a list, use a dict and store the dvp values as keys, with the xindex and pindex variables as values
Here's the code
for xindex, xvalue in enumerate(xarr):
darr = {}
for pindex, pvalue in enumerate(parr):
dvp = math.fabs(xvalue - pvalue)
darr[dvp] = {'xindex': xindex, 'pindex': pindex}
mini = min(darr.keys())
minix = darr[mini]['xindex']
minip = darr[mini]['pindex']
minindex = darr.keys().index(mini)
print "minimum_index> {0}, is the difference of xarr[{1}] and parr[{2}]".format(minindex, minix, minip)
darr.clear()
Explanation
The enumerate function allows you to iterate over a list and also receive the index of the item. It is an alternative to your range(100). Notice that I don't have the line where I get the value at index xpre, ppre, this is because the enumerate function gives me both index and value as a tuple.
The most important change, however, is that instead of your darr being a list like this:
[130, 18, 42, 37 ...]
It is now a dictionary like this:
{
130: {'xindex': 1, 'pindex': 4},
18: {'xindex': 1, 'pindex': 6},
43: {'xindex': 1, 'pindex': 9},
...
}
So now, instead of just storing the dvp values alone, I am also storing the indices into x and p which generated those dvp values. Now, if I want to know something, say, Which x and p values produce the dvp value of 43? I would do this:
xindex = darr[43]['xindex']
pindex = darr[43]['pindex']
x = xarr[xindex]
p = parr[pindex]
Now x and p are the values in question.
Note I personally would store the values which produced a particular dvp, and not the indices of those values. But you asked for the indices so I gave you that answer. I'm going to assume that you have a reason for wanting to handle indices like this, but in Python generally you do not find yourself handling indices in this way when you are programming in Pythonic manner. This is a very C way of doing things.
A:
Edit: This doesn't answer the OP's question:
min_diff, min_idx = min((math.fabs(a - b), i) for i, (a, b) in enumerate(zip(xpre, ppre)
right to left:
zip takes xpre and ppre and makes a tuple of the 1st, 2nd, ... elements respectively, like so:
[ (xpre[0],ppre[0]) , (xpre[1],ppre[1]) , ... ]
enumerate enumerates adds the index by just counting upwards from 0:
[ (0 , (xpre[0],ppre[0]) ) , (1 , (xpre[1],ppre[1]) ) , ... ]
This unpacks each nestet tuple:
for i, (a, b) in ...
i is the index generated by enumerate, a and b are the elements of xarr and parr.
This builds a tuple consisting of a difference and the index:
(math.fabs(a - b), i)
The whole thing inbetween the min(...) is a generator expression. min then finds the minimal value in these values, and the assignment unpacks them:
min_diff, min_idx = min(...)
| find value of forloop at which event occurred Python | hey guys, this is very confusing...
i am trying to find the minimum of an array by:
for xpre in range(100): #used pre because I am using vapor pressures with some x molarity
xvalue=xarray[xpre]
for ppre in range(100): #same as xpre but vapor pressures for pure water, p
pvalue=parray[p]
d=math.fabs(xvalue-pvalue) #d represents the difference(due to vapor pressure lowering, a phenomenon in chemistry)
darray.append(d) #darray stores the differences
mini=min(darray) #mini is the minimum value in darray
darr=[] #this is to make way for a new set of floats
all the arrays (xarr,parr,darr)are already defined and what not. they have 100 floats each
so my question is how would I find the pvap and the xvap @ which min(darr) is found?
edit
have changed some variable names and added variable descriptions, sorry guys
| [
"A couple things: \n\nTry enumerate\nInstead of darr being a list, use a dict and store the dvp values as keys, with the xindex and pindex variables as values\n\nHere's the code\nfor xindex, xvalue in enumerate(xarr):\n darr = {}\n for pindex, pvalue in enumerate(parr):\n dvp = math.fabs(xvalue - pvalue)\n ... | [
2,
0
] | [] | [] | [
"arrays",
"for_loop",
"minimum",
"python"
] | stackoverflow_0003499620_arrays_for_loop_minimum_python.txt |
Q:
Efficient way of phrasing multiple tuple pair WHERE conditions in SQL statement
I want to perform an SQL query that is logically equivalent to the following:
DELETE FROM pond_pairs
WHERE
((pond1 = 12) AND (pond2 = 233)) OR
((pond1 = 12) AND (pond2 = 234)) OR
((pond1 = 12) AND (pond2 = 8)) OR
((pond1 = 13) AND (pond2 = 6547)) OR
((pond1 = 13879) AND (pond2 = 6))
I will have hundreds of thousands pond1-pond2 pairs. I have an index on (pond1, pond2).
My limited SQL knowledge came up with several approaches:
Run the whole query as is.
Batch the query up into smaller queries with n WHERE conditions
Save the pond1-pond2 pairs into a new table, and do a subquery in the WHERE clause to identify
Convert the python logic which identifies rows to delete into a stored procedure. Note that I am unfamiliar with programming stored procedures and thus this would probably involve a steep learning curve.
I am using postgres if that is relevant.
A:
I will do 3. (with JOIN rather than subquery) and measure time of DELETE query (without creating table and inserting). This is good starting point, because JOINing is very common and optimized procedure, so It will be hard to beat that time. Then you can compare that time to your current approach.
Also you can try following approach:
Sort pairs in same way as in index.
Delete using method 2. from your description (probably in single transaction).
Sorting before delete will give better index reading performance, because there's greater chance for hard-drive cache to work.
A:
For a large number of pond1-pond2 pairs to be deleted in a single DELETE, I would create temporary table and join on this table.
-- Create the temp table:
CREATE TEMP TABLE foo AS SELECT * FROM (VALUES(1,2), (1,3)) AS sub (pond1, pond2);
-- Delete
DELETE FROM bar
USING
foo -- the joined table
WHERE
bar.pond1= foo.pond1
AND
bar.pond2 = foo.pond2;
A:
With hundred of thousands of pairs, you cannot do 1 (run the query as is), because the SQL statement would be too long.
3 is good if you have the pairs already in a table. If not, you would need to insert them first. If you do not need them later, you might just as well run the same amount of DELETE statements instead of INSERT statements.
How about a prepared statement in a loop, maybe batched (if Python supports that)
begin transaction
prepare statement "DELETE FROM pond_pairs WHERE ((pond1 = ?) AND (pond2 = ?))"
loop over your data (in Python), and run the statement with one pair (or add to batch)
commit
Where are the pairs coming from? If you can write a SELECT statements to identify them, you can just move this condition into the WHERE clause of your delete.
DELETE FROM pond_pairs WHERE (pond1, ponds) in (SELECT pond1, pond2 FROM ...... )
| Efficient way of phrasing multiple tuple pair WHERE conditions in SQL statement | I want to perform an SQL query that is logically equivalent to the following:
DELETE FROM pond_pairs
WHERE
((pond1 = 12) AND (pond2 = 233)) OR
((pond1 = 12) AND (pond2 = 234)) OR
((pond1 = 12) AND (pond2 = 8)) OR
((pond1 = 13) AND (pond2 = 6547)) OR
((pond1 = 13879) AND (pond2 = 6))
I will have hundreds of thousands pond1-pond2 pairs. I have an index on (pond1, pond2).
My limited SQL knowledge came up with several approaches:
Run the whole query as is.
Batch the query up into smaller queries with n WHERE conditions
Save the pond1-pond2 pairs into a new table, and do a subquery in the WHERE clause to identify
Convert the python logic which identifies rows to delete into a stored procedure. Note that I am unfamiliar with programming stored procedures and thus this would probably involve a steep learning curve.
I am using postgres if that is relevant.
| [
"I will do 3. (with JOIN rather than subquery) and measure time of DELETE query (without creating table and inserting). This is good starting point, because JOINing is very common and optimized procedure, so It will be hard to beat that time. Then you can compare that time to your current approach.\nAlso you can tr... | [
1,
1,
0
] | [] | [] | [
"optimization",
"postgresql",
"python",
"sql"
] | stackoverflow_0003499613_optimization_postgresql_python_sql.txt |
Q:
Python - Writing to a text file using functions?
i wrote a simple function to write into a text file. like this,
def write_func(var):
var = str(var)
myfile.write(var)
a= 5
b= 5
c= a + b
write_func(c)
this will write the output to a desired file.
now, i want the output in another format. say,
write_func("Output is :"+c)
so that the output will have a meaningful name in the file. how do i do it?
and why is that i cant write an integer to a file? i do, int = str(int) before writing to a file?
A:
You can't add/concatenate a string and integer directly.
If you do anything more complicated than "string :"+str(number), I would strongly recommend using string formatting:
write_func('Output is: %i' % (c))
A:
Simple, you do:
write_func('Output is' + str(c))
You have to convert c to a string before you can concatenate it with another string. Then you can also take off the:
var = str(var)
From your function.
why is that i cant write an integer to
a file? i do, int = str(int) before
writing to a file?
You can write binary data to a file, but byte representations of numbers aren't really human readable. -2 for example is 0xfffffffe in a 2's complement 32-bit integer. It's even worse when the number is a float: 2.1 is 0x40066666.
If you plan on having a human-readable file, you need to human-readable characters on them. In an ASCII file '0.5' isn't a number (at least not as a computer understands numbers), but instead the characters '0', '.' and '5'. And that's why you need convert your numbers to strings.
A:
Python is a strongly typed language. This means, among other things, that you cannot concatenate a string and an integer. Therefore you'll have to convert the integer to string before concatenating. This can be done using a format string (as Nick T suggested) or passing the integer to the built in str function (as NullUserException suggested).
A:
From http://docs.python.org/library/stdtypes.html#file.write
file.write(str)
Write a string to the file. There is no return value. Due to buffering,
the string may not actually show up in
the file until the flush() or close()
method is called.
Note how documentation specifies that write's argument must be a string.
So you should create a string yourself before passing it to file.write().
| Python - Writing to a text file using functions? | i wrote a simple function to write into a text file. like this,
def write_func(var):
var = str(var)
myfile.write(var)
a= 5
b= 5
c= a + b
write_func(c)
this will write the output to a desired file.
now, i want the output in another format. say,
write_func("Output is :"+c)
so that the output will have a meaningful name in the file. how do i do it?
and why is that i cant write an integer to a file? i do, int = str(int) before writing to a file?
| [
"You can't add/concatenate a string and integer directly.\nIf you do anything more complicated than \"string :\"+str(number), I would strongly recommend using string formatting:\nwrite_func('Output is: %i' % (c))\n\n",
"Simple, you do:\nwrite_func('Output is' + str(c))\n\nYou have to convert c to a string before ... | [
3,
2,
2,
1
] | [] | [] | [
"file_io",
"function",
"python"
] | stackoverflow_0003499961_file_io_function_python.txt |
Q:
Can you use Python v. 2.7 with Django?
The Django book says: "The core Django framework works with any Python version from 2.3 to 2.6, inclusive. Django’s optional GIS (Geographic Information Systems) support requires Python 2.4 to 2.6."
A:
From Django's FAQ:
Currently, Django itself officially supports any version of Python from 2.4 through 2.7, inclusive.
The Django Book (2nd edition) is written for Django version 1.0, while the latest release of Django is version 1.2.1, hence the difference.
| Can you use Python v. 2.7 with Django? | The Django book says: "The core Django framework works with any Python version from 2.3 to 2.6, inclusive. Django’s optional GIS (Geographic Information Systems) support requires Python 2.4 to 2.6."
| [
"From Django's FAQ:\n\nCurrently, Django itself officially supports any version of Python from 2.4 through 2.7, inclusive. \n\nThe Django Book (2nd edition) is written for Django version 1.0, while the latest release of Django is version 1.2.1, hence the difference.\n"
] | [
6
] | [] | [] | [
"compatibility",
"django",
"python"
] | stackoverflow_0003500160_compatibility_django_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.