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:
HTTP GET script based on httplib
I need a tool, which can download some part of data from web server, and after that i want connection not be closed. Therfore, i thought about a script in python, which can do:
1) send request
2) read some part of response
3) will freeze - server should think that connection exist, and should not close it
is it possilbe to do it in python ? here is my code:
conn = HTTPConnection("myhost", 10000)
conn.request("GET", "/?file=myfile")
r1 = conn.getresponse()
print r1.status, r1.reason
data = r1.read(2000000)
print len(data)
When im running it, all data is received, and after that server closes connection.
thx in advance for any help
A:
httplib doesn't support that. Use another library, like httplib2. Here's example.
| HTTP GET script based on httplib | I need a tool, which can download some part of data from web server, and after that i want connection not be closed. Therfore, i thought about a script in python, which can do:
1) send request
2) read some part of response
3) will freeze - server should think that connection exist, and should not close it
is it possilbe to do it in python ? here is my code:
conn = HTTPConnection("myhost", 10000)
conn.request("GET", "/?file=myfile")
r1 = conn.getresponse()
print r1.status, r1.reason
data = r1.read(2000000)
print len(data)
When im running it, all data is received, and after that server closes connection.
thx in advance for any help
| [
"httplib doesn't support that. Use another library, like httplib2. Here's example.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003636703_python.txt |
Q:
Projects using py.test
I am looking for (list of) projects that use py.test.
I am new to testing, and want to use py.test. I need examples from projects, so i can use py.test extensively. The documentation is good for py.test but is too fragmented to get a good grasp. I have a vague idea of how it works. I saw the py.test video(3hrs) from pycon. But need some working examples in projects.
A:
There is MoinMoin, Pida, PyPy and a host of other projects using py.test. In terms of examples you might also look into py.test's own test suite which naturally uses a lot of its features. Checkout http://bitbucket.org/hpk42/py-trunk and the "testing" sub directory and maybe file an issue on the tracker that you want to see more documented examples on the web page :)
update: these days there are some companies and projects listed which use py.test, see
http://pytest.org/latest/projects.html#projects
| Projects using py.test | I am looking for (list of) projects that use py.test.
I am new to testing, and want to use py.test. I need examples from projects, so i can use py.test extensively. The documentation is good for py.test but is too fragmented to get a good grasp. I have a vague idea of how it works. I saw the py.test video(3hrs) from pycon. But need some working examples in projects.
| [
"There is MoinMoin, Pida, PyPy and a host of other projects using py.test. In terms of examples you might also look into py.test's own test suite which naturally uses a lot of its features. Checkout http://bitbucket.org/hpk42/py-trunk and the \"testing\" sub directory and maybe file an issue on the tracker that y... | [
3
] | [] | [] | [
"pytest",
"python",
"testing"
] | stackoverflow_0003486194_pytest_python_testing.txt |
Q:
Executing modules as scripts
I am learn python now, and today, i met a problem
in
http://docs.python.org/release/2.5.4/tut/node8.html
6.1.1 Executing modules as scripts
When you run a Python module with
python fibo.py <arguments>
the code in the module will be executed, just as if you imported it, but with the
__name__ set to "__main__". That means that by adding this code at the end of
your module:
if __name__ == "__main__":
import sys`
fib(int(sys.argv[1]))
you can make the file usable as a script as well as
an importable module, because the code
that parses the command line only runs
if the module is executed as the
"main" file:
$ python fibo.py 50 1 1 2 3 5 8 13 21
34
but when i do this in shell, i got
File "<input>", line 1
python fibo.py 222
SyntaxError: invalid syntax
how to execute script correctly?
fibo.py is
def fib(n):
a,b=0,1
while b<n:
print b,
a,b = b,a+b
def fib2(n):
result=[]
a,b=0,1
while b<n:
result.append(b)
a,b=b,a+b
return result
if __name__ =="__main__":
import sys
fib(int(sys.argv[1]))
A:
What exactly did you do in the shell? What is the code you are running?
It sounds like you made a mistake in your script - perhaps missing the colon or getting the indentation wrong. Without seeing the file you are running it is impossible to say more.
edit:
I have figured out what is going wrong. You are trying to run python fibo.py 222 in the python shell. I get the same error when I do that:
[138] % python
Python 2.6.1 (r261:67515, Apr 9 2009, 17:53:24)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> python fibo.py 222
File "<stdin>", line 1
python fibo.py 222
^
SyntaxError: invalid syntax
>>>
You need to run it from the operating system's command line prompt NOT from within Python's interactive shell.
Make sure to change to Python home directory first. For example, from the Operating system's command line, type: cd C:\Python33\ -- depending on your python version. Mine is 3.3. And then type: python fibo.py 200 (for example)
| Executing modules as scripts | I am learn python now, and today, i met a problem
in
http://docs.python.org/release/2.5.4/tut/node8.html
6.1.1 Executing modules as scripts
When you run a Python module with
python fibo.py <arguments>
the code in the module will be executed, just as if you imported it, but with the
__name__ set to "__main__". That means that by adding this code at the end of
your module:
if __name__ == "__main__":
import sys`
fib(int(sys.argv[1]))
you can make the file usable as a script as well as
an importable module, because the code
that parses the command line only runs
if the module is executed as the
"main" file:
$ python fibo.py 50 1 1 2 3 5 8 13 21
34
but when i do this in shell, i got
File "<input>", line 1
python fibo.py 222
SyntaxError: invalid syntax
how to execute script correctly?
fibo.py is
def fib(n):
a,b=0,1
while b<n:
print b,
a,b = b,a+b
def fib2(n):
result=[]
a,b=0,1
while b<n:
result.append(b)
a,b=b,a+b
return result
if __name__ =="__main__":
import sys
fib(int(sys.argv[1]))
| [
"What exactly did you do in the shell? What is the code you are running?\nIt sounds like you made a mistake in your script - perhaps missing the colon or getting the indentation wrong. Without seeing the file you are running it is impossible to say more.\nedit:\nI have figured out what is going wrong. You are tr... | [
13
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0003636798_python_windows.txt |
Q:
Matrix multiplication with Numpy
Assume that I have an affinity matrix A and a diagonal matrix D. How can I compute the Laplacian matrix in Python with nympy?
L = D^(-1/2) A D^(1/2)
Currently, I use L = D**(-1/2) * A * D**(1/2). Is this a right way?
Thank you.
A:
Please note that it is recommended to use numpy's array instead of matrix: see this paragraph in the user guide. The confusion in some of the responses is an example of what can go wrong... In particular, D**0.5 and the products are elementwise if applied to numpy arrays, which would give you a wrong answer. For example:
import numpy as np
from numpy import dot, diag
D = diag([1., 2., 3.])
print D**(-0.5)
[[ 1. Inf Inf]
[ Inf 0.70710678 Inf]
[ Inf Inf 0.57735027]]
In your case, the matrix is diagonal, and so the square root of the matrix is just another diagonal matrix with the square root of the diagonal elements. Using numpy arrays, the equation becomes
D = np.array([1., 2., 3.]) # note that we define D just by its diagonal elements
A = np.cov(np.random.randn(3,100)) # a random symmetric positive definite matrix
L = dot(diag(D**(-0.5)), dot(A, diag(D**0.5)))
A:
Numpy allows you to exponentiate a diagonal "matrix" with positive elements and a positive exponent directly:
m = diag(range(1, 11))
print m**0.5
The result is what you expect in this case because NumPy actually applies the exponentiation to each element of the NumPy array individually.
However, it indeed does not allow you to exponentiate any NumPy matrix directly:
m = matrix([[1, 1], [1, 2]])
print m**0.5
produces the TypeError that you have observed (the exception says that the exponent must be an integer–even for matrices that can be diagonalized with positive coefficients).
So, as long as your matrix D is diagonal and your exponent is positive, you should be able to directly use your formula.
A:
Well, the only problem I see is that if you are using Python 2.6.x (without from __future__ import division), then 1/2 will be interpreted as 0 because it will be considered integer division. You can get around this by using D**(-.5) * A * D**.5 instead. You can also force float division with 1./2 instead of 1/2.
Other than that, it looks correct to me.
Edit:
I was trying to exponentiate a numpy array, not a matrix before, which works with D**.5. You can exponentiate a matrix element-wise using numpy.power. So you would just use
from numpy import power
power(D, -.5) * A * power(D, .5)
A:
Does numpy have square root function for matrixes? Then you could do sqrt(D) instead of (D**(1/2))
Maybe the formula should realy be written
L = (D**(-1/2)) * A * (D**(1/2))
Based on previous comment this formula should work in case of D being diagonal matrix (I have not chance to prove it now).
| Matrix multiplication with Numpy | Assume that I have an affinity matrix A and a diagonal matrix D. How can I compute the Laplacian matrix in Python with nympy?
L = D^(-1/2) A D^(1/2)
Currently, I use L = D**(-1/2) * A * D**(1/2). Is this a right way?
Thank you.
| [
"Please note that it is recommended to use numpy's array instead of matrix: see this paragraph in the user guide. The confusion in some of the responses is an example of what can go wrong... In particular, D**0.5 and the products are elementwise if applied to numpy arrays, which would give you a wrong answer. For e... | [
4,
3,
1,
0
] | [] | [] | [
"matrix_multiplication",
"numpy",
"python"
] | stackoverflow_0003580632_matrix_multiplication_numpy_python.txt |
Q:
serial port: have to send \n
[edit]
Initially I thought this was a pyserial problem but it's not. Basically it's a system problem: Sending anything over the serial port (/dev/ttyS0) would need a "\n" or "\r" or else it'll just be buffered. Below is the original question. Is it a limitation of Linux driver or is there some settings I can change?
Hello there,
I'm trying to use pyserial to write some test code. In reality I'll be transmitting binary data but that's not my problem. My problem is that: it looks like pyserial write() command will only actually send the data when it sees "\n".
Take the following code for sending pure text file.
for l in file:
print "Sending %s" % l
s.write( l )
s.flush()
time.sleep(2)
Unless I insert s.write("\n") after s.write( l ), nothing would be seen on the other side. Is there a way I can make pyserial to send whatever I want whenever I want it?
Thanks,
A:
from the documentation for pyserial http://pyserial.sourceforge.net/pyserial_api.html that does not seem to be the case. which version are you using?
to clarify, which pySerial and which python seem to be relevant.
| serial port: have to send \n | [edit]
Initially I thought this was a pyserial problem but it's not. Basically it's a system problem: Sending anything over the serial port (/dev/ttyS0) would need a "\n" or "\r" or else it'll just be buffered. Below is the original question. Is it a limitation of Linux driver or is there some settings I can change?
Hello there,
I'm trying to use pyserial to write some test code. In reality I'll be transmitting binary data but that's not my problem. My problem is that: it looks like pyserial write() command will only actually send the data when it sees "\n".
Take the following code for sending pure text file.
for l in file:
print "Sending %s" % l
s.write( l )
s.flush()
time.sleep(2)
Unless I insert s.write("\n") after s.write( l ), nothing would be seen on the other side. Is there a way I can make pyserial to send whatever I want whenever I want it?
Thanks,
| [
"from the documentation for pyserial http://pyserial.sourceforge.net/pyserial_api.html that does not seem to be the case. which version are you using?\nto clarify, which pySerial and which python seem to be relevant.\n"
] | [
1
] | [] | [] | [
"pyserial",
"python",
"serial_port"
] | stackoverflow_0003636910_pyserial_python_serial_port.txt |
Q:
Long programs using python -c switch
I would like to use python for things I've been doing using bash. Is it possible to use the -c switch for long programs, e.g. a for loop with two statements? This would let me use python directly from command line, just like bash or php.
Thanks.
EDIT: Don't know how I missed it, simply doing a python -c ' and then pressing enter does what I've wanted to do. I'd tried a lot of variations, and one using a \ but that didn't work, so I asked the question.
e.g.
$python -c '
>print "x"
>for i in range(3):
> print "y" '
does what I wanted to do, though Rod's answer looks good too.
A:
No problem if your underlying shell is bash, since you can continue an argument across multiple lines if an opened ' (quote) is not yet closed -- e.g.:
$ python -c'for x in range(3):
> if x!=1:
> print x'
0
2
$
The > is bash's default PS2, the "multi-line continuation prompt", as distinguished from $, AKA PS1, the normal "start entering a command" prompt.
If you can't use such multi-line continuation, multiple nested block statements (such as an if within a loop) could otherwise be problematic.
A:
You can use compound statements, using the semi-colon to delimiter the statements, such as
python -c "for x in range(0,3) : print x; print x
Then output would then be:
0
0
1
1
2
2
see http://docs.python.org/reference/compound_stmts.html
A:
When used inside a script, I think it would be better to have python read the script from standard input, like so:
#!/bin/bash
python - arg1 arg2 <<END
import sys
print 'Arg:', sys.argv[1:]
END
This uses bash's HEREDOC syntax.
A:
If you are running from a bash script, just use quotes:
#!/bin/sh
python -c 'import os
for i in range(3):
for j in range(3):
print i*j
'
echo "done"
Otherwise, if using the cmd line, use ; semicolons to seperate statements, or use single quotes again to wrap around to the next line:
python -c 'import os
> for i in range(3):
> for j in range(3):
> print i*j
> '
| Long programs using python -c switch | I would like to use python for things I've been doing using bash. Is it possible to use the -c switch for long programs, e.g. a for loop with two statements? This would let me use python directly from command line, just like bash or php.
Thanks.
EDIT: Don't know how I missed it, simply doing a python -c ' and then pressing enter does what I've wanted to do. I'd tried a lot of variations, and one using a \ but that didn't work, so I asked the question.
e.g.
$python -c '
>print "x"
>for i in range(3):
> print "y" '
does what I wanted to do, though Rod's answer looks good too.
| [
"No problem if your underlying shell is bash, since you can continue an argument across multiple lines if an opened ' (quote) is not yet closed -- e.g.:\n$ python -c'for x in range(3):\n> if x!=1:\n> print x'\n0\n2\n$\n\nThe > is bash's default PS2, the \"multi-line continuation prompt\", as distinguished fro... | [
8,
5,
3,
1
] | [] | [] | [
"command_line",
"python"
] | stackoverflow_0003637020_command_line_python.txt |
Q:
Python Twisted: "wait" for a variable to be filled by another event
I know that twisted will not "wait"... I am working with an XMPP client to exchange data with an external process. I send an request and need to fetch the corresponding answer. I use a sendMessage to send my request to the server. When the server answers a onMessage method will receive it and check if it an answer to a request (not necessarily the one I am looking for) and puts any answer in a stack.
As return to my sendRequest I want to return the results, so I would like to pop the response to my request from the stack and return.
I read about threads, defers, callbacks and conditionals, tried a lot of the examples and none is working for me. So my example code here is very stripped down pseudo-code to illustrate my problem. Any advice is appreciated.
class Foo(FooMessageProtocol):
def __init__(self, *args, **kwargs):
self.response_stack = dict()
super(Foo, self).__init__(*args, **kwargs)
def sendRequest(self, data):
self.sendMessage(id, data)
# I know that this doesn't work, just to illustrate what I would like to do:
while 1:
if self.response_stack.has_key(id):
break
return self.response_stack.pop(id)
def receiveAnswers(self, msg):
response = parse(msg)
self.response_stack[response['id']] = response
A:
you can't return the results to sendRequest, because sendRequest can't wait.
make sendRequest return a Deferred instead, and fire it when the result arrives.
So the code calling sendRequest can just add a callback to the deferred and it will be called when there's a response.
Something like this (pseudo-code):
class Foo(FooMessageProtocol):
def __init__(self, *args, **kwargs):
self._deferreds = {}
super(Foo, self).__init__(*args, **kwargs)
def sendRequest(self, data):
self.sendMessage(id, data)
d = self._deferreds[id] = defer.Deferred()
return d
def receiveAnswers(self, msg):
response = parse(msg)
id = response['id']
if id in self._deferreds:
self._deferreds.pop(id).callback(response)
| Python Twisted: "wait" for a variable to be filled by another event | I know that twisted will not "wait"... I am working with an XMPP client to exchange data with an external process. I send an request and need to fetch the corresponding answer. I use a sendMessage to send my request to the server. When the server answers a onMessage method will receive it and check if it an answer to a request (not necessarily the one I am looking for) and puts any answer in a stack.
As return to my sendRequest I want to return the results, so I would like to pop the response to my request from the stack and return.
I read about threads, defers, callbacks and conditionals, tried a lot of the examples and none is working for me. So my example code here is very stripped down pseudo-code to illustrate my problem. Any advice is appreciated.
class Foo(FooMessageProtocol):
def __init__(self, *args, **kwargs):
self.response_stack = dict()
super(Foo, self).__init__(*args, **kwargs)
def sendRequest(self, data):
self.sendMessage(id, data)
# I know that this doesn't work, just to illustrate what I would like to do:
while 1:
if self.response_stack.has_key(id):
break
return self.response_stack.pop(id)
def receiveAnswers(self, msg):
response = parse(msg)
self.response_stack[response['id']] = response
| [
"you can't return the results to sendRequest, because sendRequest can't wait.\nmake sendRequest return a Deferred instead, and fire it when the result arrives.\nSo the code calling sendRequest can just add a callback to the deferred and it will be called when there's a response.\nSomething like this (pseudo-code):\... | [
3
] | [] | [] | [
"asynchronous",
"python",
"twisted"
] | stackoverflow_0003636890_asynchronous_python_twisted.txt |
Q:
python -> multiprocessing module
Here's what I am trying to accomplish -
I have about a million files which I need to parse & append the parsed content to a single file.
Since a single process takes ages, this option is out.
Not using threads in Python as it essentially comes to running a single process (due to GIL).
Hence using multiprocessing module. i.e. spawning 4 sub-processes to utilize all that raw core power :)
So far so good, now I need a shared object which all the sub-processes have access to. I am using Queues from the multiprocessing module. Also, all the sub-processes need to write their output to a single file. A potential place to use Locks I guess. With this setup when I run, I do not get any error (so the parent process seems fine), it just stalls. When I press ctrl-C I see a traceback (one for each sub-process). Also no output is written to the output file. Here's code (note that everything runs fine without multi-processes) -
import os
import glob
from multiprocessing import Process, Queue, Pool
data_file = open('out.txt', 'w+')
def worker(task_queue):
for file in iter(task_queue.get, 'STOP'):
data = mine_imdb_page(os.path.join(DATA_DIR, file))
if data:
data_file.write(repr(data)+'\n')
return
def main():
task_queue = Queue()
for file in glob.glob('*.csv'):
task_queue.put(file)
task_queue.put('STOP') # so that worker processes know when to stop
# this is the block of code that needs correction.
if multi_process:
# One way to spawn 4 processes
# pool = Pool(processes=4) #Start worker processes
# res = pool.apply_async(worker, [task_queue, data_file])
# But I chose to do it like this for now.
for i in range(4):
proc = Process(target=worker, args=[task_queue])
proc.start()
else: # single process mode is working fine!
worker(task_queue)
data_file.close()
return
what am I doing wrong? I also tried passing the open file_object to each of the processes at the time of spawning. But to no effect. e.g.- Process(target=worker, args=[task_queue, data_file]). But this did not change anything. I feel the subprocesses are not able to write to the file for some reason. Either the instance of the file_object is not getting replicated (at the time of spawn) or some other quirk... Anybody got an idea?
EXTRA: Also Is there any way to keep a persistent mysql_connection open & pass it across to the sub_processes? So I open a mysql connection in my parent process & the open connection should be accessible to all my sub-processes. Basically this is the equivalent of a shared_memory in python. Any ideas here?
A:
Although the discussion with Eric was fruitful, later on I found a better way of doing this. Within the multiprocessing module there is a method called 'Pool' which is perfect for my needs.
It's optimizes itself to the number of cores my system has. i.e. only as many processes are spawned as the no. of cores. Of course this is customizable. So here's the code. Might help someone later-
from multiprocessing import Pool
def main():
po = Pool()
for file in glob.glob('*.csv'):
filepath = os.path.join(DATA_DIR, file)
po.apply_async(mine_page, (filepath,), callback=save_data)
po.close()
po.join()
file_ptr.close()
def mine_page(filepath):
#do whatever it is that you want to do in a separate process.
return data
def save_data(data):
#data is a object. Store it in a file, mysql or...
return
Still going through this huge module. Not sure if save_data() is executed by parent process or this function is used by spawned child processes. If it's the child which does the saving it might lead to concurrency issues in some situations. If anyone has anymore experience in using this module, you appreciate more knowledge here...
A:
The docs for multiprocessing indicate several methods of sharing state between processes:
http://docs.python.org/dev/library/multiprocessing.html#sharing-state-between-processes
I'm sure each process gets a fresh interpreter and then the target (function) and args are loaded into it. In that case, the global namespace from your script would have been bound to your worker function, so the data_file would be there. However, I am not sure what happens to the file descriptor as it is copied across. Have you tried passing the file object as one of the args?
An alternative is to pass another Queue that will hold the results from the workers. The workers put the results and the main code gets the results and writes it to the file.
| python -> multiprocessing module | Here's what I am trying to accomplish -
I have about a million files which I need to parse & append the parsed content to a single file.
Since a single process takes ages, this option is out.
Not using threads in Python as it essentially comes to running a single process (due to GIL).
Hence using multiprocessing module. i.e. spawning 4 sub-processes to utilize all that raw core power :)
So far so good, now I need a shared object which all the sub-processes have access to. I am using Queues from the multiprocessing module. Also, all the sub-processes need to write their output to a single file. A potential place to use Locks I guess. With this setup when I run, I do not get any error (so the parent process seems fine), it just stalls. When I press ctrl-C I see a traceback (one for each sub-process). Also no output is written to the output file. Here's code (note that everything runs fine without multi-processes) -
import os
import glob
from multiprocessing import Process, Queue, Pool
data_file = open('out.txt', 'w+')
def worker(task_queue):
for file in iter(task_queue.get, 'STOP'):
data = mine_imdb_page(os.path.join(DATA_DIR, file))
if data:
data_file.write(repr(data)+'\n')
return
def main():
task_queue = Queue()
for file in glob.glob('*.csv'):
task_queue.put(file)
task_queue.put('STOP') # so that worker processes know when to stop
# this is the block of code that needs correction.
if multi_process:
# One way to spawn 4 processes
# pool = Pool(processes=4) #Start worker processes
# res = pool.apply_async(worker, [task_queue, data_file])
# But I chose to do it like this for now.
for i in range(4):
proc = Process(target=worker, args=[task_queue])
proc.start()
else: # single process mode is working fine!
worker(task_queue)
data_file.close()
return
what am I doing wrong? I also tried passing the open file_object to each of the processes at the time of spawning. But to no effect. e.g.- Process(target=worker, args=[task_queue, data_file]). But this did not change anything. I feel the subprocesses are not able to write to the file for some reason. Either the instance of the file_object is not getting replicated (at the time of spawn) or some other quirk... Anybody got an idea?
EXTRA: Also Is there any way to keep a persistent mysql_connection open & pass it across to the sub_processes? So I open a mysql connection in my parent process & the open connection should be accessible to all my sub-processes. Basically this is the equivalent of a shared_memory in python. Any ideas here?
| [
"Although the discussion with Eric was fruitful, later on I found a better way of doing this. Within the multiprocessing module there is a method called 'Pool' which is perfect for my needs. \nIt's optimizes itself to the number of cores my system has. i.e. only as many processes are spawned as the no. of cores. Of... | [
4,
3
] | [] | [] | [
"multiprocessing",
"python",
"queue"
] | stackoverflow_0003586723_multiprocessing_python_queue.txt |
Q:
Decompressing a .bz2 file in Python
So, this is a seemingly simple question, but I'm apparently very very dull. I have a little script that downloads all the .bz2 files from a webpage, but for some reason the decompressing of that file is giving me a MAJOR headache.
I'm quite a Python newbie, so the answer is probably quite obvious, please help me.
In this bit of the script, I already have the file, and I just want to read it out to a variable, then decompress that? Is that right? I've tried all sorts of way to do this, I usually get "ValueError: couldn't find end of stream" error on the last line in this snippet. I've tried to open up the zipfile and write it out to a string in a zillion different ways. This is the latest.
openZip = open(zipFile, "r")
s = ''
while True:
newLine = openZip.readline()
if(len(newLine)==0):
break
s+=newLine
print s
uncompressedData = bz2.decompress(s)
Hi Alex, I should've listed all the other methods I've tried, as I've tried the read() way.
METHOD A:
print 'decompressing ' + filename
fileHandle = open(zipFile)
uncompressedData = ''
while True:
s = fileHandle.read(1024)
if not s:
break
print('RAW "%s"', s)
uncompressedData += bz2.decompress(s)
uncompressedData += bz2.flush()
newFile = open(steamTF2mapdir + filename.split(".bz2")[0],"w")
newFile.write(uncompressedData)
newFile.close()
I get the error:
uncompressedData += bz2.decompress(s)
ValueError: couldn't find end of stream
METHOD B
zipFile = steamTF2mapdir + filename
print 'decompressing ' + filename
fileHandle = open(zipFile)
s = fileHandle.read()
uncompressedData = bz2.decompress(s)
Same error :
uncompressedData = bz2.decompress(s)
ValueError: couldn't find end of stream
Thanks so much for you prompt reply. I'm really banging my head against the wall, feeling inordinately thick for not being able to decompress a simple .bz2 file.
By the by, used 7zip to decompress it manually, to make sure the file isn't wonky or anything, and it decompresses fine.
A:
You're opening and reading the compressed file as if it was a textfile made up of lines. DON'T! It's NOT.
uncompressedData = bz2.BZ2File(zipFile).read()
seems to be closer to what you're angling for.
Edit: the OP has shown a few more things he's tried (though I don't see any notes about having tried the best method -- the one-liner I recommend above!) but they seem to all have one error in common, and I repeat the key bits from above:
opening ... the compressed file as if
it was a textfile ... It's NOT.
open(filename) and even the more explicit open(filename, 'r') open, for reading, a text file -- a compressed file is a binary file, so in order to read it correctly you must open it with open(filename, 'rb'). ((my recommended bz2.BZ2File KNOWS it's dealing with a compressed file, of course, so there's no need to tell it anything more)).
In Python 2.*, on Unix-y systems (i.e. every system except Windows), you could get away with a sloppy use of open (but in Python 3.* you can't, as text is Unicode, while binary is bytes -- different types).
In Windows (and before then in DOS) it's always been indispensable to distinguish, as Windows' text files, for historical reason, are peculiar (use two bytes rather than one to end lines, and, at least in some cases, take a byte worth '\0x1A' as meaning a logical end of file) and so the reading and writing low-level code must compensate.
So I suspect the OP is using Windows and is paying the price for not carefully using the 'rb' option ("read binary") to the open built-in. (though bz2.BZ2File is still simpler, whatever platform you're using!-).
A:
openZip = open(zipFile, "r")
If you're running on Windows, you may want to do say openZip = open(zipFile, "rb") here since the file is likely to contain CR/LF combinations, and you don't want them to be translated.
newLine = openZip.readline()
As Alex pointed out, this is very wrong, as the concept of "lines" is foreign to a compressed stream.
s = fileHandle.read(1024)
[...]
uncompressedData += bz2.decompress(s)
This is wrong for the same reason. 1024-byte chunks aren't likely to mean much to the decompressor, since it's going to want to work with it's own block-size.
s = fileHandle.read()
uncompressedData = bz2.decompress(s)
If that doesn't work, I'd say it's the new-line translation problem I mentioned above.
A:
This was very helpful.
44 of 2300 files gave an end of file missing error, on Windows open.
Adding the b(inary) flag to open fixed the problem.
for line in bz2.BZ2File(filename, 'rb', 10000000) :
works well. (the 10M is the buffering size that works well with the large files involved)
Thanks!
| Decompressing a .bz2 file in Python | So, this is a seemingly simple question, but I'm apparently very very dull. I have a little script that downloads all the .bz2 files from a webpage, but for some reason the decompressing of that file is giving me a MAJOR headache.
I'm quite a Python newbie, so the answer is probably quite obvious, please help me.
In this bit of the script, I already have the file, and I just want to read it out to a variable, then decompress that? Is that right? I've tried all sorts of way to do this, I usually get "ValueError: couldn't find end of stream" error on the last line in this snippet. I've tried to open up the zipfile and write it out to a string in a zillion different ways. This is the latest.
openZip = open(zipFile, "r")
s = ''
while True:
newLine = openZip.readline()
if(len(newLine)==0):
break
s+=newLine
print s
uncompressedData = bz2.decompress(s)
Hi Alex, I should've listed all the other methods I've tried, as I've tried the read() way.
METHOD A:
print 'decompressing ' + filename
fileHandle = open(zipFile)
uncompressedData = ''
while True:
s = fileHandle.read(1024)
if not s:
break
print('RAW "%s"', s)
uncompressedData += bz2.decompress(s)
uncompressedData += bz2.flush()
newFile = open(steamTF2mapdir + filename.split(".bz2")[0],"w")
newFile.write(uncompressedData)
newFile.close()
I get the error:
uncompressedData += bz2.decompress(s)
ValueError: couldn't find end of stream
METHOD B
zipFile = steamTF2mapdir + filename
print 'decompressing ' + filename
fileHandle = open(zipFile)
s = fileHandle.read()
uncompressedData = bz2.decompress(s)
Same error :
uncompressedData = bz2.decompress(s)
ValueError: couldn't find end of stream
Thanks so much for you prompt reply. I'm really banging my head against the wall, feeling inordinately thick for not being able to decompress a simple .bz2 file.
By the by, used 7zip to decompress it manually, to make sure the file isn't wonky or anything, and it decompresses fine.
| [
"You're opening and reading the compressed file as if it was a textfile made up of lines. DON'T! It's NOT.\nuncompressedData = bz2.BZ2File(zipFile).read()\n\nseems to be closer to what you're angling for.\nEdit: the OP has shown a few more things he's tried (though I don't see any notes about having tried the bes... | [
16,
9,
6
] | [] | [] | [
"compression",
"python"
] | stackoverflow_0001250688_compression_python.txt |
Q:
Python URL download
The code below returns none. How can I fix it? I'm using Python 2.6.
import urllib
URL = "http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sl1t1v&e=.csv"
symbols = ('GGP', 'JPM', 'AIG', 'AMZN','GGP', 'JPM', 'AIG', 'AMZN')
#symbols = ('GGP')
def fetch_quote(symbols):
url = URL % '+'.join(symbols)
fp = urllib.urlopen(url)
try:
data = fp.read()
finally:
fp.close()
def main():
data_fp = fetch_quote(symbols)
# print data_fp
if __name__ =='__main__':
main()
A:
You have to explicitly return the data from fetch_quote function. Something like this:
def fetch_quote(symbols):
url = URL % '+'.join(symbols)
fp = urllib.urlopen(url)
try:
data = fp.read()
finally:
fp.close()
return data # <======== Return
In the absence of an explicit return statement Python returns None which is what you are seeing.
A:
Your method doesn't explicitly return anything, so it returns None
| Python URL download | The code below returns none. How can I fix it? I'm using Python 2.6.
import urllib
URL = "http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sl1t1v&e=.csv"
symbols = ('GGP', 'JPM', 'AIG', 'AMZN','GGP', 'JPM', 'AIG', 'AMZN')
#symbols = ('GGP')
def fetch_quote(symbols):
url = URL % '+'.join(symbols)
fp = urllib.urlopen(url)
try:
data = fp.read()
finally:
fp.close()
def main():
data_fp = fetch_quote(symbols)
# print data_fp
if __name__ =='__main__':
main()
| [
"You have to explicitly return the data from fetch_quote function. Something like this:\ndef fetch_quote(symbols):\n url = URL % '+'.join(symbols)\n fp = urllib.urlopen(url)\n try:\n data = fp.read()\n finally:\n fp.close()\n return data # <======== Return\n\nIn the absence of an explic... | [
4,
2
] | [] | [] | [
"python",
"url"
] | stackoverflow_0003637553_python_url.txt |
Q:
Python change data into sequence
The "idata" I pulled from this URL needs to be turned into a sequence, how do i turn it into a sequence
import urllib, csv
URL = "http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sl1vt1&e=.csv"
symbols = ('GGP', 'JPM', 'AIG', 'AMZN','GGP', 'JPM', 'AIG', 'AMZN')
#symbols = ('GGP',)
def fetch_quote(symbols):
url = URL % '+'.join(symbols)
fp = urllib.urlopen(url)
try:
data = fp.read()
finally:
fp.close()
return data # <======== Return
idata = fetch_quote(symbols)
print idata
Python URL download
A:
I would guess based on the URL that you are downloading data in CSV format. As such, you probably want to parse it with a CSV reader.
A:
What do you mean by "a sequence"? You could turn it into a dictionary as follows. Just place this code after you produce idata.
stocks = {}
for line in idata.split("\r\n"):
if line == '':
continue
stock, price, volume, stime = line.split(',')
stock = stock[1:-1]
price = float(price)
volume = int(volume)
stime = stime[1:-1]
stocks[stock] = (price, volume, stime)
If you want to be a bit more robust, you can use the csv module (add import csv to the top of your code) then use
reader = csv.reader(idata.split("\r\n"))
stocks = {}
for line in reader:
if line == '':
continue
stock, price, volume, stime = line
price = float(price)
volume = int(volume)
stocks[stock] = (price, volume, stime)
For inserting into a database, the following may work
reader = csv.reader(idata.split("\r\n"))
stocks = []
for line in reader:
if line == '':
continue
stock, price, volume, stime = line
price = float(price)
volume = int(volume)
stocks.append((stock, price, volume, stime))
csr.executemany('INSERT INTO test.prices VALUES (?,?,?,?)', stocks)
This of course assumes your columns are in the same order as the elements of the array.
| Python change data into sequence | The "idata" I pulled from this URL needs to be turned into a sequence, how do i turn it into a sequence
import urllib, csv
URL = "http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sl1vt1&e=.csv"
symbols = ('GGP', 'JPM', 'AIG', 'AMZN','GGP', 'JPM', 'AIG', 'AMZN')
#symbols = ('GGP',)
def fetch_quote(symbols):
url = URL % '+'.join(symbols)
fp = urllib.urlopen(url)
try:
data = fp.read()
finally:
fp.close()
return data # <======== Return
idata = fetch_quote(symbols)
print idata
Python URL download
| [
"I would guess based on the URL that you are downloading data in CSV format. As such, you probably want to parse it with a CSV reader. \n",
"What do you mean by \"a sequence\"? You could turn it into a dictionary as follows. Just place this code after you produce idata.\nstocks = {}\nfor line in idata.split(\"\\r... | [
1,
1
] | [] | [] | [
"python",
"url"
] | stackoverflow_0003637986_python_url.txt |
Q:
sqlalchemy: turn off declarative polymorphic join?
Is there a way in sqlalchemy to turn off declarative's polymorphic join loading, in a single query? Most of the time it's nice, but I have:
class A(Base) :
discriminator = Column('type', mysql.INTEGER(1), index=True, nullable=False)
__mapper_args__ = { 'polymorphic_on' : discriminator }
id = Column(Integer, primary_key=True)
p = Column(Integer)
class B(A) :
__mapper_args__ = { 'polymorphic_identity' : 0 }
id = Column(Integer, primary_key=True)
x = Column(Integer)
class C(A) :
__mapper_args__ = { 'polymorphic_identity' : 1 }
id = Column(Integer, primary_key=True)
y = Column(String)
I want to make a query such that I get all A.ids for which B.x > 10, if that A is actually a B, or where C.y == 'blah', if that A is actually a C, all ordered by p.
To do it iteratively, I'm starting just with the first part - "get all A.id for which B.x > 10 if that A is actually a B". So I thought I would start with an outer join:
session.query(A.id).outerjoin((B, B.id == A.id)).filter(B.x > 10)
... except there seems to be no way to avoid having that outerjoin((B, B.id == A.id)) clause generate a full join of everything in A to everything in B within a subselect. If B doesn't inherit from A, then that doesn't happen, so I'm thinking it's the polymorphic declarative code generation that does that. Is there a way to turn that off? Or to force the outerjoin to do what I want?
What I want is something like this:
select a.id from A a left outer join B b on b.id == a.id where b.x > 10
but instead I get something like:
select a.id from A a left outer join (select B.id, B.x, A.id from B inner join A on B.id == A.id)
... as an aside, if it's not possible, then is the latter less efficient than the former? Will the sql engine actually perform that inner join, or will it elide it?
A:
You should use with_polymorphic() instead of outerjoin(), which seems to return the expected results:
session.query(A).with_polymorphic(B).filter(B.x > 10).all()
# BEGIN
# SELECT "A".type AS "A_type", "A".id AS "A_id", "A".p AS "A_p", "B".id AS "B_id", "B".x AS "B_x"
# FROM "A" LEFT OUTER JOIN "B" ON "A".id = "B".id
# WHERE "B".x > ?
# (10,)
# Col ('A_type', 'A_id', 'A_p', 'B_id', 'B_x')
Compared to:
session.query(A.id).outerjoin((B, B.id == A.id)).filter(B.x > 10)
# BEGIN
# SELECT "A".id AS "A_id"
# FROM "A" LEFT OUTER JOIN (SELECT "A".type AS "A_type", "A".id AS "A_id", "A".p AS "A_p", "B".id AS "B_id", "B".x AS "B_x"
# FROM "A" JOIN "B" ON "A".id = "B".id) AS anon_1 ON anon_1."A_id" = "A".id
# WHERE anon_1."B_x" > ?
# (10,)
# Col ('A_id',)
The code I used to test this, in case anybody wants to test this neat bit of SQLAlchemy:
#!/usr/bin/env python
import logging
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class A(Base) :
__mapper_args__ = { 'polymorphic_on' : discriminator }
__tablename__ = 'A'
id = Column(Integer, primary_key=True)
discriminator = Column('type', Integer, index=True, nullable=False)
p = Column(Integer)
class B(A) :
__mapper_args__ = { 'polymorphic_identity' : 0 }
__tablename__ = 'B'
id = Column(Integer, ForeignKey('A.id'), primary_key=True)
x = Column(Integer)
class C(A) :
__mapper_args__ = { 'polymorphic_identity' : 1 }
__tablename__ = 'C'
id = Column(Integer, ForeignKey('A.id'), primary_key=True)
y = Column(String)
meta = Base.metadata
meta.bind = create_engine('sqlite://')
meta.create_all()
Session = sessionmaker()
Session.configure(bind=meta.bind)
session = Session()
log = logging.getLogger('sqlalchemy')
log.addHandler(logging.StreamHandler())
log.setLevel(logging.DEBUG)
session.query(A.id).outerjoin((B, B.id == A.id)).filter(B.x > 10).all()
session.query(A).with_polymorphic(B).filter(B.x > 10).all()
I ran this on Python 2.7 with SQLAlchemy 0.6.4.
A:
You could try building the queries for each subclass individually, then unioning them together. When querying B.id, SQLAlchemy implicitly joins the superclass and returns A.id instead, so taking the union of selects for B.id and C.id only returns a single column.
>>> b_query = session.query(B.id).filter(B.x > 10)
>>> c_query = session.query(C.id).filter(C.y == 'foo')
>>> print b_query.union(c_query)
SELECT anon_1."A_id" AS "anon_1_A_id"
FROM (SELECT "A".id AS "A_id"
FROM "A" JOIN "B" ON "A".id = "B".id
WHERE "B".x > ? UNION SELECT "A".id AS "A_id"
FROM "A" JOIN "C" ON "A".id = "C".id
WHERE "C".y = ?) AS anon_1
You still get a subselect, but only a single "layer" of joins - the outer select is just renaming the column.
| sqlalchemy: turn off declarative polymorphic join? | Is there a way in sqlalchemy to turn off declarative's polymorphic join loading, in a single query? Most of the time it's nice, but I have:
class A(Base) :
discriminator = Column('type', mysql.INTEGER(1), index=True, nullable=False)
__mapper_args__ = { 'polymorphic_on' : discriminator }
id = Column(Integer, primary_key=True)
p = Column(Integer)
class B(A) :
__mapper_args__ = { 'polymorphic_identity' : 0 }
id = Column(Integer, primary_key=True)
x = Column(Integer)
class C(A) :
__mapper_args__ = { 'polymorphic_identity' : 1 }
id = Column(Integer, primary_key=True)
y = Column(String)
I want to make a query such that I get all A.ids for which B.x > 10, if that A is actually a B, or where C.y == 'blah', if that A is actually a C, all ordered by p.
To do it iteratively, I'm starting just with the first part - "get all A.id for which B.x > 10 if that A is actually a B". So I thought I would start with an outer join:
session.query(A.id).outerjoin((B, B.id == A.id)).filter(B.x > 10)
... except there seems to be no way to avoid having that outerjoin((B, B.id == A.id)) clause generate a full join of everything in A to everything in B within a subselect. If B doesn't inherit from A, then that doesn't happen, so I'm thinking it's the polymorphic declarative code generation that does that. Is there a way to turn that off? Or to force the outerjoin to do what I want?
What I want is something like this:
select a.id from A a left outer join B b on b.id == a.id where b.x > 10
but instead I get something like:
select a.id from A a left outer join (select B.id, B.x, A.id from B inner join A on B.id == A.id)
... as an aside, if it's not possible, then is the latter less efficient than the former? Will the sql engine actually perform that inner join, or will it elide it?
| [
"You should use with_polymorphic() instead of outerjoin(), which seems to return the expected results:\nsession.query(A).with_polymorphic(B).filter(B.x > 10).all()\n# BEGIN\n# SELECT \"A\".type AS \"A_type\", \"A\".id AS \"A_id\", \"A\".p AS \"A_p\", \"B\".id AS \"B_id\", \"B\".x AS \"B_x\" \n# FROM \"A\" LEFT OUTE... | [
1,
1
] | [] | [] | [
"declarative",
"python",
"sqlalchemy"
] | stackoverflow_0003630310_declarative_python_sqlalchemy.txt |
Q:
Multiple simultaneous tcp client connections for performace test
i need to create multiple TCP connections simultaneously to some custom TCP-server application for its performance testing. I know a lot of such for Web (i.e. curl-loader based on libcurl), but I didn't found some general one.
Scenario for client is the simplest: create connection, send special data, read the answer and close connection. In every step there's timestamp. All timestamps should be written to file for the further calculations. I need about 10 000 such connections in parallel.
I'd prefer some ready solution but there's nothing found in Google, so I'm ready to write this one with Python. If so, can you recommend me a suitable python modules that could produce this amount of connections? (multiprocessing, twisted..?)
A:
My two cents:
Go for Twisted, or any other asynchronous networking library.
Make sure you can open enough file descriptors on the client and on the
server. On my Linux box, for instance, I can have no more than 1024 file
file descriptors by default:
carlos@marcelino:~$ ulimit -a
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
[..]
open files (-n) 1024
[..]
It may pay to run the client and the server on different machines.
A:
Handling 10k connections is a tough problem (known as C10K problem). If you need real numbers, stick with C++(Boost/POCO libraries or OS native API), or distribute clients across 10 load-generating clients.
No way should you try this with Python (handle 10'000 connection on 1 CPU core - not realistic).
| Multiple simultaneous tcp client connections for performace test | i need to create multiple TCP connections simultaneously to some custom TCP-server application for its performance testing. I know a lot of such for Web (i.e. curl-loader based on libcurl), but I didn't found some general one.
Scenario for client is the simplest: create connection, send special data, read the answer and close connection. In every step there's timestamp. All timestamps should be written to file for the further calculations. I need about 10 000 such connections in parallel.
I'd prefer some ready solution but there's nothing found in Google, so I'm ready to write this one with Python. If so, can you recommend me a suitable python modules that could produce this amount of connections? (multiprocessing, twisted..?)
| [
"My two cents:\n\nGo for Twisted, or any other asynchronous networking library.\nMake sure you can open enough file descriptors on the client and on the\nserver. On my Linux box, for instance, I can have no more than 1024 file\nfile descriptors by default:\ncarlos@marcelino:~$ ulimit -a\ncore file size (bl... | [
1,
0
] | [] | [] | [
"network_programming",
"parallel_processing",
"python",
"tcpclient"
] | stackoverflow_0003636141_network_programming_parallel_processing_python_tcpclient.txt |
Q:
What is the difference between LIST.append(1) and LIST = LIST + [1] (Python)
When I execute (I'm using the interactive shell) these statements I get this:
L=[1,2,3]
K=L
L.append(4)
L
[1,2,3,4]
K
[1,2,3,4]
But when I do exactly the same thing replacing L.append(4) with L=L+[4]
I get:
L
[1,2,3,4]
K
[1,2,3]
Is this some sort of reference thing? Why does this happen?
Another funny thing I noticed is that L+=[4] acts like .append, which is odd as I thought it would act like L = L + [4].
Clarification to all of this would be greatly appreciated.
Thanks
A:
L.append(4)
This adds an element on to the end of the existing list L.
L += [4]
The += operator invokes the magic __iadd__() method. It turns out list overrides the __iadd__() method and makes it equivalent to extend() which, like append(), adds elements directly onto an existing list.
L = L + [4]
L + [4] generates a new list which is equal to L with 4 added to the end. This new list is then assigned back to L. Because you've created a new list object, K is unchanged by this assignment.
We can use id() to identify when a new object reference is created:
>>> L = [1, 2, 3]
>>> id(L)
152678284
>>> L.append(4)
>>> id(L)
152678284
>>> L = [1, 2, 3]
>>> id(L)
152680524
>>> L = L + [4]
>>> id(L)
152678316
A:
With append you're modifying the list directly. With L=L+[4], you're making a copy of the original L and adding a new element, then assigning that result back to L and breaking its equivalence to K.
I'm not sure about the behavior of +=.
A:
If you are curious about the bytecodes:
>>> def L_app( ):
... L.append( 4 )
...
>>> def L_add( ):
... L = L + [ 4 ]
...
>>> def L_add_inplace( ):
... L += [ 4 ]
...
>>> dis.dis( L_app )
2 0 LOAD_GLOBAL 0 (L)
3 LOAD_ATTR 1 (append)
6 LOAD_CONST 1 (4)
9 CALL_FUNCTION 1
12 POP_TOP
13 LOAD_CONST 0 (None)
16 RETURN_VALUE
>>> dis.dis( L_add )
2 0 LOAD_FAST 0 (L)
3 LOAD_CONST 1 (4)
6 BUILD_LIST 1
9 BINARY_ADD
10 STORE_FAST 0 (L)
13 LOAD_CONST 0 (None)
16 RETURN_VALUE
>>> dis.dis( L_add_inplace )
2 0 LOAD_FAST 0 (L)
3 LOAD_CONST 1 (4)
6 BUILD_LIST 1
9 INPLACE_ADD
10 STORE_FAST 0 (L)
13 LOAD_CONST 0 (None)
16 RETURN_VALUE
A:
In your first example K and L variable names refer to the same object, so when you invoke a method mutating that object, changes are obviously seen through both references. In the second example + operator invokes list.__add__ which returns new object (concatenation of two lists) and L name now refers to this new object, while K is intact.
| What is the difference between LIST.append(1) and LIST = LIST + [1] (Python) | When I execute (I'm using the interactive shell) these statements I get this:
L=[1,2,3]
K=L
L.append(4)
L
[1,2,3,4]
K
[1,2,3,4]
But when I do exactly the same thing replacing L.append(4) with L=L+[4]
I get:
L
[1,2,3,4]
K
[1,2,3]
Is this some sort of reference thing? Why does this happen?
Another funny thing I noticed is that L+=[4] acts like .append, which is odd as I thought it would act like L = L + [4].
Clarification to all of this would be greatly appreciated.
Thanks
| [
"L.append(4)\n\nThis adds an element on to the end of the existing list L.\nL += [4]\n\nThe += operator invokes the magic __iadd__() method. It turns out list overrides the __iadd__() method and makes it equivalent to extend() which, like append(), adds elements directly onto an existing list.\nL = L + [4]\n\nL + [... | [
16,
2,
1,
0
] | [] | [] | [
"append",
"list",
"python"
] | stackoverflow_0003638486_append_list_python.txt |
Q:
Active texturing with pygame (possible? what concepts to look into?)
I have two images:
I'd like to essentially 'cut out' the black shape from the texture tile so that I end up with something along these lines:
Except transparent around the shape. Is this possible using pygame? This example I had to create in GIMP.
Additionally, would it be too performance-heavy to do this for every frame for a few sprites in a real-time environment? (30+ frames per second)
A:
I made a solution, however it is not the best either for speed either for beauty.
You can use double blitting with setting colorkeys for transparency. In that way the mask should have only two colors: black and white.
Note that you can't use this for images with per pixel alpha (RGBA) only for RGB images.
Other restriction is that it is recommended that the size of the texture and the mask image is the same (if not you should use areas for blitting).
In words, step by step:
create a surface with the mask. background should be white (255,255,255), the masked parts should be black (0,0,0)
create or load the texture into a surface
set a transparency colorkey for the mask for the black color
blit the mask onto the texture (or onto a copy of the texture). at this point the black parts of the mask haven't blitted to the texture because we set the black color to transparent with the set_colorkey method
now set the colorkey of the texture (or the copy of the texture) to white. remember that our current texture surface has white and textured parts.
blit the texture to the screen. the white parts won't be blitted due to we have set it to transparent with the colorkey
Code sample:
#!/usr/bin/python
# -*- coding:utf8 -*-
import pygame, sys
#init pygame
pygame.init()
#init screen
screen=pygame.display.set_mode((800,600))
screen.fill((255,0,255))
#loading the images
texture=pygame.image.load("texture.jpg").convert()
texture_rect=texture.get_rect()
texture_rect.center=(200,300)
mask=pygame.Surface((texture_rect.width,texture_rect.height)) # mask should have only 2 colors: black and white
mask.fill((255,255,255))
pygame.draw.circle(mask,(0,0,0),(texture_rect.width/2,texture_rect.height/2),int(texture_rect.width*0.3))
mask_rect=mask.get_rect()
mask_rect.center=(600,300)
tmp_image=texture.copy() # make a copy of the texture to keep it unchanged for future usage
mask.set_colorkey((0,0,0)) # we want the black colored parts of the mask to be transparent
tmp_image.blit(mask,(0,0)) # blit the mask to the texture. the black parts are transparent so we see the pixels of the texture there
tmp_rect=tmp_image.get_rect()
tmp_rect.center=(400,300)
tmp_image.set_colorkey((255,255,255))
screen.blit(texture,texture_rect)
screen.blit(mask,mask_rect)
screen.blit(tmp_image,tmp_rect)
pygame.display.flip()
while 1:
event=pygame.event.wait()
if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key in [pygame.K_ESCAPE, pygame.K_q]):
sys.exit()
I recommend not to use jpg as mask because of its lossy format, I recommend bmp or png (bmp is better). Remember it not uses alpha so the edges won't be anti-aliased so it is not a nice solution in 2010 :)
Here is the screenshot of the result:
Edit:
Hi again,
I made some tests with the blitting with BLEND_ADD and the results was promising. Here is the code:
import pygame, sys
#init pygame
pygame.init()
#init screen
screen=pygame.display.set_mode((800,600))
screen.fill((255,0,255))
#loading the images
texture=pygame.image.load("texture.jpg").convert_alpha()
texture_rect=texture.get_rect()
texture_rect.center=(200,300)
mask=pygame.image.load("mask2.png").convert_alpha()
mask_rect=mask.get_rect()
mask_rect.center=(600,300)
textured_mask=mask.copy()
textured_rect=textured_mask.get_rect()
textured_rect.center=400,300
textured_mask.blit(texture,(0,0),None,pygame.BLEND_ADD)
screen.blit(texture,texture_rect)
screen.blit(mask,mask_rect)
screen.blit(textured_mask,textured_rect)
pygame.display.flip()
while 1:
event=pygame.event.wait()
if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key in [pygame.K_ESCAPE, pygame.K_q]):
sys.exit()
And the result:
With this solution you can get per pixel alpha texturing. Please note that the mask should be an image with alpha channel so jpg could not be used. The best to use is png.
Texture image (texture.jpg):
Mask image (mask2.png):
A:
If you're using images with a pre-rendered alpha and additive blending, you can get alpha-blended masks:
import pygame
import sys
screen = pygame.display.set_mode( (800, 600) )
pygame.init()
background = pygame.image.load( "background.png" )
mask = pygame.image.load( "mask.png" )
# Create a surface to hold the masked image
masked_image = pygame.surface.Surface( background.get_size(), 0, mask )
# Blit the texture normally
masked_image.blit( background, (0,0) )
# Multiply by the pre-rendered, inverted mask
masked_image.blit( mask, (0,0), None, pygame.BLEND_MULT )
# masked_image now holds the 'cutout' of your texture blended onto a black
# background, so we need to blit it as such, i.e., using additive blending.
screen.fill( (0, 0, 0) )
screen.blit( masked_image, (10, 10), None, pygame.BLEND_ADD )
pygame.display.flip()
while True:
event=pygame.event.wait()
if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key in [pygame.K_ESCAPE, pygame.K_q]):
sys.exit()
Where background.png and mask.png are:
+ =
| Active texturing with pygame (possible? what concepts to look into?) | I have two images:
I'd like to essentially 'cut out' the black shape from the texture tile so that I end up with something along these lines:
Except transparent around the shape. Is this possible using pygame? This example I had to create in GIMP.
Additionally, would it be too performance-heavy to do this for every frame for a few sprites in a real-time environment? (30+ frames per second)
| [
"I made a solution, however it is not the best either for speed either for beauty.\nYou can use double blitting with setting colorkeys for transparency. In that way the mask should have only two colors: black and white.\nNote that you can't use this for images with per pixel alpha (RGBA) only for RGB images.\nOther... | [
8,
5
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0003580500_pygame_python.txt |
Q:
what is the max size of TextProperty on google app engine
class JsTree_JsonData(db.Model):
JsonData=db.TextProperty()
i can;t find what is the TextProperty
did you know ?
thanks
A:
1 megabyte.
The archived page lists maximum entity size as 1 megabyte.
| what is the max size of TextProperty on google app engine | class JsTree_JsonData(db.Model):
JsonData=db.TextProperty()
i can;t find what is the TextProperty
did you know ?
thanks
| [
"1 megabyte.\nThe archived page lists maximum entity size as 1 megabyte.\n"
] | [
6
] | [] | [] | [
"google_app_engine",
"max",
"properties",
"python"
] | stackoverflow_0003638577_google_app_engine_max_properties_python.txt |
Q:
Error Handling CRM 4 Webservice
What is the best way to trap errors/exceptions with the CRM 4 Web service. Is there a way to get more detailed error messages from the web service? There is a custom application that creates orders and when the get a error message from the web service it is not very details or useful. Is there a better way to get more detailed message from the CRM 4 web service in a custom application written in python.
A:
Catch SoapException and take a look at Detail property. You'll find everything about the error in there.
| Error Handling CRM 4 Webservice | What is the best way to trap errors/exceptions with the CRM 4 Web service. Is there a way to get more detailed error messages from the web service? There is a custom application that creates orders and when the get a error message from the web service it is not very details or useful. Is there a better way to get more detailed message from the CRM 4 web service in a custom application written in python.
| [
"Catch SoapException and take a look at Detail property. You'll find everything about the error in there.\n"
] | [
1
] | [] | [] | [
"dynamics_crm",
"dynamics_crm_4",
"python",
"web_services"
] | stackoverflow_0003637579_dynamics_crm_dynamics_crm_4_python_web_services.txt |
Q:
Having trouble with Tkinter transparency
I'm having problems making a top level widget fade in, in TKinter. For some reason the widget doesn't fade in at all, then it will show up in the taskbar, but only after clicking the button that runs this command twice (it's not supposed to be in the taskbar).
The code responsible for these problems.
Alpha = 0.0
w1.attributes("-alpha", Alpha)
w1.wm_geometry("+" + str(X) + "+" + str(M))
while 1.0 > Alpha :
Alpha = Alpha + 0.01
w1.attributes("-alpha", Alpha)
sleep(0.005)
This is python 2.6 on Windows 7.
A:
The problem is that your code never allows the window to redraw itself. Sleep causes the program to stop so the event loop isn't entered, and it's the event loop that causes the window to be drawn.
Instead of sleeping, take advantage of the event loop and update the attributes every N milliseconds until you get the desired alpha transparency you want.
Here's an example that works on the mac. I assume it works on windows too.
import Tkinter as tk
class App:
def __init__(self):
self.root = tk.Tk()
self.count = 0
b=tk.Button(text="create window", command=self.create_window)
b.pack()
self.root.mainloop()
def create_window(self):
self.count += 1
t=FadeToplevel(self.root)
t.wm_title("Window %s" % self.count)
t.fade_in()
class FadeToplevel(tk.Toplevel):
'''A toplevel widget with the ability to fade in'''
def __init__(self, *args, **kwargs):
tk.Toplevel.__init__(self, *args, **kwargs)
self.attributes("-alpha", 0.0)
def fade_in(self):
alpha = self.attributes("-alpha")
alpha = min(alpha + .01, 1.0)
self.attributes("-alpha", alpha)
if alpha < 1.0:
self.after(10, self.fade_in)
if __name__ == "__main__":
app=App()
| Having trouble with Tkinter transparency | I'm having problems making a top level widget fade in, in TKinter. For some reason the widget doesn't fade in at all, then it will show up in the taskbar, but only after clicking the button that runs this command twice (it's not supposed to be in the taskbar).
The code responsible for these problems.
Alpha = 0.0
w1.attributes("-alpha", Alpha)
w1.wm_geometry("+" + str(X) + "+" + str(M))
while 1.0 > Alpha :
Alpha = Alpha + 0.01
w1.attributes("-alpha", Alpha)
sleep(0.005)
This is python 2.6 on Windows 7.
| [
"The problem is that your code never allows the window to redraw itself. Sleep causes the program to stop so the event loop isn't entered, and it's the event loop that causes the window to be drawn. \nInstead of sleeping, take advantage of the event loop and update the attributes every N milliseconds until you get ... | [
6
] | [] | [] | [
"fadein",
"python",
"tkinter",
"transparency",
"windows_7"
] | stackoverflow_0003399882_fadein_python_tkinter_transparency_windows_7.txt |
Q:
how do I set a field with a duplicate name of another field in mechanize?
I am trying to submit a form with 2 fields with the same name but different type. I can identify the correct field I want by the field type or the number. Whats the best way of setting the correct field without iterating through all the fields?
A:
Here is the signature of set_value() method of HTMLForm class.
set_value(value, name=None, type=None, kind=None,
id=None, nr=None,by_label=False,
# by_label is deprecated
label=None)
As you can see, you could specify type parameter, useful in this case to select the proper field.
| how do I set a field with a duplicate name of another field in mechanize? | I am trying to submit a form with 2 fields with the same name but different type. I can identify the correct field I want by the field type or the number. Whats the best way of setting the correct field without iterating through all the fields?
| [
"Here is the signature of set_value() method of HTMLForm class.\nset_value(value, name=None, type=None, kind=None,\n id=None, nr=None,by_label=False,\n # by_label is deprecated \n label=None)\n\nAs you can see, you could specify type parameter, useful in this case to select the proper fie... | [
0
] | [] | [] | [
"duplicates",
"forms",
"mechanize",
"python"
] | stackoverflow_0003639251_duplicates_forms_mechanize_python.txt |
Q:
Module name redefines built-in
I'm making a game in Python, and it makes sense to have one of my modules named 'map'. My preferred way of importing is to do this:
from mygame import map
As pylint is telling me, however, this is redefining a built-in. What's the common way of dealing with this? Here are the choices I can come up with:
1) Ignore the pylint warning since I don't use the built-in map anyway.
2) Change to:
import mygame
then reference as mygame.map throughout my code.
3) Rename my map module to something else (hexmap, gamemap, etc.)
I'm leaning towards (2) but I want to see what other people think.
A:
This is subjective; there's no right answer.
That said, for me 3 is the only sensible option. Really really don't do 1; overwriting builtins is almost never a good idea and in this case it's especially confusing. 2 is better, but I think there is still an expectation that any function called map performs some operation similar to that of the builtin.
Maybe mapping?
A:
Quoth PEP 20:
Explicit is better than implicit.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
mygame.map is more explicit than map. mygame.board or mygame.terrain is less ambiguous than mygame.map. Guessing if code is talking about __builtins__.map or mygame.map is frightful and will mostly be wrong.
A:
Options 2 or 3 would work, however I think it would be most understandable to rename map so that it can't be confused. That way, you can get the conciseness that referring to map instead of mygame.map gives you, but you won't have any problems with scope. Also, I think map is a somewhat undescriptive variable name, so it'd be better to give it a more specific name.
| Module name redefines built-in | I'm making a game in Python, and it makes sense to have one of my modules named 'map'. My preferred way of importing is to do this:
from mygame import map
As pylint is telling me, however, this is redefining a built-in. What's the common way of dealing with this? Here are the choices I can come up with:
1) Ignore the pylint warning since I don't use the built-in map anyway.
2) Change to:
import mygame
then reference as mygame.map throughout my code.
3) Rename my map module to something else (hexmap, gamemap, etc.)
I'm leaning towards (2) but I want to see what other people think.
| [
"This is subjective; there's no right answer.\nThat said, for me 3 is the only sensible option. Really really don't do 1; overwriting builtins is almost never a good idea and in this case it's especially confusing. 2 is better, but I think there is still an expectation that any function called map performs some ope... | [
4,
2,
1
] | [] | [] | [
"coding_style",
"conventions",
"naming_conventions",
"python"
] | stackoverflow_0003639511_coding_style_conventions_naming_conventions_python.txt |
Q:
Design pattern for multiple consumers and a single data source
I am designing a web interface to a certain hardware appliance that provides its own custom API. Said web interface can manage multiple appliances at once. The data is retrieved from appliance through polling with the custom API so it'd be preferable to make it asynchronous.
The most obvious thing is to have a poller thread that polls for data, saves into a process wide singleton with semaphores and then the web server threads will retrieve data from said singleton and show it. I'm not a huge fan of singletons or mashed together designs, so I was thinking of maybe separating the poller datasource from the web server, looping it back on the local interface and using something like XML-RPC to consume data.
The application need not be 'enterprisey' or scalable really since it'll at most be accessed by a couple people at a time, but I'd rather make it robust by not mixing two kinds of logic together. There's a current implementation in python using CherryPy and it's the biggest mishmash of terrible design I've ever seen. I feel that if I go with the most obvious design I'll just end up reimplementing the same horrible thing my own way.
A:
If you use Django and celery, you can create a Django project to be the web interface and a celery job to run in the background and poll. In that job, you can import your Django models so it can save the results of the polling very simply.
| Design pattern for multiple consumers and a single data source | I am designing a web interface to a certain hardware appliance that provides its own custom API. Said web interface can manage multiple appliances at once. The data is retrieved from appliance through polling with the custom API so it'd be preferable to make it asynchronous.
The most obvious thing is to have a poller thread that polls for data, saves into a process wide singleton with semaphores and then the web server threads will retrieve data from said singleton and show it. I'm not a huge fan of singletons or mashed together designs, so I was thinking of maybe separating the poller datasource from the web server, looping it back on the local interface and using something like XML-RPC to consume data.
The application need not be 'enterprisey' or scalable really since it'll at most be accessed by a couple people at a time, but I'd rather make it robust by not mixing two kinds of logic together. There's a current implementation in python using CherryPy and it's the biggest mishmash of terrible design I've ever seen. I feel that if I go with the most obvious design I'll just end up reimplementing the same horrible thing my own way.
| [
"If you use Django and celery, you can create a Django project to be the web interface and a celery job to run in the background and poll. In that job, you can import your Django models so it can save the results of the polling very simply.\n"
] | [
4
] | [] | [] | [
"architecture",
"cherrypy",
"design_patterns",
"python",
"rpc"
] | stackoverflow_0003639607_architecture_cherrypy_design_patterns_python_rpc.txt |
Q:
Trouble with variable. [Python]
I have this variable on the beginning of the code:
enterActive = False
and then, in the end of it, I have this part:
def onKeyboardEvent(event):
if event.KeyID == 113: # F2
doLogin()
enterActive = True
if event.KeyID == 13: # ENTER
if enterActive == True:
m_lclick()
return True
hookManager.KeyDown = onKeyboardEvent
hookManager.HookKeyboard()
pythoncom.PumpMessages()
and I get this error when I press enter first, and when I press F2 first:
UnboundLocalError: local variable 'enterActive' referenced before assignment
I know why this happens, but I don't know how can I solve it...
anyone?
A:
See Global variables in Python. Inside onKeyboardEvent, enterActive currently refers to a local variable, not the (global) variable you have defined outside the function. You need to put
global enterActive
at the beginning of the function to make enterActive refer to the global variable.
A:
Approach 1: Use a local variable.
def onKeyboardEvent(event):
enterActive = false
...
Approach 2: Explicitly declare that you are using the global variable enterActive.
def onKeyboardEvent(event):
global enterActive
...
Because you have the line enterActive = True within the functiononKeyboardEvent, any reference to enterActive within the function uses the local variable by default, not the global one. In your case, the local variable is not defined at the time of its use, hence the error.
A:
enterActive = False
def onKeyboardEvent(event):
global enterActive
...
A:
Maybe this is the answer:
Using global variables in a function other than the one that created them
You are writing to a global variable and have to state that you know
what you're doing by adding a "global enterActive" in the beginning of
your function:
def onKeyboardEvent(event):
global enterActive
if event.KeyID == 113: # F2
doLogin()
enterActive = True
if event.KeyID == 13: # ENTER
if enterActive == True:
m_lclick()
return True
A:
Maybe you are trying to declare enterActive in another function and you aren't using the global statement to make it global. Anywhere in a function where you declare the variable, add:
global enterActive
That will declare it as global inside the functions.
| Trouble with variable. [Python] | I have this variable on the beginning of the code:
enterActive = False
and then, in the end of it, I have this part:
def onKeyboardEvent(event):
if event.KeyID == 113: # F2
doLogin()
enterActive = True
if event.KeyID == 13: # ENTER
if enterActive == True:
m_lclick()
return True
hookManager.KeyDown = onKeyboardEvent
hookManager.HookKeyboard()
pythoncom.PumpMessages()
and I get this error when I press enter first, and when I press F2 first:
UnboundLocalError: local variable 'enterActive' referenced before assignment
I know why this happens, but I don't know how can I solve it...
anyone?
| [
"See Global variables in Python. Inside onKeyboardEvent, enterActive currently refers to a local variable, not the (global) variable you have defined outside the function. You need to put\nglobal enterActive\n\nat the beginning of the function to make enterActive refer to the global variable.\n",
"Approach 1: Use... | [
6,
2,
1,
0,
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0003639631_python_windows.txt |
Q:
Search by a property of a reference
I have the following models:
class Station(db.Model):
code = db.StringProperty(required=True)
name = db.StringProperty(required=True)
class Schedule(db.Model):
tripCode = db.StringProperty(required=True)
station = db.ReferenceProperty(Station, required=True)
arrivalTime = db.TimeProperty(required=True)
departureTime = db.TimeProperty(required=True)
How can I order programatically all the Schedules by Station's name?
Something like Schedule.all().order('station.name')
A:
You will to de-normalize your models or sort the results in memory:
Schedule.all().fetch(100).sort(key=lambda s: s.station.name)
(code not tested)
A:
After use sort i think you need to fetch all entities:
Schedule.all().fetch (100).sort(key=lambda s: s.station.name)
May be you can also use collection name.
But i think the jbochi answer is better :)
[x.schedule_set.get () for x in Station.all ().order ('name')]
| Search by a property of a reference | I have the following models:
class Station(db.Model):
code = db.StringProperty(required=True)
name = db.StringProperty(required=True)
class Schedule(db.Model):
tripCode = db.StringProperty(required=True)
station = db.ReferenceProperty(Station, required=True)
arrivalTime = db.TimeProperty(required=True)
departureTime = db.TimeProperty(required=True)
How can I order programatically all the Schedules by Station's name?
Something like Schedule.all().order('station.name')
| [
"You will to de-normalize your models or sort the results in memory:\nSchedule.all().fetch(100).sort(key=lambda s: s.station.name)\n\n(code not tested)\n",
"After use sort i think you need to fetch all entities:\nSchedule.all().fetch (100).sort(key=lambda s: s.station.name)\n\nMay be you can also use collection n... | [
0,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003638691_google_app_engine_python.txt |
Q:
Break a text file into chunks based on line like the string split operation?
I have text report files I need to "split()" like strings are split up into arrays.
So the file is like:
BOBO:12341234123412341234
1234123412341234123412341
123412341234
BOBO:12349087609812340-98
43690871234509875
45
BOBO:32498714235908713248
0987235
And I want to create 3 sub-files out of that splitting on lines that begin with "^BOBO:". I don't really want 3 physical files, I'd prefer 3 different file pointers.
A:
Perhaps use itertools.groupby:
import itertools
def bobo(x):
if x.startswith('BOBO:'):
bobo.count+=1
return bobo.count
bobo.count=0
with open('a') as f:
for key,grp in itertools.groupby(f,bobo):
print(key,list(grp))
yields:
(1, ['BOBO:12341234123412341234\n', '1234123412341234123412341\n', '123412341234\n'])
(2, ['BOBO:12349087609812340-98\n', '43690871234509875\n', '45\n', '\n'])
(3, ['BOBO:32498714235908713248\n', '0987235\n'])
Since you say you don't want physical files, the whole file must be able to fit in memory. In that case, to create file-like objects, use the cStringIO module:
import cStringIO
with open('a') as f:
file_handles=[]
for key,grp in itertools.groupby(f,bobo):
file_handles.append(cStringIO.StringIO(''.join(grp)))
file_handles will be a list of file-like objects, one for each "BOBO:" stanza.
A:
If you can deal with keeping them in memory to work with them something like this probably works:
subFileBlocks = []
with open('myReportFile.txt') as fh:
for line in fh:
if line.startswith('BOBO'):
subFileBlocks.append(line)
else:
subFileBlocks[-1] += line
At the end of that subFileBlocks should contain your sections as strings.
| Break a text file into chunks based on line like the string split operation? | I have text report files I need to "split()" like strings are split up into arrays.
So the file is like:
BOBO:12341234123412341234
1234123412341234123412341
123412341234
BOBO:12349087609812340-98
43690871234509875
45
BOBO:32498714235908713248
0987235
And I want to create 3 sub-files out of that splitting on lines that begin with "^BOBO:". I don't really want 3 physical files, I'd prefer 3 different file pointers.
| [
"Perhaps use itertools.groupby:\nimport itertools\n\ndef bobo(x): \n if x.startswith('BOBO:'):\n bobo.count+=1\n return bobo.count\nbobo.count=0\n\nwith open('a') as f:\n for key,grp in itertools.groupby(f,bobo):\n print(key,list(grp))\n\nyields:\n(1, ['BOBO:12341234123412341234\\n', '1234... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003639647_python.txt |
Q:
Does Lua support Decorators?
I come from a Python background and really like the power of Python Decorators.
Does Lua support Decorators?
I've read the following link but it's unclear to me: http://lua-users.org/wiki/DecoratorsAndDocstrings
UPDATE
Would you also mind given an example how how to implement it in Lua if it's possible.
A:
The "decorators" documented at the page you quote (and used for example in this one to add type-checking) have little to do with Python's oddly-named "decorator syntax" for a specific way to apply a higher-order function (HOF) -- rather, the decorators described and used in Lua's wiki are a Lua idiom to support an application of the Decorator Design Pattern to Lua functions (by holding "extra attributes" -- such as docstrings, typechecking functions, etc -- in separate global tables).
Lua does support HOFs (I'm not sure if you can re-bind a function name to the result of applying a HOF to the function, but you can easily, as the wiki pages show, use an anonymous "original function" and only bind a name to the HOF's result with that anon function as the arg).
Python's "decorator syntax" syntax sugar is nice (and, to my surprise, seems to have increased the use of HOFs by most Pythonistas by an order of magnitude!-), but there's nothing intrinsic or essential about them that you can't do in Lua (and Lua's anonymous functions run circle around Python's goofy, limited lambda anyway -- just like in Javascript, they have essentially the same power, and pretty much the same syntax, as a "normal" named function!-).
| Does Lua support Decorators? | I come from a Python background and really like the power of Python Decorators.
Does Lua support Decorators?
I've read the following link but it's unclear to me: http://lua-users.org/wiki/DecoratorsAndDocstrings
UPDATE
Would you also mind given an example how how to implement it in Lua if it's possible.
| [
"The \"decorators\" documented at the page you quote (and used for example in this one to add type-checking) have little to do with Python's oddly-named \"decorator syntax\" for a specific way to apply a higher-order function (HOF) -- rather, the decorators described and used in Lua's wiki are a Lua idiom to suppor... | [
10
] | [] | [] | [
"decorator",
"lua",
"programming_languages",
"python",
"syntax"
] | stackoverflow_0003640536_decorator_lua_programming_languages_python_syntax.txt |
Q:
Python, ctypes and mmap
I am wondering if it is possible for the ctypes package to interface with mmap.
Currently, my module allocates a buffer (with create_string_buffer) and then passes that using byref to my libraries mylib.read function. This, as the name suggests, reads data into the buffer. I then call file.write(buf.raw) to write the data to disk. My benchmarks, however, show this to be far from optimal (time spent in file.write is time better spent in mylib.read).
I am therefore interested in knowing if ctypes can interoperate with mmap. Given an mmap.mmap instance and an offset how can I get a pointer (c_void_p) into the address space?
A:
An mmap object "supports the writable buffer interface", therefore you can use the from_buffer class method, which all ctypes classes have, with the mmap instance as the argument, to create a ctypes object just like you want, i.e., sharing the memory (and therefore the underlying file) that the mmap instance has mapped. I imagine, in specific, that you'll want a suitable ctypes array.
A:
Be aware that the operating system is going to be doing readahead for read() anyway. You're going to be blocking either in read() or write()--one or the other will bottleneck the operation--but even though you're blocking in one, that doesn't mean the other isn't taking place for you behind the scenes. That's the job of every multitasking operating system.
If you use mmap for this, you're very likely making things more complicated for the OS--making it harder for it to determine that you're really just streaming data in and out, and making it more complicated for it to do read-ahead. It may still figure it out (operating systems are very good at this), but you're probably not helping.
The only benefit in principle is avoiding the cost of a memory copy, but it doesn't sound like that's your goal here (and unless profiling clearly says otherwise, I'd strongly doubt that would help performance).
| Python, ctypes and mmap | I am wondering if it is possible for the ctypes package to interface with mmap.
Currently, my module allocates a buffer (with create_string_buffer) and then passes that using byref to my libraries mylib.read function. This, as the name suggests, reads data into the buffer. I then call file.write(buf.raw) to write the data to disk. My benchmarks, however, show this to be far from optimal (time spent in file.write is time better spent in mylib.read).
I am therefore interested in knowing if ctypes can interoperate with mmap. Given an mmap.mmap instance and an offset how can I get a pointer (c_void_p) into the address space?
| [
"An mmap object \"supports the writable buffer interface\", therefore you can use the from_buffer class method, which all ctypes classes have, with the mmap instance as the argument, to create a ctypes object just like you want, i.e., sharing the memory (and therefore the underlying file) that the mmap instance has... | [
13,
1
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0003640092_ctypes_python.txt |
Q:
Help with if statement
I'm trying this part of my script and it work perfectly
if win32gui.GetCursorInfo()[1] == 65567:
but when I'm trying to add this
win32gui.GetCursorInfo()[2] == categoriesScreenPos[1]:
it stop working... why?
The categoriesScreenPos[1] is the same value (17,242) of the position of the cursor, but the if doesn't work...
Full if:
if win32gui.GetCursorInfo()[1] == 65567 and win32gui.GetCursorInfo()[2] == categoriesScreenPos[1]:
What I'm trying is to, when the cursor is in a specified position and has a specified icon, the if break a while.
ps: if I print the both commands like this
print categoriesScreenPos[1]
print win32gui.GetCursorInfo()[2]
they give me the same result!
edit: doesn't work because I have a break inside the if, and the while still continues... but only with the first if statement, worked perfectly.
I'm sorry...
Full part of the script:
while timer < timerMax:
timer = timer + 1
time.sleep(2)
m_move(*categoriesScreenPos[1])
time.sleep(2)
m_move(*loginScreenPos[0])
if win32gui.GetCursorInfo()[1] == 65567 and win32gui.GetCursorInfo()[2] == categoriesScreenPos[1]:
print '[' + time.strftime('%Y/%m/%d %H:%M:%S')+'] ' + 'Login Sucess'
break
if win32gui.GetCursorInfo()[1] == 65541:
time.sleep(0.2)
kbShell.SendKeys('{F2}')
print '[' + time.strftime('%Y/%m/%d %H:%M:%S')+'] ' + 'Login Failed'
break
A:
I think the m_move(*loginScreenPos[0]) causes the mouse coordinates to change (because it moves the mouse) and consequently so does win32gui.GetCursorInfo()[2] -- you say you printed it, but did you print it immediately after moving the mouse elsewhere?
| Help with if statement | I'm trying this part of my script and it work perfectly
if win32gui.GetCursorInfo()[1] == 65567:
but when I'm trying to add this
win32gui.GetCursorInfo()[2] == categoriesScreenPos[1]:
it stop working... why?
The categoriesScreenPos[1] is the same value (17,242) of the position of the cursor, but the if doesn't work...
Full if:
if win32gui.GetCursorInfo()[1] == 65567 and win32gui.GetCursorInfo()[2] == categoriesScreenPos[1]:
What I'm trying is to, when the cursor is in a specified position and has a specified icon, the if break a while.
ps: if I print the both commands like this
print categoriesScreenPos[1]
print win32gui.GetCursorInfo()[2]
they give me the same result!
edit: doesn't work because I have a break inside the if, and the while still continues... but only with the first if statement, worked perfectly.
I'm sorry...
Full part of the script:
while timer < timerMax:
timer = timer + 1
time.sleep(2)
m_move(*categoriesScreenPos[1])
time.sleep(2)
m_move(*loginScreenPos[0])
if win32gui.GetCursorInfo()[1] == 65567 and win32gui.GetCursorInfo()[2] == categoriesScreenPos[1]:
print '[' + time.strftime('%Y/%m/%d %H:%M:%S')+'] ' + 'Login Sucess'
break
if win32gui.GetCursorInfo()[1] == 65541:
time.sleep(0.2)
kbShell.SendKeys('{F2}')
print '[' + time.strftime('%Y/%m/%d %H:%M:%S')+'] ' + 'Login Failed'
break
| [
"I think the m_move(*loginScreenPos[0]) causes the mouse coordinates to change (because it moves the mouse) and consequently so does win32gui.GetCursorInfo()[2] -- you say you printed it, but did you print it immediately after moving the mouse elsewhere?\n"
] | [
1
] | [] | [] | [
"if_statement",
"python"
] | stackoverflow_0003640070_if_statement_python.txt |
Q:
django: trying to access my robots.txt: "TypeError at /robots.txt 'str' object is not callable"
Exception Type: TypeError at /robots.txt
Exception Value: 'str' object is not callable
What gives?
Views:
ROBOTS_PATH = os.path.join(CURRENT_PATH, 'robots.txt')
def robots(request):
""" view for robots.txt file """
return HttpResponse(open(ROBOTS_PATH).read(), 'text/plain')
Settings:
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__).decode('utf-8'))
URLs:
(r'^robots\.txt$', 'robots'),
A:
Try:
from appname.views import robots
(r'^robots\.txt$', robots),
Or:
(r'^robots\.txt$', 'projectname.appname.views.robots'),
Django can't figure out where your 'robots' function is.
| django: trying to access my robots.txt: "TypeError at /robots.txt 'str' object is not callable" | Exception Type: TypeError at /robots.txt
Exception Value: 'str' object is not callable
What gives?
Views:
ROBOTS_PATH = os.path.join(CURRENT_PATH, 'robots.txt')
def robots(request):
""" view for robots.txt file """
return HttpResponse(open(ROBOTS_PATH).read(), 'text/plain')
Settings:
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__).decode('utf-8'))
URLs:
(r'^robots\.txt$', 'robots'),
| [
"Try: \nfrom appname.views import robots\n(r'^robots\\.txt$', robots), \n\nOr:\n(r'^robots\\.txt$', 'projectname.appname.views.robots'),\n\nDjango can't figure out where your 'robots' function is. \n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003640478_django_python.txt |
Q:
In my MapperExtension.create_instance, how can I extract individual row data by column name?
I've got a query that returns a fair number of rows, and have found that
We wind up throwing away most of the associated ORM instances; and
building up those soon-to-be-thrown-away instances is pretty slow.
So I'd like to build only the instances that I need!
Unfortunately, I can't do this by simply restricting the query; I need to do a fair bit of "business logic" processing on each row before I can tell if I'll throw it out; I can't do this in SQL.
So I was thinking that I could use a MapperExtension to handle this: I'd subclass MapperExtension, and then override create_instance; that method would examine the row data, and either return EXT_CONTINUE if the data is worth building into an instance, or ... something else (I haven't yet decided what) otherwise.
Firstly, does this approach even make sense?
Secondly, if it does make sense, I haven't figured out how to find the data I need in the arguments that get passed to create_instance. I suspect it's in there somewhere, but it's hard to find ... instead of getting a row that directly corresponds to the particular class I'm interested in, I'm getting a row that corresponds to the query that SQLalchemy generated, which happens to be a somewhat complex join between (say) tables A, B, and C.
The problem is that I don't know which elements of the row correspond to the fields in my ORM class: I want to be able to pluck out (e.g.) A.id, B.weight, and C.height.
I assume that somewhere inside the mapper, selectcontext, or class_ arguments is some sort of mapping between columns of my table, and offsets into the row. But I haven't yet found just the right thing. I've come tantalizingly close, though. For example, I've found that selectcontext.statement.columns contains the names of the generated columns ... but not those of the table I'm interested in. For example:
Column(u'A_id', UUID(), ...
...
Column(u'%(32285328 B)s_weight, MSInt(), ...
...
Column(u'%(32285999 C)s_height', MSInt(), ...
So: how do I map column names like C.height to offsets into the
row?
A:
The row accepts Column objects as indexes:
row[MyClass.some_element.__clause_element__()]
but that will only get you as far as the classes and aliased() constructs you have access to on the outside. Its very likely that would be all you'd need for that part of the issue (even though ultimately the idea won't work, read on).
If your statement has had subqueries wrapped around it, from using things like from_self() or join() to a polymorphic target, the create_instance() method doesn't give you access to the translation functions you'd need to accomplish that.
If you're trying to get at rows that are linked to an eagerload(), that's totally not something you should be doing. eagerload() is about optimizing the load of collections. If you want your query to join between two tables and you're looking to filter on the joined table, use join().
But above all, create_instance() is from version 0.1 of SQLAlchemy and I doubt anyone uses it for anything, and it has no capability to say, "skip this row". It has to return something or the mapper will create the instance on its own. So no matter how well you can interpret the row, there's no hook for what you want to do here.
If i really wanted to do such a thing, it would likely be easier to monkeypatch the "fetchall()" method of the returned ResultProxy to filter rows, and send it to Query.instances(). Any result can be sent to this method. Although, if the Query has done translations and such on the mapped selectables, it would need the original QueryContext as well to know how to translate. But this is nothing I'd be bothering with either.
Overall, if speed is so critical of an issue throughout all of this that creating the object is that big of a difference, I'd make it so that I don't need the mapped objects at all for the whole operation, or I'd use caching, or generate the objects I need manually from a result set. I also would make sure that I have access to all the targeted columns in the selectable I'm using so I can re-fetch from result rows, which means I either don't use automatic-subquery/alias generation functions in the ORM, or I use the expression language directly (if you're really hungry for speed and are in the mood to write large tracts of optimizing code, you should probably just be using the expression language).
So the real questions you have to ask here are:
Have you verified that the real difference in speed is creating the object from the row. I.e. not fetching the row, or fetching its columns, etc.
Does the row just have some expensive columns that you don't need? Have you looked into deferred() ?
What are these business rules and why cant they be done in SQL, as stored procedures, etc.
How many thousands of rows are you really skipping here, that its so "slow" to not "skip" them
Have you investigated techniques for having the objects already present, like in-memory caches, preloads, etc. For many scenarios, this fits the bill.
None of this works, and you really want to hack up some home-rolled optimization code. So why not use the SQL expression language directly? If ultimately you're just dealing with a view layer, result rows are quite friendly (they allow "attribute" style access and such), or build some quick "generate an object" routine from it. The ORM presents a very specific use case of the SQL expression language, and if you really need something much more lightweight than it, you're better off skipping it.
| In my MapperExtension.create_instance, how can I extract individual row data by column name? | I've got a query that returns a fair number of rows, and have found that
We wind up throwing away most of the associated ORM instances; and
building up those soon-to-be-thrown-away instances is pretty slow.
So I'd like to build only the instances that I need!
Unfortunately, I can't do this by simply restricting the query; I need to do a fair bit of "business logic" processing on each row before I can tell if I'll throw it out; I can't do this in SQL.
So I was thinking that I could use a MapperExtension to handle this: I'd subclass MapperExtension, and then override create_instance; that method would examine the row data, and either return EXT_CONTINUE if the data is worth building into an instance, or ... something else (I haven't yet decided what) otherwise.
Firstly, does this approach even make sense?
Secondly, if it does make sense, I haven't figured out how to find the data I need in the arguments that get passed to create_instance. I suspect it's in there somewhere, but it's hard to find ... instead of getting a row that directly corresponds to the particular class I'm interested in, I'm getting a row that corresponds to the query that SQLalchemy generated, which happens to be a somewhat complex join between (say) tables A, B, and C.
The problem is that I don't know which elements of the row correspond to the fields in my ORM class: I want to be able to pluck out (e.g.) A.id, B.weight, and C.height.
I assume that somewhere inside the mapper, selectcontext, or class_ arguments is some sort of mapping between columns of my table, and offsets into the row. But I haven't yet found just the right thing. I've come tantalizingly close, though. For example, I've found that selectcontext.statement.columns contains the names of the generated columns ... but not those of the table I'm interested in. For example:
Column(u'A_id', UUID(), ...
...
Column(u'%(32285328 B)s_weight, MSInt(), ...
...
Column(u'%(32285999 C)s_height', MSInt(), ...
So: how do I map column names like C.height to offsets into the
row?
| [
"The row accepts Column objects as indexes:\nrow[MyClass.some_element.__clause_element__()]\n\nbut that will only get you as far as the classes and aliased() constructs you have access to on the outside. Its very likely that would be all you'd need for that part of the issue (even though ultimately the idea won't... | [
1
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0003571104_python_sqlalchemy.txt |
Q:
Alternative to Passing Global Variables Around to Classes and Functions
I'm new to python, and I've been reading that using global to pass variables to other functions is considered noobie, as well as a bad practice. I would like to move away from using global variables, but I'm not sure what to do instead.
Right now I have a UI I've created in wxPython as its own separate class, and I have another class that loads settings from a .ini file. Since the settings in the UI should match those in the .ini, how do I pass around those values? I could using something like: Settings = Settings() and then define the variables as something like self.settings1, but then I would have to make Settings a global variable to pass it to my UI class (which it wouldn't be if I assign in it main()).
So what is the correct and pythonic way to pass around these variables?
Edit: Here is the code that I'm working with, and I'm trying to get it to work like Alex Martelli's example. The following code is saved in Settings.py:
import ConfigParser
class _Settings():
@property
def enableautodownload(self): return self._enableautodownload
def __init__(self):
self.config = ConfigParser.ConfigParser()
self.config.readfp(open('settings.ini'))
self._enableautodownload=self.config.getboolean('DLSettings', 'enableautodownload')
settings = _Settings()
Whenever I try to refer to Settings.settings.enableautodownload from another file I get: AttributeError: 'module' object has no attribute 'settings'. What am I doing wrong?
Edit 2: Never mind about the issue, I retyped the code and it works now, so it must have been a simple spelling or syntax error.
A:
The alternatives to global variables are many -- mostly:
explicit arguments to functions, classes called to create one of their instance, etc (this is usually the clearest, since it makes the dependency most explicit, when feasible and not too repetitious);
instance variables of an object, when the functions that need access to those values are methods on that same object (that's OK too, and a reasonable way to use OOP);
"accessor functions" that provide the values (or an object which has attributes or properties for the values).
Each of these (esp. the first and third ones) is particularly useful for values whose names must not be re-bound by all and sundry, but only accessed. The really big problem with global is that it provides a "covert communication channel" (not in the cryptographic sense, but in the literal one: apparently separate functions can actually be depending on each other, influencing each other, via global values that are not "obvious" from the functions' signatures -- this makes the code hard to test, debug, maintain, and understand).
For your specific problem, if you never use the global statement, but rather access the settings in a "read-only" way from everywhere (and you can ensure that more fully by making said object's attributes be read-only properties!), then having the "read-only" accesses be performed on a single, made-once-then-not-changed, module-level instance, is not too bad. I.e., in some module foo.py:
class _Settings(object):
@property
def one(self): return self._one
@property
def two(self): return self._two
def __init__(self, one, two):
self._one, self._two = one, two
settings = _Settings(23, 45)
and from everywhere else, import foo then just access foo.settings.one and foo.settings.two as needed. Note that I've named the class with a single leading underscore (just like the two instance attributes that underlie the read-only properties) to suggest that it's not meant to be used from "outside" the module -- only the settings object is supposed to be (there's no enforcement -- but any user violating such requested privacy is most obviously the only party responsible for whatever mayhem may ensue;-).
| Alternative to Passing Global Variables Around to Classes and Functions | I'm new to python, and I've been reading that using global to pass variables to other functions is considered noobie, as well as a bad practice. I would like to move away from using global variables, but I'm not sure what to do instead.
Right now I have a UI I've created in wxPython as its own separate class, and I have another class that loads settings from a .ini file. Since the settings in the UI should match those in the .ini, how do I pass around those values? I could using something like: Settings = Settings() and then define the variables as something like self.settings1, but then I would have to make Settings a global variable to pass it to my UI class (which it wouldn't be if I assign in it main()).
So what is the correct and pythonic way to pass around these variables?
Edit: Here is the code that I'm working with, and I'm trying to get it to work like Alex Martelli's example. The following code is saved in Settings.py:
import ConfigParser
class _Settings():
@property
def enableautodownload(self): return self._enableautodownload
def __init__(self):
self.config = ConfigParser.ConfigParser()
self.config.readfp(open('settings.ini'))
self._enableautodownload=self.config.getboolean('DLSettings', 'enableautodownload')
settings = _Settings()
Whenever I try to refer to Settings.settings.enableautodownload from another file I get: AttributeError: 'module' object has no attribute 'settings'. What am I doing wrong?
Edit 2: Never mind about the issue, I retyped the code and it works now, so it must have been a simple spelling or syntax error.
| [
"The alternatives to global variables are many -- mostly:\n\nexplicit arguments to functions, classes called to create one of their instance, etc (this is usually the clearest, since it makes the dependency most explicit, when feasible and not too repetitious);\ninstance variables of an object, when the functions t... | [
5
] | [] | [] | [
"python"
] | stackoverflow_0003640700_python.txt |
Q:
Computing greatest common denominator in python
If you have a list of integers in python, say L = [4,8,12,24], how can you compute their greatest common denominator/divisor (4 in this case)?
A:
One way to do it is:
import fractions
def gcd(L):
return reduce(fractions.gcd, L)
print gcd([4,8,12,24])
| Computing greatest common denominator in python | If you have a list of integers in python, say L = [4,8,12,24], how can you compute their greatest common denominator/divisor (4 in this case)?
| [
"One way to do it is:\nimport fractions\n\ndef gcd(L):\n return reduce(fractions.gcd, L)\n\nprint gcd([4,8,12,24])\n\n"
] | [
26
] | [] | [] | [
"division",
"integer",
"python"
] | stackoverflow_0003640955_division_integer_python.txt |
Q:
How to write a common get_by_id() method for all kinds of models in Sqlalchemy?
I'm using pylons with sqlalchemy. I have several models, and found myself wrote such code again and again:
question = Session.query(Question).filter_by(id=question_id).one()
answer = Session.query(Answer).fileter_by(id=answer_id).one()
...
user = Session.query(User).filter_by(id=user_id).one()
Since the models are all extend class Base, is there any way to define a common get_by_id() method?
So I can use it as:
quesiton = Question.get_by_id(question_id)
answer = Answer.get_by_id(answer_id)
...
user = User.get_by_id(user_id)
A:
If id is your primary key column, you just do:
session.query(Foo).get(id)
which has the advantage of not querying the database if that instance is already in the session.
A:
Unfortunately, SQLAlchemy doesn't allow you to subclass Base without a corresponding table declaration. You could define a mixin class with get_by_id as a classmethod, but then you'd need to specify it for each class.
A quicker-and-dirtier solution is to just monkey-patch it into Base:
def get_by_id(cls, id, session=session):
return session.query(cls).filter_by(id=id).one()
Base.get_by_id = classmethod(get_by_id)
This assumes you've got a session object available at definition-time, otherwise you'll need to pass it as an argument each time.
A:
class Base(object):
@classmethod
def get_by_id(cls, session, id):
q = session.query(cls).filter_by(id=id)
return q.one()
Question.get_by_id(Session, question_id)
| How to write a common get_by_id() method for all kinds of models in Sqlalchemy? | I'm using pylons with sqlalchemy. I have several models, and found myself wrote such code again and again:
question = Session.query(Question).filter_by(id=question_id).one()
answer = Session.query(Answer).fileter_by(id=answer_id).one()
...
user = Session.query(User).filter_by(id=user_id).one()
Since the models are all extend class Base, is there any way to define a common get_by_id() method?
So I can use it as:
quesiton = Question.get_by_id(question_id)
answer = Answer.get_by_id(answer_id)
...
user = User.get_by_id(user_id)
| [
"If id is your primary key column, you just do:\nsession.query(Foo).get(id)\n\nwhich has the advantage of not querying the database if that instance is already in the session.\n",
"Unfortunately, SQLAlchemy doesn't allow you to subclass Base without a corresponding table declaration. You could define a mixin clas... | [
3,
2,
0
] | [] | [] | [
"genericdao",
"python",
"sqlalchemy"
] | stackoverflow_0003638094_genericdao_python_sqlalchemy.txt |
Q:
Python: using downloaded modules
I am new to Python and mostly used my own code. But so now I downloaded a package that I need for some problem I have.
Example structure:
root\
externals\
__init__.py
cowfactory\
__init__.py
cow.py
milk.py
kittens.py
Now the cowfactory's __init__.py does from cowfactory import cow. This gives an import error.
I could fix it and change the import statement to from externals.cowfactory import cow but something tells me that there is an easier way since it's not very practical.
An other fix could be to put the cowfactory package in the root of my project but that's not very tidy either.
I think I have to do something with the __init__.py file in the externals directory but I am not sure what.
A:
Inside the cowfactory package, relative imports should be used such as from . import cow. The __init__.py file in externals is not necessary. Assuming that your project lies in root\ and cowfactory is the external package you downloaded, you can do it in two different ways:
Install the external module
External Python packages usually come with a file "setup.py" that allows you to install it. On Windows, it would be the command "setup.py bdist_wininst" and you get a EXE installer in the "dist" directory (if it builds correctly). Use that installer and the package will be installed in the Python installation directory. Afterwards, you can simply do an import cowfactory just like you would do import os.
If you have pip or easy_install installed: Many external packages can be installed with them (pip even allows easy uninstallation).
Use PYTHONPATH for development
If you want to keep all dependencies together in your project directory, then keep all external packages in the externals\ folder and add the folder to the PYTHONPATH. If you're using the command line, you can create a batch file containing something like
set PYTHONPATH=%PYTHONPATH%:externals
yourprogram.py
I'm actually doing something similar, but using PyDev+Eclipse. There, you can change the "Run configurations" to include the environment variable PYTHONPATH with the value "externals". After the environment variable is set, you can simply import cowfactory in your own modules. Note how that is better than from external import cowfactory because in the latter case, it wouldn't work anymore once you install your project (or you'd have to install all external dependencies as a package called "external" which is a bad idea).
Same solutions of course apply to Linux, as well, but with different commands.
A:
generally, you would use easy_install our pip to install it for you in the appropriate directory. There is a site-packages directory on windows where you can put the package if you can't use easy_install for some reason. On ubuntu, it's /usr/lib/pythonX.Y/dist-packages. Google for your particular system. Or you can put it anywhere on your PYTHONPATH environment variable.
As a general rule, it's good to not put third party libs in your programs directory structure (although there are differing opinions on this vis a vis source control). This keeps your directory structure as minimalist as possible.
A:
The easiest way is to use the enviroment variable $PYTHONPATH. You set it before running your scripts as follows:
export $PYTHONPATH=$PYTHONPATH:/root/externals/
You can add as many folders as you want (provided their separate by :) and python will look in all those folders when importing.
| Python: using downloaded modules | I am new to Python and mostly used my own code. But so now I downloaded a package that I need for some problem I have.
Example structure:
root\
externals\
__init__.py
cowfactory\
__init__.py
cow.py
milk.py
kittens.py
Now the cowfactory's __init__.py does from cowfactory import cow. This gives an import error.
I could fix it and change the import statement to from externals.cowfactory import cow but something tells me that there is an easier way since it's not very practical.
An other fix could be to put the cowfactory package in the root of my project but that's not very tidy either.
I think I have to do something with the __init__.py file in the externals directory but I am not sure what.
| [
"Inside the cowfactory package, relative imports should be used such as from . import cow. The __init__.py file in externals is not necessary. Assuming that your project lies in root\\ and cowfactory is the external package you downloaded, you can do it in two different ways:\n\nInstall the external module\nExterna... | [
7,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003641322_python.txt |
Q:
What is necessary to use Win32 extensions with Portable Python
I installed Portable Python in an USB drive and it is working but I cannot make it import Win32 extensions.
A:
Which version are you using? What is the error?
If you are using PP 1.1 based on 2.6.1, there is a known bug that prevents import of pythoncom and there is also a workaround to fix it:
http://groups.google.com/group/portablepython/browse_frm/thread/acfacb783bc39cb7
| What is necessary to use Win32 extensions with Portable Python | I installed Portable Python in an USB drive and it is working but I cannot make it import Win32 extensions.
| [
"Which version are you using? What is the error?\nIf you are using PP 1.1 based on 2.6.1, there is a known bug that prevents import of pythoncom and there is also a workaround to fix it:\nhttp://groups.google.com/group/portablepython/browse_frm/thread/acfacb783bc39cb7\n"
] | [
1
] | [] | [] | [
"portable_python",
"python"
] | stackoverflow_0003639041_portable_python_python.txt |
Q:
Postfix hangs when sending email
If I try to send an email as follows, the process hangs and nothing happens:
>>> from django.core.management import setup_environ
>>> from cube import settings
>>> setup_environ(settings)
'cube'
>>> from django.core.mail import send_mail
>>> send_mail('Subject', 'Message', 'sender@domain.com', ['recepient@domain.com'], fail_silently=False)
However, doing telnet to port 25 works just fine
$ telnet localhost 25
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
^]
telnet>
and here's this just in case
$ netstat -a | grep :smtp
tcp 0 0 *:smtp *:* LISTEN
tcp 0 0 localhost:smtp localhost:44932 ESTABLISHED
tcp 0 0 localhost:44932 localhost:smtp ESTABLISHED
tcp 0 0 localhost:smtp localhost:60964 ESTABLISHED
tcp 0 0 localhost:60964 localhost:smtp ESTABLISHED
tcp 0 0 localhost:37247 localhost:smtp FIN_WAIT2
tcp 1 0 localhost:smtp localhost:37247 CLOSE_WAIT
tcp 9 0 localhost:smtp localhost:37245 CLOSE_WAIT
I run Ubuntu 10.04 and Python 2.6.5
I don't know where to look next to figure out what's wrong. Please help me. Thank you.
A:
Your mail server isn't working fine. When you connect to it using telnet, you should see a welcome message along the lines of:
220 your.server.name ESMTP Postfix
(You can check the greeting that you should be seeing by running postconf smtpd_banner.)
You don't get that, so the mail server isn't running properly. send_mail is probably hanging waiting for that initial message.
Restart Postfix, and look in the /var/log/mail.* log files; there may be a clue in there as to why it's not working.
| Postfix hangs when sending email | If I try to send an email as follows, the process hangs and nothing happens:
>>> from django.core.management import setup_environ
>>> from cube import settings
>>> setup_environ(settings)
'cube'
>>> from django.core.mail import send_mail
>>> send_mail('Subject', 'Message', 'sender@domain.com', ['recepient@domain.com'], fail_silently=False)
However, doing telnet to port 25 works just fine
$ telnet localhost 25
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
^]
telnet>
and here's this just in case
$ netstat -a | grep :smtp
tcp 0 0 *:smtp *:* LISTEN
tcp 0 0 localhost:smtp localhost:44932 ESTABLISHED
tcp 0 0 localhost:44932 localhost:smtp ESTABLISHED
tcp 0 0 localhost:smtp localhost:60964 ESTABLISHED
tcp 0 0 localhost:60964 localhost:smtp ESTABLISHED
tcp 0 0 localhost:37247 localhost:smtp FIN_WAIT2
tcp 1 0 localhost:smtp localhost:37247 CLOSE_WAIT
tcp 9 0 localhost:smtp localhost:37245 CLOSE_WAIT
I run Ubuntu 10.04 and Python 2.6.5
I don't know where to look next to figure out what's wrong. Please help me. Thank you.
| [
"Your mail server isn't working fine. When you connect to it using telnet, you should see a welcome message along the lines of:\n220 your.server.name ESMTP Postfix\n\n(You can check the greeting that you should be seeing by running postconf smtpd_banner.)\nYou don't get that, so the mail server isn't running proper... | [
11
] | [] | [] | [
"django",
"postfix_mta",
"python",
"smtp",
"ubuntu_10.04"
] | stackoverflow_0003641936_django_postfix_mta_python_smtp_ubuntu_10.04.txt |
Q:
Automatic spam filtering or flagging for Django or Python?
I'm working on a Django-based site that consists mostly of user-
generated content: reviews, comments, tweet-like posts, etc.
I'm concerned about spam. Are there any spam filters available for
Django/Python? If not, what types of algorithms can be used for automatic spam
filtering or flagging?
On a more general note, does anyone know how do major sites like
Amazon and Yelp prevent spams in their user-submitted reviews?
A:
Take a look at SO question 915204. Jason Baker recommends using the Akismet Python API, which he states is what WordPress uses to stop spam. From the Akismet Python API website:
Akismet is a web service for recognising spam comments.
Also, Patrick Beeson has a blog entry on how to use Akismet to stop spam on a Django blog that might be relevant to your application.
A:
SpamBayes comes to mind.
| Automatic spam filtering or flagging for Django or Python? | I'm working on a Django-based site that consists mostly of user-
generated content: reviews, comments, tweet-like posts, etc.
I'm concerned about spam. Are there any spam filters available for
Django/Python? If not, what types of algorithms can be used for automatic spam
filtering or flagging?
On a more general note, does anyone know how do major sites like
Amazon and Yelp prevent spams in their user-submitted reviews?
| [
"Take a look at SO question 915204. Jason Baker recommends using the Akismet Python API, which he states is what WordPress uses to stop spam. From the Akismet Python API website:\n\nAkismet is a web service for recognising spam comments.\n\nAlso, Patrick Beeson has a blog entry on how to use Akismet to stop spam on... | [
2,
1
] | [] | [] | [
"django",
"python",
"spam",
"spam_prevention"
] | stackoverflow_0003641042_django_python_spam_spam_prevention.txt |
Q:
Django "for" loop and python dictionary problems
I'm having a couple of issues getting django templating for loop tag to go through this dictionary:
It is definitely being passed to the page ok as if I just do:
{% for event in events %}
{{ event }}
{% endfor %}
it writes 1,2,3 but when I try and do {{ event.start }} it just doesn't output anything...
evs = {
"1": {
'start': '8:00:00',
'end': '9:00:00',
'name': 'test',
'description': 'test',
'image_url': 'http://test',
'channel_url': 'http://test',
},
"2": {
'start': '8:00:00',
'end': '9:00:00',
'name': 'test',
'description': 'test',
'image_url': 'http://test',
'channel_url': 'http://test',
},
"3": {
'start': '8:00:00',
'end': '9:00:00',
'name': 'test',
'description': 'test',
'image_url': 'http://test',
'channel_url': 'http://test',
}
}
And this is my django code in the template:
{% for event in events %}
{{ event.end }}
{{ event.name }}
{{ event.description }}
{{ event.image_url }}
{{ event.channel_url }}
{% endfor %}
Any help would be really appreciated!
Thanks
A:
If you are just iterating over events you are just iterating over the dictonary's keys; you need to iterate over the dictionary's values: {% for event in events.values %}!
A:
Well, in your case, event is the always the key of one entry (which is a string), not the object itself, so event.start cannot work.
Have look at the documentation. You could do:
{% for key, event in events.items %}
{{ event.end }}
{{ event.name }}
{{ event.description }}
{{ event.image_url }}
{{ event.channel_url }}
{% endfor %}
| Django "for" loop and python dictionary problems | I'm having a couple of issues getting django templating for loop tag to go through this dictionary:
It is definitely being passed to the page ok as if I just do:
{% for event in events %}
{{ event }}
{% endfor %}
it writes 1,2,3 but when I try and do {{ event.start }} it just doesn't output anything...
evs = {
"1": {
'start': '8:00:00',
'end': '9:00:00',
'name': 'test',
'description': 'test',
'image_url': 'http://test',
'channel_url': 'http://test',
},
"2": {
'start': '8:00:00',
'end': '9:00:00',
'name': 'test',
'description': 'test',
'image_url': 'http://test',
'channel_url': 'http://test',
},
"3": {
'start': '8:00:00',
'end': '9:00:00',
'name': 'test',
'description': 'test',
'image_url': 'http://test',
'channel_url': 'http://test',
}
}
And this is my django code in the template:
{% for event in events %}
{{ event.end }}
{{ event.name }}
{{ event.description }}
{{ event.image_url }}
{{ event.channel_url }}
{% endfor %}
Any help would be really appreciated!
Thanks
| [
"If you are just iterating over events you are just iterating over the dictonary's keys; you need to iterate over the dictionary's values: {% for event in events.values %}!\n",
"Well, in your case, event is the always the key of one entry (which is a string), not the object itself, so event.start cannot work.\nHa... | [
6,
5
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003642026_django_python.txt |
Q:
Is there a script to manage/search python snippets which understands python code like nullege.com?
I have a folder full of python snippets and want to search it in a more intelligent way than grep. Is there already a script which parses python snippets to AST and lets you search it, like http://nullege.com?
For example, if you have the following code:
class InspectionFrame(wx.Frame):
def SaveSettings(self, config):
w, h = self.GetSize()
you should be able to search for wx.Frame.GetSize.
A:
To my knowledge, ctags is a classic tool for such a task. As of now, python support in exuberant ctags is lacking, but some work have been done last year: http://ctags.sourceforge.net/news.html.
Now indexing of classes, functions, class members, variables and imports are supported.
A:
Your idea is awesome, I'd love to see that available. FFR, this won't do what you want but it's way better than for grep for code searching: ack, it's "better than grep".
| Is there a script to manage/search python snippets which understands python code like nullege.com? | I have a folder full of python snippets and want to search it in a more intelligent way than grep. Is there already a script which parses python snippets to AST and lets you search it, like http://nullege.com?
For example, if you have the following code:
class InspectionFrame(wx.Frame):
def SaveSettings(self, config):
w, h = self.GetSize()
you should be able to search for wx.Frame.GetSize.
| [
"To my knowledge, ctags is a classic tool for such a task. As of now, python support in exuberant ctags is lacking, but some work have been done last year: http://ctags.sourceforge.net/news.html.\nNow indexing of classes, functions, class members, variables and imports are supported.\n",
"Your idea is awesome, I'... | [
2,
1
] | [] | [] | [
"code_snippets",
"python",
"search"
] | stackoverflow_0003599096_code_snippets_python_search.txt |
Q:
How to get byte offset in a file in python
I am making a inverted index using hadoop and python.
I want to know how can I include the byte offset of a line/word in python.
I need something like this
hello hello.txt@1124
I need the locations for making a full inverted index.
Please help.
A:
Like this?
file.tell()
Return the file’s current position, like stdio's ftell().
http://docs.python.org/library/stdtypes.html#file-objects
Unfortunately tell() does not function since OP is using stdin instead of a file. But it is not hard to build a wrapper around it to give what you need.
class file_with_pos(object):
def __init__(self, fp):
self.fp = fp
self.pos = 0
def read(self, *args):
data = self.fp.read(*args)
self.pos += len(data)
return data
def tell(self):
return self.pos
Then you can use this instead:
fp = file_with_pos(sys.stdin)
| How to get byte offset in a file in python | I am making a inverted index using hadoop and python.
I want to know how can I include the byte offset of a line/word in python.
I need something like this
hello hello.txt@1124
I need the locations for making a full inverted index.
Please help.
| [
"Like this?\nfile.tell()\n\nReturn the file’s current position, like stdio's ftell().\nhttp://docs.python.org/library/stdtypes.html#file-objects\nUnfortunately tell() does not function since OP is using stdin instead of a file. But it is not hard to build a wrapper around it to give what you need.\nclass file_with_... | [
12
] | [] | [] | [
"inverted_index",
"python"
] | stackoverflow_0003642088_inverted_index_python.txt |
Q:
Take first successful match from a batch of regexes
I'm trying to extract set of data from a string that can match one of three patterns. I have a list of compiled regexes. I want to run through them (in order) and go with the first match.
regexes = [
compiled_regex_1,
compiled_regex_2,
compiled_regex_3,
]
m = None
for reg in regexes:
m = reg.match(name)
if m: break
if not m:
print 'ARGL NOTHING MATCHES THIS!!!'
This should work (haven't tested yet) but it's pretty fugly. Is there a better way of boiling down a loop that breaks when it succeeds or explodes when it doesn't?
There might be something specific to re that I don't know about that allows you to test multiple patterns too.
A:
You can use the else clause of the for loop:
for reg in regexes:
m = reg.match(name)
if m: break
else:
print 'ARGL NOTHING MATCHES THIS!!!'
A:
If you just want to know if any of the regex match then you could use the builtin any function:
if any(reg.match(name) for reg in regexes):
....
however this will not tell you which regex matched.
Alternatively you can combine multiple patterns into a single regex with |:
regex = re.compile(r"(regex1)|(regex2)|...")
Again this will not tell you which regex matched, but you will have a match object that you can use for further information. For example you can find out which of the regex succeeded from the group that is not None:
>>> match = re.match("(a)|(b)|(c)|(d)", "c")
>>> match.groups()
(None, None, 'c', None)
However this can get complicated however if any of the sub-regex have groups in them as well, since the numbering will be changed.
This is probably faster than matching each regex individually since the regex engine has more scope for optimising the regex.
A:
Since you have a finite set in this case, you could use short ciruit evaluation:
m = compiled_regex_1.match(name) or
compiled_regex_2.match(name) or
compiled_regex_3.match(name) or
print("ARGHHHH!")
A:
In Python 2.6 or better:
import itertools as it
m = next(it.ifilter(None, (r.match(name) for r in regexes)), None)
The ifilter call could be made into a genexp, but only a bit awkwardly, i.e., with the usual trick for name binding in a genexp (aka the "phantom nested for clause idiom"):
m = next((m for r in regexes for m in (r.match(name),) if m), None)
but itertools is generally preferable where applicable.
The bit needing 2.6 is the next built-in, which lets you specify a default value if the iterator is exhausted. If you have to simulate it in 2.5 or earlier,
def next(itr, deft):
try: return itr.next()
except StopIteration: return deft
A:
I use something like Dave Kirby suggested, but add named groups to the regexps, so that I know which one matched.
regexps = {
'first': r'...',
'second': r'...',
}
compiled = re.compile('|'.join('(?P<%s>%s)' % item for item in regexps.iteritems()))
match = compiled.match(my_string)
print match.lastgroup
A:
Eric is in better track in taking bigger picture of what OP is aiming, I would use if else though. I would also think that using print function in or expression is little questionable. +1 for Nathon of correcting OP to use proper else statement.
Then my alternative:
# alternative to any builtin that returns useful result,
# the first considered True value
def first(seq):
for item in seq:
if item: return item
regexes = [
compiled_regex_1,
compiled_regex_2,
compiled_regex_3,
]
m = first(reg.match(name) for reg in regexes)
print(m if m else 'ARGL NOTHING MATCHES THIS!!!')
| Take first successful match from a batch of regexes | I'm trying to extract set of data from a string that can match one of three patterns. I have a list of compiled regexes. I want to run through them (in order) and go with the first match.
regexes = [
compiled_regex_1,
compiled_regex_2,
compiled_regex_3,
]
m = None
for reg in regexes:
m = reg.match(name)
if m: break
if not m:
print 'ARGL NOTHING MATCHES THIS!!!'
This should work (haven't tested yet) but it's pretty fugly. Is there a better way of boiling down a loop that breaks when it succeeds or explodes when it doesn't?
There might be something specific to re that I don't know about that allows you to test multiple patterns too.
| [
"You can use the else clause of the for loop:\nfor reg in regexes:\n m = reg.match(name)\n if m: break\nelse:\n print 'ARGL NOTHING MATCHES THIS!!!'\n\n",
"If you just want to know if any of the regex match then you could use the builtin any function:\nif any(reg.match(name) for reg in regexes):\n ..... | [
6,
2,
1,
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003642621_python_regex.txt |
Q:
Is this webpage-logging-in Python script correct?
Is this Python script correct?
import urllib, urllib2, cookielib
username = 'myuser'
password = 'mypassword'
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
resp.read()
I found this script HERE.It is meant to login to a webpage first, retrieve the cookies, store them and use them in order to open some other page in the same website. I want to login in this way to my eBay account (the URL is https://signin.ebay.com/ws/eBayISAPI.dll?SignIn ) and then go to my inbox on my eBay account (the URL is http://my.ebay.com/ws/eBayISAPI.dll?MyEbay&gbh=1) .
So, here are the values that I need to use in this script:
First (Sing-in) URL: https://signin.ebay.com/ws/eBayISAPI.dll?SignIn
Second URL: http://my.ebay.com/ws/eBayISAPI.dll?MyEbay&gbh=1
My login name on eBay: tryinghard
My password on eBay: gettingsomewhere
With all these new values the above script must look this way:
import urllib, urllib2, cookielib
username = 'tryinghard'
password = 'gettingsomewhere'
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open(https://signin.ebay.com/ws/eBayISAPI.dll?SignIn', login_data)
resp = opener.open(http://my.ebay.com/ws/eBayISAPI.dll?MyEbay&gbh=1')
resp.read()
Is it correct? I am especially suspicious about the login_data = line (the fourth one from bottom), why is it a j_password there instead of just password?
I tried this script with all these values and it didn't work. Does anybody know why it doesn't work in my case?
I've already learned how to log in to my eBay account and then check some other pages there by means of running a python script that is using twill as an external module, but that was only successful when I ran that script from the command prompt or from the Python shell. It wasn't successful when I tried running that script by means of "Google App Engine Software Development Kit" that I had downloaded from "Google App Engine".
Later I was told here that it wasn't successful because "Google App Engine" doesn't like external modules. That's why I found this script - those modules that it is importing in the very beginning (urllib, urllib2, cookielib) are all built-in modules.
A:
A simple "view source" on the login page whose URL you give reveals very easily the following detail about it... (just formatting the HTML minimally for readability):
<span style="display:-moz-inline-stack" class="unl">
<label for="userid">User ID </label></span>
<span><input size="27" maxlength="64" class="txtBxF"
value="" name="userid" id="userid"></span></div>
<div><span style="display:-moz-inline-stack" class="unl">
<label for="pass">Password </label></span>
<span><input size="27" maxlength="64" class="txtBxF"
value="" name="pass" id="pass" type="password"></span>
As you can see at a glance, the names of the crucial input fields are not username and j_password as you're using, but rather userid and pass. It's therefore obviously impossible for your code to work as it currently stands.
Read a bit more of the page and you'll also see soon after:
<input type="checkbox" name="keepMeSignInOption" value="1" id="signed_in"></b>
<span class="pcsm"><label for="signed_in"><b>Keep me signed in for today.</b>
Most likely you'll have to simulate that checkbox being selected to get cookies that are usable (at least for anything but a fleeting time;-).
And so on, and so forth, really -- the attempt to automate interaction with a page without bothering to read that page's source to get the actual IDs and names to use strikes me as definitely displaying a very optimistic attitude towards life, the universe, and everything...;-). Incidentally, to simplify such interaction (after perusing the source;-), I've found mechanize quite handy (and more robust than trying to hack it just with the standard library, as you are doing).
Also, before automatic interaction with a site, always check out its robots.txt to make sure you're not breaking its terms of use -- sites can easily identify "robots" (automated interaction) as opposed to "humans", and retaliate against robots.txt violation by banning, blacklisting, and worse; you don't really want to run into that;-).
| Is this webpage-logging-in Python script correct? | Is this Python script correct?
import urllib, urllib2, cookielib
username = 'myuser'
password = 'mypassword'
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
resp.read()
I found this script HERE.It is meant to login to a webpage first, retrieve the cookies, store them and use them in order to open some other page in the same website. I want to login in this way to my eBay account (the URL is https://signin.ebay.com/ws/eBayISAPI.dll?SignIn ) and then go to my inbox on my eBay account (the URL is http://my.ebay.com/ws/eBayISAPI.dll?MyEbay&gbh=1) .
So, here are the values that I need to use in this script:
First (Sing-in) URL: https://signin.ebay.com/ws/eBayISAPI.dll?SignIn
Second URL: http://my.ebay.com/ws/eBayISAPI.dll?MyEbay&gbh=1
My login name on eBay: tryinghard
My password on eBay: gettingsomewhere
With all these new values the above script must look this way:
import urllib, urllib2, cookielib
username = 'tryinghard'
password = 'gettingsomewhere'
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open(https://signin.ebay.com/ws/eBayISAPI.dll?SignIn', login_data)
resp = opener.open(http://my.ebay.com/ws/eBayISAPI.dll?MyEbay&gbh=1')
resp.read()
Is it correct? I am especially suspicious about the login_data = line (the fourth one from bottom), why is it a j_password there instead of just password?
I tried this script with all these values and it didn't work. Does anybody know why it doesn't work in my case?
I've already learned how to log in to my eBay account and then check some other pages there by means of running a python script that is using twill as an external module, but that was only successful when I ran that script from the command prompt or from the Python shell. It wasn't successful when I tried running that script by means of "Google App Engine Software Development Kit" that I had downloaded from "Google App Engine".
Later I was told here that it wasn't successful because "Google App Engine" doesn't like external modules. That's why I found this script - those modules that it is importing in the very beginning (urllib, urllib2, cookielib) are all built-in modules.
| [
"A simple \"view source\" on the login page whose URL you give reveals very easily the following detail about it... (just formatting the HTML minimally for readability):\n<span style=\"display:-moz-inline-stack\" class=\"unl\">\n <label for=\"userid\">User ID </label></span>\n<span><input size=\"27\" maxlength=\"... | [
3
] | [] | [] | [
"authentication",
"built_in",
"cookiecontainer",
"cookies",
"python"
] | stackoverflow_0003642569_authentication_built_in_cookiecontainer_cookies_python.txt |
Q:
Calculating if date is in start, future or present in Python
I have two date/time strings:
start_date = 10/2/2010 8:00:00
end_date = 10/2/2010 8:59:00
I need to write a function to calculate if the event is in the future, in the past or if it is happening right now - I've read a fair bit of documentation but just finding it quite hard to get this to work.
I've not really done much time based calculations in Python so any help would be really appreciated!
Many thanks
A:
from datetime import datetime
start_date = "10/2/2010 8:00:00"
end_date = "10/2/2010 8:59:00"
# format of date/time strings; assuming dd/mm/yyyy
date_format = "%d/%m/%Y %H:%M:%S"
# create datetime objects from the strings
start = datetime.strptime(start_date, date_format)
end = datetime.strptime(end_date, date_format)
now = datetime.now()
if end < now:
# event in past
elif start > now:
# event in future
else:
# event occuring now
| Calculating if date is in start, future or present in Python | I have two date/time strings:
start_date = 10/2/2010 8:00:00
end_date = 10/2/2010 8:59:00
I need to write a function to calculate if the event is in the future, in the past or if it is happening right now - I've read a fair bit of documentation but just finding it quite hard to get this to work.
I've not really done much time based calculations in Python so any help would be really appreciated!
Many thanks
| [
"from datetime import datetime\nstart_date = \"10/2/2010 8:00:00\"\nend_date = \"10/2/2010 8:59:00\"\n\n# format of date/time strings; assuming dd/mm/yyyy\ndate_format = \"%d/%m/%Y %H:%M:%S\"\n\n# create datetime objects from the strings\nstart = datetime.strptime(start_date, date_format)\nend = datetime.strptime(e... | [
18
] | [] | [] | [
"datetime",
"django",
"python",
"time"
] | stackoverflow_0003642892_datetime_django_python_time.txt |
Q:
Adding a numpy array to a scipy.sparse.dok_matrix
I have a scipy.sparse.dok_matrix (dimensions m x n), wanting to add a flat numpy-array with length m.
for col in xrange(n):
dense_array = ...
dok_matrix[:,col] = dense_array
However, this code raises an Exception in dok_matrix.__setitem__ when it tries to delete a non existing key (del self[(i,j)]).
So, for now I am doing this the unelegant way:
for col in xrange(n):
dense_array = ...
for row in dense_array.nonzero():
dok_matrix[row, col] = dense_array[row]
This feels very ineffecient.
So, what is the most efficient way of doing this?
Thanks!
A:
I'm surprised that your unelegant way doesn't have the same problems as the slice way. This looks like a bug to me upon looking at the Scipy code. When you try to set a certain row and column in a dok_matrix to zero when it is already zero, there is be an error because it tries to delete the value at that row and column without checking if it exists.
In answer to your question, what you are doing in your inelegant way is exactly what the __setitem__ method does currently with your elegant method (after a couple of isinstance checks and what not). If you want to use the elegant way, you can fix the bug I mentioned in your own Scipy package by opening up dok.py in Lib/site-packages/scipy/sparse/ and changing line 222 from
if value==0:
to
if value==0 and self.has_key((i,j)):
Then you can use the elegant way and it should work just fine. I went to submit a bug fix, but this it is already fixed for the next version and this is the way that it was fixed.
A:
I think that this bug has been fixed in Scipy 0.8.0
| Adding a numpy array to a scipy.sparse.dok_matrix | I have a scipy.sparse.dok_matrix (dimensions m x n), wanting to add a flat numpy-array with length m.
for col in xrange(n):
dense_array = ...
dok_matrix[:,col] = dense_array
However, this code raises an Exception in dok_matrix.__setitem__ when it tries to delete a non existing key (del self[(i,j)]).
So, for now I am doing this the unelegant way:
for col in xrange(n):
dense_array = ...
for row in dense_array.nonzero():
dok_matrix[row, col] = dense_array[row]
This feels very ineffecient.
So, what is the most efficient way of doing this?
Thanks!
| [
"I'm surprised that your unelegant way doesn't have the same problems as the slice way. This looks like a bug to me upon looking at the Scipy code. When you try to set a certain row and column in a dok_matrix to zero when it is already zero, there is be an error because it tries to delete the value at that row and ... | [
2,
1
] | [] | [] | [
"numpy",
"python",
"scipy",
"sparse_matrix"
] | stackoverflow_0002674437_numpy_python_scipy_sparse_matrix.txt |
Q:
Amazon S3cmd crashes on some large uploads
I routinely upload large bzipped sql files to S3 and have been noticing it crashing lately with this error. What might be causing this? Its always the same files that crash, but I am able to upload larger ones without a problem so it doesnt seem to be a size limit.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
An unexpected error has occurred.
Please report the following lines to:
s3tools-general@lists.sourceforge.net
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Traceback (most recent call last):
File "/usr/bin/s3cmd", line 1040, in <module>
main()
File "/usr/bin/s3cmd", line 1020, in main
cmd_func(args)
File "/usr/bin/s3cmd", line 188, in cmd_object_put
response = s3.object_put_uri(real_filename, uri_final, extra_headers)
File "/usr/lib/python2.5/site-packages/S3/S3.py", line 195, in object_put_uri
return self.object_put(filename, uri.bucket(), uri.object(), extra_headers)
File "/usr/lib/python2.5/site-packages/S3/S3.py", line 175, in object_put
response = self.send_file(request, file)
File "/usr/lib/python2.5/site-packages/S3/S3.py", line 384, in send_file
debug("MD5 sums: computed=%s, received=%s" % (md5_computed, response["headers"]["etag"]))
KeyError: 'etag'
A:
S3 did not return an ETag [entity tag] in its response. Irrespective of what cause the ETag to be missing in the response, your version of s3cmd did not expect the ETag to be absent and aborted.
As far as I can tell, this should no longer be an issue in the latest version, 0.9.9.91, of s3cmd:
## S3.py ##
...
# S3 from time to time doesn't send ETag back in a response :-(
# Force re-upload here.
if not response['headers'].has_key('etag'):
response['headers']['etag'] = ''
...
debug("MD5 sums: computed=%s, received=%s" % (md5_computed, response["headers"]["etag"]))
...
Ensure that you are using version 0.9.9.91 of s3cmd.
Version 0.9.9.91 of s3cmd will retry the upload. In the eventuality that subsequent retries also fail for this particular file, alter S3.py to print out the full S3 response, or use a packet sniffer [tcpdump on linux, Wireshark on Windows] to intercept that same full S3 response. It may contain additional hints as to what is causing this behaviour.
| Amazon S3cmd crashes on some large uploads | I routinely upload large bzipped sql files to S3 and have been noticing it crashing lately with this error. What might be causing this? Its always the same files that crash, but I am able to upload larger ones without a problem so it doesnt seem to be a size limit.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
An unexpected error has occurred.
Please report the following lines to:
s3tools-general@lists.sourceforge.net
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Traceback (most recent call last):
File "/usr/bin/s3cmd", line 1040, in <module>
main()
File "/usr/bin/s3cmd", line 1020, in main
cmd_func(args)
File "/usr/bin/s3cmd", line 188, in cmd_object_put
response = s3.object_put_uri(real_filename, uri_final, extra_headers)
File "/usr/lib/python2.5/site-packages/S3/S3.py", line 195, in object_put_uri
return self.object_put(filename, uri.bucket(), uri.object(), extra_headers)
File "/usr/lib/python2.5/site-packages/S3/S3.py", line 175, in object_put
response = self.send_file(request, file)
File "/usr/lib/python2.5/site-packages/S3/S3.py", line 384, in send_file
debug("MD5 sums: computed=%s, received=%s" % (md5_computed, response["headers"]["etag"]))
KeyError: 'etag'
| [
"S3 did not return an ETag [entity tag] in its response. Irrespective of what cause the ETag to be missing in the response, your version of s3cmd did not expect the ETag to be absent and aborted.\nAs far as I can tell, this should no longer be an issue in the latest version, 0.9.9.91, of s3cmd:\n## S3.py ##\n...\n... | [
1
] | [] | [] | [
"amazon_s3",
"python"
] | stackoverflow_0003567080_amazon_s3_python.txt |
Q:
Google App Engine: Including external packages
I understand that if you want to include external packages you have to include them in your project. So I was wondering how do you do this?
Do people use one general script that auto imports them from a location. Maybe some kind of config file that lists all the external packages? Do you always zip the packages and use zipimporter?
Anway, I guess I am looking for a good general strategy for import external packages. I learned some already from looking at source code but extra info/examples would be super.
A:
Just place the package's folder in the root directory of your GAE application, easy!
A:
if you have modules or eggs in your scripts directory these can be imported like modules
for example if i wanted to use PyRTF on Google app engine i would copy the PyRTF folder from my computer into my projects root directory, this will only work with pure-python modules though
also you can make your own modules, python will import folders as modules if they fit the structure
<foldername>
-"__init__.py"
-"someotherscript.py"
and can then be imported as
import foldername
A:
Jaikuengine use a good solution in my point of view.
It use a directory "vendor" with all dependencies and at start the application zips all packages in the directory and updates the sys path.
For more informations see on jaikuengine project:
svn/trunk/manage.py
svn/trunk/build.py
svn/trunk/vendor/
Also the importante point is, in app.yaml the directory vendor is skipped and just the libs.zip are uploaded into appengine.
| Google App Engine: Including external packages | I understand that if you want to include external packages you have to include them in your project. So I was wondering how do you do this?
Do people use one general script that auto imports them from a location. Maybe some kind of config file that lists all the external packages? Do you always zip the packages and use zipimporter?
Anway, I guess I am looking for a good general strategy for import external packages. I learned some already from looking at source code but extra info/examples would be super.
| [
"Just place the package's folder in the root directory of your GAE application, easy!\n",
"if you have modules or eggs in your scripts directory these can be imported like modules\nfor example if i wanted to use PyRTF on Google app engine i would copy the PyRTF folder from my computer into my projects root direct... | [
2,
1,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003641538_google_app_engine_python.txt |
Q:
CherryPy How to respond with JSON?
In my controller/request-handler, I have the following code:
def monkey(self, **kwargs):
cherrypy.response.headers['Content-Type'] = "application/json"
message = {"message" : "Hello World!" }
return message
monkey.exposed = True
And, in my view, I've got this javascript:
$(function() {
var body = document.getElementsByTagName("body")[0];
$.ajaxSetup({
scriptCharset : "utf-8",
contentType: "application/json; charset=utf-8"
});
$.post("http://localhost/wsgi/raspberry/monkey", "somePostData",
function(data) {
try{
var response = jQuery.parseJSON(data);
body.innerHTML += "<span class='notify'>" + response + "</span>";
}catch(e){
body.innerHTML += "<span class='error'>" + e + "</span>";
}
}
);
});
And finally, here's my problem. I get no JSON response and I'm not sure why.
Secondly, would someone be able to explain how to format data in my controller/request-handler response as a JSON response in the simplest way possible, without using tools?
A:
Since CherryPy 3.2 there are tools to accept/return JSON:
@cherrypy.expose
@cherrypy.tools.json_out()
def monkey(self, **params):
return {"message": "Hello World!"}
Using json_out serializes the output and sets the appropriate Content-Type header for you.
Similarly decorating with @cherrypy.tools.json_in() can automatically accept/decode JSON post requests.
A:
Not sure what you mean by "without using tools" -- Python is "a tool", right?
With just Python and its standard library (2.6 or better), add at the top of your module
import json
and change the return statement to
return json.dumps(message)
| CherryPy How to respond with JSON? | In my controller/request-handler, I have the following code:
def monkey(self, **kwargs):
cherrypy.response.headers['Content-Type'] = "application/json"
message = {"message" : "Hello World!" }
return message
monkey.exposed = True
And, in my view, I've got this javascript:
$(function() {
var body = document.getElementsByTagName("body")[0];
$.ajaxSetup({
scriptCharset : "utf-8",
contentType: "application/json; charset=utf-8"
});
$.post("http://localhost/wsgi/raspberry/monkey", "somePostData",
function(data) {
try{
var response = jQuery.parseJSON(data);
body.innerHTML += "<span class='notify'>" + response + "</span>";
}catch(e){
body.innerHTML += "<span class='error'>" + e + "</span>";
}
}
);
});
And finally, here's my problem. I get no JSON response and I'm not sure why.
Secondly, would someone be able to explain how to format data in my controller/request-handler response as a JSON response in the simplest way possible, without using tools?
| [
"Since CherryPy 3.2 there are tools to accept/return JSON:\n@cherrypy.expose\n@cherrypy.tools.json_out()\ndef monkey(self, **params):\n return {\"message\": \"Hello World!\"}\n\nUsing json_out serializes the output and sets the appropriate Content-Type header for you. \nSimilarly decorating with @cherrypy.tools... | [
45,
14
] | [] | [] | [
"cherrypy",
"jquery",
"json",
"python"
] | stackoverflow_0003641007_cherrypy_jquery_json_python.txt |
Q:
storing file path using windows explorer browser in python
I have written some encryption code in python that takes raw input message from user and then encrypts and decrypts it using AES. Now i want to enhance the working and i want that i can open the windows explorer from my code and browse to any file on my computer, select it and when i press OK button the path to file is stored in a variable so i can use it for processing.
I have search many forums, i have managed to open windows explorer but there is no traditional OK and Cancel button. If user presses OK button the path to the file should be stored in my code variable.
Any help in this regard will be highly appreciated.
moreover, just to let you know i have used the following code:
import os
os.system("start .")
but the explorer window doesnt have any cancel or OK button. Please help
A:
That is because what you see when you open files in Windows is not actually an Explorer window, it is called a common dialog. I am assuming you are referering to this dialog:
There are different ways you can go about opening the common open dialog, among the most easiest is probably just using the Tkinter module from the Python standard library, namely the tkFileDialog module's askopenfilename.
Example code:
import Tkinter
import tkFileDialog
root = Tkinter.Tk()
root.withdraw()
filename = tkFileDialog.askopenfilename(parent=root,title='Open file to encrypt')
As for the curly braces: You are using askopenfilenames to tell Tk that you possibly want more than one filename. That's why you get a list of filenames enclosed in curly braces. I actually suspect an oversight in Python's Tk binding so that the filenames are not split up and a list is returned, but this is easily remedied using code similar to this:
import re
# ...
# ...
filenames = tkFileDialog.askopenfilenames(parent=root)
files_to_process = re.split("\}\W\{", filenames[1:-1])
This will give you a list of the selected filenames in case the user selects more than one file. It will break when only passed a single filename, so be sure to check for that case.
| storing file path using windows explorer browser in python | I have written some encryption code in python that takes raw input message from user and then encrypts and decrypts it using AES. Now i want to enhance the working and i want that i can open the windows explorer from my code and browse to any file on my computer, select it and when i press OK button the path to file is stored in a variable so i can use it for processing.
I have search many forums, i have managed to open windows explorer but there is no traditional OK and Cancel button. If user presses OK button the path to the file should be stored in my code variable.
Any help in this regard will be highly appreciated.
moreover, just to let you know i have used the following code:
import os
os.system("start .")
but the explorer window doesnt have any cancel or OK button. Please help
| [
"That is because what you see when you open files in Windows is not actually an Explorer window, it is called a common dialog. I am assuming you are referering to this dialog:\n\nThere are different ways you can go about opening the common open dialog, among the most easiest is probably just using the Tkinter modul... | [
6
] | [] | [] | [
"explorer",
"path",
"python",
"variables",
"windows_explorer"
] | stackoverflow_0003643418_explorer_path_python_variables_windows_explorer.txt |
Q:
Delegates in python
I've implemented this short example to try to demonstrate a simple delegation pattern. My question is. Does this look like I've understood delegation right?
class Handler:
def __init__(self, parent = None):
self.parent = parent
def Handle(self, event):
handler = 'Handle_' +event
if hasattr(self, handler):
func = getattr(self, handler)
func()
elif self.parent:
self.parent.Handle(event)
class Geo():
def __init__(self, h):
self.handler = h
def Handle(self, event):
func = getattr(self.handler, 'Handle')
func(event)
class Steve():
def __init__(self, h):
self.handler = h
def Handle(self, event):
func = getattr(self.handler, 'Handle')
func(event)
class Andy():
def Handle(self, event):
print 'Andy is handling %s' %(event)
if __name__ == '__main__':
a = Andy()
s = Steve(a)
g = Geo(s)
g.Handle('lab on fire')
A:
One Python tip: you don't need to say:
func = getattr(self.handler, 'Handle')
func(event)
just say:
self.handler.Handle(event)
I'm not sure what you are doing with your Handler class, it isn't used in your example.
And in Python, methods with upper-case names are very very unusual, usually a result of porting some existing API with names like that.
A:
That's the basic concept, yes - passing on some incoming request to another object to take care of.
| Delegates in python | I've implemented this short example to try to demonstrate a simple delegation pattern. My question is. Does this look like I've understood delegation right?
class Handler:
def __init__(self, parent = None):
self.parent = parent
def Handle(self, event):
handler = 'Handle_' +event
if hasattr(self, handler):
func = getattr(self, handler)
func()
elif self.parent:
self.parent.Handle(event)
class Geo():
def __init__(self, h):
self.handler = h
def Handle(self, event):
func = getattr(self.handler, 'Handle')
func(event)
class Steve():
def __init__(self, h):
self.handler = h
def Handle(self, event):
func = getattr(self.handler, 'Handle')
func(event)
class Andy():
def Handle(self, event):
print 'Andy is handling %s' %(event)
if __name__ == '__main__':
a = Andy()
s = Steve(a)
g = Geo(s)
g.Handle('lab on fire')
| [
"One Python tip: you don't need to say:\nfunc = getattr(self.handler, 'Handle')\nfunc(event)\n\njust say:\nself.handler.Handle(event)\n\nI'm not sure what you are doing with your Handler class, it isn't used in your example.\nAnd in Python, methods with upper-case names are very very unusual, usually a result of po... | [
17,
10
] | [] | [] | [
"delegates",
"design_patterns",
"python"
] | stackoverflow_0003643538_delegates_design_patterns_python.txt |
Q:
Django / Python how to get the full request header?
I've been looking over what I can find about this and found something about denying access to specific user-agents but couldn't find how I can actually get the full request header. I am trying to make a customized analytics app so would like access to the full headers.. any info is appreciated.
A:
All the headers are available in request.META. See the documentation.
| Django / Python how to get the full request header? | I've been looking over what I can find about this and found something about denying access to specific user-agents but couldn't find how I can actually get the full request header. I am trying to make a customized analytics app so would like access to the full headers.. any info is appreciated.
| [
"All the headers are available in request.META. See the documentation.\n"
] | [
12
] | [] | [] | [
"django",
"http_headers",
"httprequest",
"python"
] | stackoverflow_0003643766_django_http_headers_httprequest_python.txt |
Q:
python changing headers
how do i change my headers and request so that i appear as firefox ...
like when request to some servers
import urllib
f = urllib.urlopen("rss feed")
they deny my request saying your client dosent have permission...
i get reply but the reply contains " your client dosent have permission"
so how do i get around this and get the data...
A:
http://vsbabu.org/mt/archives/2003/05/27/urllib2_setting_http_headers.html
A:
If you want to use good old urllib instead of newer, fancier urllib2, then as urllib's docs say, and I quote,
For example, applications may want to specify a different User-Agent header than URLopener defines. This can be accomplished with the following code:
import urllib
class AppURLopener(urllib.FancyURLopener):
version = "App/1.7"
urllib._urlopener = AppURLopener()
Of course, you'll want a version (aka User-Agent header) suitable for whatever version of Firefox (or w/ever else;-) you want to pretend you are;-).
| python changing headers | how do i change my headers and request so that i appear as firefox ...
like when request to some servers
import urllib
f = urllib.urlopen("rss feed")
they deny my request saying your client dosent have permission...
i get reply but the reply contains " your client dosent have permission"
so how do i get around this and get the data...
| [
"http://vsbabu.org/mt/archives/2003/05/27/urllib2_setting_http_headers.html\n",
"If you want to use good old urllib instead of newer, fancier urllib2, then as urllib's docs say, and I quote,\nFor example, applications may want to specify a different User-Agent header than URLopener defines. This can be accomplish... | [
2,
1
] | [] | [] | [
"http_headers",
"python"
] | stackoverflow_0003643775_http_headers_python.txt |
Q:
PythonWin saving session state
I would like to be able to save my session state within the PythonWin editor (e.g. these three files are opened and positioned in these particular locations within the PythonWin window). I can get handles to each of the child windows within PythonWin using win32gui, as well as the titles of each of the files and the positions/sizes of the windows. I'm unclear though in how to get the full path for the file listed as the child window name (i.e. if child window name is test.py and test.py lives at c:\python\test.py, I don't know how to get c:\python). I was thinking I would write out which files were opened plus their window positions to a small file that I would then call at PythonWin start time for loading.
Any ideas on how to get the full paths to the child window names?
Alternatively if someone already has a more elegant solution for saving session state in PythonWin please pass it along.
Below is the code I'm using right now (thanks to Michal Niklas for the starter code for using win32gui).
import win32gui
import re
MAIN_HWND = 0
def is_win_ok(hwnd, starttext):
s = win32gui.GetWindowText(hwnd)
if s.startswith(starttext):
global MAIN_HWND
MAIN_HWND = hwnd
return None
return 1
def find_main_window(starttxt):
global MAIN_HWND
win32gui.EnumChildWindows(0, is_win_ok, starttxt)
return MAIN_HWND
def winPos(hwnd):
if type(hwnd) == type(1): ( left, top, right, bottom ) = win32gui.GetWindowRect(hwnd)
return "%i, %i, %i, %i" % (left, right, top, bottom)
def winName(hwnd, children):
s = win32gui.GetWindowText(hwnd)
rePy = re.compile(r'[a-zA-Z1-9_ ]*.py')
rePySearch = rePy.search(s)
if rePySearch is not None:
if rePySearch.group()[0:7] != "Running":
s = s + ',' + winPos(hwnd) + '\n'
children.append(s)
return 1
def main():
children = []
main_app = 'PythonWin'
hwnd = win32gui.FindWindow(None, main_app)
if hwnd < 1:
hwnd = find_main_window(main_app)
if hwnd:
win32gui.EnumChildWindows(hwnd, winName, children)
filename = "sessionInfo.txt"
sessionFile = os.path.join(sys.path[0],filename)
fp=open(sessionFile, 'wb')
for i in range(len(children)):
fp.write(children[i])
fp.close()
main()
A:
I could be wrong, but isn't PythonWin written in Python?
Have you tried reading the source to the "Save" command to figure out where it stores its full paths?
(I'd take a look myself, but I haven't used Windows in half a decade)
| PythonWin saving session state | I would like to be able to save my session state within the PythonWin editor (e.g. these three files are opened and positioned in these particular locations within the PythonWin window). I can get handles to each of the child windows within PythonWin using win32gui, as well as the titles of each of the files and the positions/sizes of the windows. I'm unclear though in how to get the full path for the file listed as the child window name (i.e. if child window name is test.py and test.py lives at c:\python\test.py, I don't know how to get c:\python). I was thinking I would write out which files were opened plus their window positions to a small file that I would then call at PythonWin start time for loading.
Any ideas on how to get the full paths to the child window names?
Alternatively if someone already has a more elegant solution for saving session state in PythonWin please pass it along.
Below is the code I'm using right now (thanks to Michal Niklas for the starter code for using win32gui).
import win32gui
import re
MAIN_HWND = 0
def is_win_ok(hwnd, starttext):
s = win32gui.GetWindowText(hwnd)
if s.startswith(starttext):
global MAIN_HWND
MAIN_HWND = hwnd
return None
return 1
def find_main_window(starttxt):
global MAIN_HWND
win32gui.EnumChildWindows(0, is_win_ok, starttxt)
return MAIN_HWND
def winPos(hwnd):
if type(hwnd) == type(1): ( left, top, right, bottom ) = win32gui.GetWindowRect(hwnd)
return "%i, %i, %i, %i" % (left, right, top, bottom)
def winName(hwnd, children):
s = win32gui.GetWindowText(hwnd)
rePy = re.compile(r'[a-zA-Z1-9_ ]*.py')
rePySearch = rePy.search(s)
if rePySearch is not None:
if rePySearch.group()[0:7] != "Running":
s = s + ',' + winPos(hwnd) + '\n'
children.append(s)
return 1
def main():
children = []
main_app = 'PythonWin'
hwnd = win32gui.FindWindow(None, main_app)
if hwnd < 1:
hwnd = find_main_window(main_app)
if hwnd:
win32gui.EnumChildWindows(hwnd, winName, children)
filename = "sessionInfo.txt"
sessionFile = os.path.join(sys.path[0],filename)
fp=open(sessionFile, 'wb')
for i in range(len(children)):
fp.write(children[i])
fp.close()
main()
| [
"I could be wrong, but isn't PythonWin written in Python?\nHave you tried reading the source to the \"Save\" command to figure out where it stores its full paths?\n(I'd take a look myself, but I haven't used Windows in half a decade)\n"
] | [
0
] | [] | [] | [
"python",
"pywin32",
"session",
"win32gui"
] | stackoverflow_0003643696_python_pywin32_session_win32gui.txt |
Q:
Utf-8 with sqlalchemy on a database with init connect
I am trying to use sqlalchemy to connect with mysql database. I have set up charset=utf-8$use_unicode=0. This worked with almost all databases, but not with a particular one. I believe it is because it has 'init-connect' variable set to 'SET NAMES latin2;' I have no privileges to change that.
It works for me if I send explicit query SET NAMES utf8, however if there is a temporal disconnection, then after reconnecting my program breaks again as it gets lati2-encoded data from the server.
Is it possible to create some hook to always send the SET NAMES when sqlalchemy connects? Or any other way to solve this problem?
A:
Sounds like what you want is a custom PoolListener. This SO answer explains how to write one in the context of SQLite's PRAGMA foreign_keys=ON
Sqlite / SQLAlchemy: how to enforce Foreign Keys?
| Utf-8 with sqlalchemy on a database with init connect | I am trying to use sqlalchemy to connect with mysql database. I have set up charset=utf-8$use_unicode=0. This worked with almost all databases, but not with a particular one. I believe it is because it has 'init-connect' variable set to 'SET NAMES latin2;' I have no privileges to change that.
It works for me if I send explicit query SET NAMES utf8, however if there is a temporal disconnection, then after reconnecting my program breaks again as it gets lati2-encoded data from the server.
Is it possible to create some hook to always send the SET NAMES when sqlalchemy connects? Or any other way to solve this problem?
| [
"Sounds like what you want is a custom PoolListener. This SO answer explains how to write one in the context of SQLite's PRAGMA foreign_keys=ON\nSqlite / SQLAlchemy: how to enforce Foreign Keys?\n"
] | [
1
] | [] | [] | [
"mysql",
"python",
"sqlalchemy",
"utf_8"
] | stackoverflow_0003617714_mysql_python_sqlalchemy_utf_8.txt |
Q:
Django url doesn't match even though it should
In browser I get:
Request URL: http://xxxxxx:8000/person/test/
Using the URLconf defined in person.urls, Django tried these URL patterns, in this order:
^person/ ^$
^person/ ^person/(?P<slug>[-\w]+)/$
^admin/
The current URL, person/test/, didn't match any of these.
In python shell I get:
import re
url = 'person/test/'
pattern = re.compile(r'^person/(?P<slug>[-\w]+)/$'
re.match(pattern,url)
<_sre.SRE_Match object at 0xb7716860>
So it obviously should match the regexp.
Using only url person/ (the ^$ regexp) does work.
I've tried restarting the development server of course. What could be wrong here?
A:
It isn't matching against r'^person/(?P<slug>[-\w]+)/$', the 404 page shows that it's matching against r'^person/person/(?P<slug>[-\w]+)/$'
You've probably matched ^person/ in a urls.py, then imported another urls.py and put "person" in there also. Remove it from the second urls.py. After importing, a secondary urls.py only has to match the rest of the URL, not the whole URL.
| Django url doesn't match even though it should | In browser I get:
Request URL: http://xxxxxx:8000/person/test/
Using the URLconf defined in person.urls, Django tried these URL patterns, in this order:
^person/ ^$
^person/ ^person/(?P<slug>[-\w]+)/$
^admin/
The current URL, person/test/, didn't match any of these.
In python shell I get:
import re
url = 'person/test/'
pattern = re.compile(r'^person/(?P<slug>[-\w]+)/$'
re.match(pattern,url)
<_sre.SRE_Match object at 0xb7716860>
So it obviously should match the regexp.
Using only url person/ (the ^$ regexp) does work.
I've tried restarting the development server of course. What could be wrong here?
| [
"It isn't matching against r'^person/(?P<slug>[-\\w]+)/$', the 404 page shows that it's matching against r'^person/person/(?P<slug>[-\\w]+)/$'\nYou've probably matched ^person/ in a urls.py, then imported another urls.py and put \"person\" in there also. Remove it from the second urls.py. After importing, a secon... | [
5
] | [] | [] | [
"django",
"django_urls",
"python"
] | stackoverflow_0003644095_django_django_urls_python.txt |
Q:
deploying python qt project
can you tell me how do i deploy my project on qt designer. i am using windows and also how do i convert the .py files to standard .exe
A:
Converting ".py" to ".exe" would be like converting Java to ".exe" without using GCJ. Since the language doesn't compile to native code, you're just bundling the interpreter and a packed set of .py files together using the same mechanism self-extracting .zip files use.
The main tools I know of for doing this on Windows are:
Py2Exe
PyInstaller
bbfreeze
cx_Freeze
Here are some docs on how to work around the common sticking-points with PyQt:
Py2Exe and PyQt
How-to: Deploying PyQt applications on Windows and Mac OS X
Deploying PyQt Applications
Assuming you're doing this to simplify distribution, you'll probably also want to build an installer to bundle in any DLL dependencies. The two popular free choices for Windows are:
NSIS (Open-source)
InnoSetup (Freeware)
Py2Exe comes with an example of how to use a silent InnoSetup installer to build a fake single-file EXE by silently extracting the program and DLLs to a temp folder and running them. There's an example for NSIS on the site.
A:
Try pyinstaller
| deploying python qt project | can you tell me how do i deploy my project on qt designer. i am using windows and also how do i convert the .py files to standard .exe
| [
"Converting \".py\" to \".exe\" would be like converting Java to \".exe\" without using GCJ. Since the language doesn't compile to native code, you're just bundling the interpreter and a packed set of .py files together using the same mechanism self-extracting .zip files use.\nThe main tools I know of for doing thi... | [
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0003511765_python.txt |
Q:
How to access comments using lxml
I am trying to remove comments from a list of elements that were obtained by using lxml
The best I have been able to do is:
no_comments=[element for element in element_list if 'HtmlComment' not in str(type(each))]
I am wondering if there is a more direct way?
I am going to add something based on Matthew's answer - he got me almost there the problem is that when the element are taken from the tree the comments lose some identity (I don't know how to describe it) so that it cannot be determined whether they are HtmlComment class objects using the isinstance() method
However, that method can be used when the elements are being iterated through on the tree
from lxml.html import HtmlComment
no_comments=[element for element in root.iter() if not isinstance(element,HtmlComment)
For those novices like me root is the base html element that holds all of the other elements in the tree there are a number of ways to get it. One is to open the file and iterate through it so instead of root.iter() in the above
html.fromstring(open(r'c:\temp\testlxml.htm').read()).iter()
A:
You can cut out the strings:
from lxml.html import HtmlComment # or similar
no_comments=[element for element in element_list if not isinstance(element, HtmlComment)]
| How to access comments using lxml | I am trying to remove comments from a list of elements that were obtained by using lxml
The best I have been able to do is:
no_comments=[element for element in element_list if 'HtmlComment' not in str(type(each))]
I am wondering if there is a more direct way?
I am going to add something based on Matthew's answer - he got me almost there the problem is that when the element are taken from the tree the comments lose some identity (I don't know how to describe it) so that it cannot be determined whether they are HtmlComment class objects using the isinstance() method
However, that method can be used when the elements are being iterated through on the tree
from lxml.html import HtmlComment
no_comments=[element for element in root.iter() if not isinstance(element,HtmlComment)
For those novices like me root is the base html element that holds all of the other elements in the tree there are a number of ways to get it. One is to open the file and iterate through it so instead of root.iter() in the above
html.fromstring(open(r'c:\temp\testlxml.htm').read()).iter()
| [
"You can cut out the strings:\nfrom lxml.html import HtmlComment # or similar\nno_comments=[element for element in element_list if not isinstance(element, HtmlComment)]\n\n"
] | [
1
] | [] | [] | [
"html",
"lxml",
"parsing",
"python"
] | stackoverflow_0003644186_html_lxml_parsing_python.txt |
Q:
Help with Windows Geometry in Python
Why are the commands to change the window position before and after sleep(3.00) being ignored?
if self.selectedM.get() == 'Bump':
W1 = GetSystemMetrics(1) + 200
print W1
w1.wm_geometry("+100+" + str(W1))
w2.wm_geometry("+100+" + str(W1))
w3.wm_geometry("+100+" + str(W1))
w4.wm_geometry("+100+" + str(W1))
self.rvar.set(0)
self.rvar2.set(0)
self.rvar3.set(0)
self.rvar4.set(0)
s = self.wm_geometry()
geomPatt = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)")
m = geomPatt.search(s)
X3 = m.group(4)
Y3 = m.group(6)
M = int(Y3) - 150
P = M + 150
MH = W1
MUH = Y3
while Y3 > M:
sleep(0.0009)
Y3 = int(Y3) - 1
self.update_idletasks()
self.wm_geometry("+" + str(X3) + "+" + str(Y3))
print 1
Alpha = 1.0
#while 0.0 < Alpha :
# Alpha = Alpha - 0.01
# self.attributes("-alpha", Alpha)
# sleep(0.005)
self.wm_geometry("+" + str(X3) + "+" + str(MH))
sleep(3.00)
self.wm_geometry("+" + str(X3) + "+" + str(MUH))
#while 1.0 > Alpha :
# Alpha = Alpha + 0.01
# self.attributes("-alpha", Alpha)
# sleep(0.005)
while Y3 < P:
sleep(0.0009)
Y3 = int(Y3) + 1
self.update_idletasks()
self.wm_geometry("+" + str(X3) + "+" + str(Y3))
A:
The answer to your question is that you don't give the system a chance to update the display. The display is updated by the event loop but you don't enter the event loop after either of the wm_geometry calls surrounding the sleep(3.00) call. They aren't being ignored, it's just that you're changing the geometry again before the system has a chance to update the display.
Does the answer to the question Having Trouble with Tkinter Transparency help you solve this problem too?
| Help with Windows Geometry in Python | Why are the commands to change the window position before and after sleep(3.00) being ignored?
if self.selectedM.get() == 'Bump':
W1 = GetSystemMetrics(1) + 200
print W1
w1.wm_geometry("+100+" + str(W1))
w2.wm_geometry("+100+" + str(W1))
w3.wm_geometry("+100+" + str(W1))
w4.wm_geometry("+100+" + str(W1))
self.rvar.set(0)
self.rvar2.set(0)
self.rvar3.set(0)
self.rvar4.set(0)
s = self.wm_geometry()
geomPatt = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)")
m = geomPatt.search(s)
X3 = m.group(4)
Y3 = m.group(6)
M = int(Y3) - 150
P = M + 150
MH = W1
MUH = Y3
while Y3 > M:
sleep(0.0009)
Y3 = int(Y3) - 1
self.update_idletasks()
self.wm_geometry("+" + str(X3) + "+" + str(Y3))
print 1
Alpha = 1.0
#while 0.0 < Alpha :
# Alpha = Alpha - 0.01
# self.attributes("-alpha", Alpha)
# sleep(0.005)
self.wm_geometry("+" + str(X3) + "+" + str(MH))
sleep(3.00)
self.wm_geometry("+" + str(X3) + "+" + str(MUH))
#while 1.0 > Alpha :
# Alpha = Alpha + 0.01
# self.attributes("-alpha", Alpha)
# sleep(0.005)
while Y3 < P:
sleep(0.0009)
Y3 = int(Y3) + 1
self.update_idletasks()
self.wm_geometry("+" + str(X3) + "+" + str(Y3))
| [
"The answer to your question is that you don't give the system a chance to update the display. The display is updated by the event loop but you don't enter the event loop after either of the wm_geometry calls surrounding the sleep(3.00) call. They aren't being ignored, it's just that you're changing the geometry ag... | [
1
] | [] | [] | [
"algorithm",
"python",
"windows"
] | stackoverflow_0003327470_algorithm_python_windows.txt |
Q:
Reading data files in python 3.1
I am working on a project that is using data files from another program. My first attempt at reading the files was to open one of the files in binary mode, read the first 100 bytes and print the data to the terminal. I am not sure how to decipher the data that was displayed. The output that I got was:
b'URES\x04\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0f\x00\x00\x00\x03\t\x00c\x01\x00\x00\x0c#\x00\x00\x02\x1b\x00\x00\x00Y\x00\x00\x00\x08\x98"\x00\x00t\x00\x00\x00\x01\'\x01\x00\x00z$\x00\x00\x04,\xa7\x00\x00\xa1%\x00\x00\x05\x0b\x00\x00\x00o$\x00\x00\n\x11\x00\x00\x00\xcd\xcc\x00\x00\x0b\xf8\x00\x00\x00\xde\xcc\x00\x00\x0c\x19\x00\x00'
I had noticed another question on stack overflow that mentioned URES files, but I was wondering how one could go about figuring out how to read the data from this type of file.
A:
Your best bet is to work upstream: find out more about the program that created these files. Find the person maintaining that program and ask them. Find other programs that consume this data.
At the very least, you're going to have to help us by telling us what you know about this data: what is it supposed to be? What field are you even working in? Oil drilling? Medicine? Finance? Architectural drawings? Give us a clue.
A:
The most important thing is finding out what kind of file this is. I've never heard of anything starting with URES, and some quick googling doesn't turn up anything either.
You have more information than we do, so I suggest some searching combining the name of the other program, and all other relevant information you have, and see if you can find a description of the fileformat.
When you have a description, it's all a matter of chopping the input into correctly sized chunks and interpreting it according to the description. For this, the struct module is probably your friend.
| Reading data files in python 3.1 | I am working on a project that is using data files from another program. My first attempt at reading the files was to open one of the files in binary mode, read the first 100 bytes and print the data to the terminal. I am not sure how to decipher the data that was displayed. The output that I got was:
b'URES\x04\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0f\x00\x00\x00\x03\t\x00c\x01\x00\x00\x0c#\x00\x00\x02\x1b\x00\x00\x00Y\x00\x00\x00\x08\x98"\x00\x00t\x00\x00\x00\x01\'\x01\x00\x00z$\x00\x00\x04,\xa7\x00\x00\xa1%\x00\x00\x05\x0b\x00\x00\x00o$\x00\x00\n\x11\x00\x00\x00\xcd\xcc\x00\x00\x0b\xf8\x00\x00\x00\xde\xcc\x00\x00\x0c\x19\x00\x00'
I had noticed another question on stack overflow that mentioned URES files, but I was wondering how one could go about figuring out how to read the data from this type of file.
| [
"Your best bet is to work upstream: find out more about the program that created these files. Find the person maintaining that program and ask them. Find other programs that consume this data.\nAt the very least, you're going to have to help us by telling us what you know about this data: what is it supposed to b... | [
1,
0
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0003644346_linux_python.txt |
Q:
Multiple values for key in dictionary in Python
What I'm trying to do is get 3 values from a key into separate variables. Currently I'm doing it like this:
for key in names:
posX = names[key][0]
posY = names[key][1]
posZ = names[key][2]
This doesn't seem very intuitive to me even though it works. I've also tried doing this:
for key, value in names:
location = value
Unfortunately, this gives me a single object (which is what I expected), but I need the individual values assigned to the key. Thanks and apologize for my newness to Python.
Update
Apologies for not specifying where I was getting my values from. Here is how I'm doing it for the first example.
names = {}
for name in objectNames:
cmds.select(name)
location = cmds.xform(q=True, ws=True, t=True)
names[name] = location
A:
It's not unintuitive at all.
The only way to store "multiple values" for a given key in a dictionary is to store some sort of container object as the value, such as a list or tuple. You can access a list or tuple by subscripting it, as you do in your first example.
The only problem with your example is that it's the ugly and inconvenient way to access such a container when it's being used in this way. Try it like this, and you'll probably be much happier:
>>> alist = [1, 2, 3]
>>> one, two, three = alist
>>> one
1
>>> two
2
>>> three
3
>>>
Thus your second example could instead be:
for key, value in names.items():
posX, posY, posZ = value
As FabienAndre points out in a comment below, there's also the more convenient syntax I'd entirely forgotten about, for key,(posX,posY,posZ) in names.items():.
You don't specify where you're getting these values from, but if they're coming from code you have control over, and you can depend on using Python 2.6 or later, you might also look into named tuples. Then you could provide a named tuple as the dict value, and use the syntax pos.x, pos.y, etc. to access the values:
for name, pos in names.items():
doSomethingWith(pos.x)
doSomethingElseWith(pos.x, pos.y, pos.z)
A:
If you don't mind an external dependency, you could include Werkzeug's MultiDict:
A MultiDict is a dictionary subclass customized to deal with multiple values for the same key which is for example used by the parsing functions in the wrappers.
>>> d = MultiDict([('a', 'b'), ('a', 'c')])
>>> d
MultiDict([('a', 'b'), ('a', 'c')])
>>> d['a']
'b'
>>> d.getlist('a')
['b', 'c']
>>> 'a' in d
True
Another way to store multiple values for a key is to use a container type, like a list, a set or a tuple.
A:
Looking at your code, working with position/location variables, you could also unify the X, Y and Z position into a common type, for example using named tuples:
from collections import namedtuple
Position = namedtuple("Position", "x, y, z")
locations = {
"chair": Position(1, 2, 5.3),
"table": Position(5, 3.732, 6),
"lamp": Position(4.4, 7.2, 2)
}
print "Chair X location: ", locations["chair"].x
Just a suggestion, though.
| Multiple values for key in dictionary in Python | What I'm trying to do is get 3 values from a key into separate variables. Currently I'm doing it like this:
for key in names:
posX = names[key][0]
posY = names[key][1]
posZ = names[key][2]
This doesn't seem very intuitive to me even though it works. I've also tried doing this:
for key, value in names:
location = value
Unfortunately, this gives me a single object (which is what I expected), but I need the individual values assigned to the key. Thanks and apologize for my newness to Python.
Update
Apologies for not specifying where I was getting my values from. Here is how I'm doing it for the first example.
names = {}
for name in objectNames:
cmds.select(name)
location = cmds.xform(q=True, ws=True, t=True)
names[name] = location
| [
"It's not unintuitive at all.\nThe only way to store \"multiple values\" for a given key in a dictionary is to store some sort of container object as the value, such as a list or tuple. You can access a list or tuple by subscripting it, as you do in your first example.\nThe only problem with your example is that it... | [
11,
2,
2
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003644409_dictionary_python.txt |
Q:
Default Python compilers on MacOS X
I'm trying to install matplotlib for Python on MacOS X. If I use the system Python 2.6.1, the default compiler commands that matplotlib uses (presumably via distutils) are::
gcc-4.2 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes
g++-4.2 -Wl,-F. -bundle -undefined dynamic_lookup
However, if I simply add the python.org 2.6.6 Python to the PATH to use that instead, the default compilers suddenly change to
gcc-4.0 -DNDEBUG -g -O3
c++ -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk \
-g -bundle -undefined dynamic_lookup
This causes issues, so I was wondering what determines which C compilers are used when running python setup.py install? Why does using the python.org Python mean that different default compiler commands are used?
A:
The python.org release is designed to work just as well on MacOsX 10.5 as on 10.6, therefore of course it has to stick with a gcc release that is commonly available for both. Apple's system Python, of course, labors under no such constraint -- it supports only a very specific version of MacOsX and therefore can use the "latest and greatest" gcc available for that one specific version... and so of course it does;-).
| Default Python compilers on MacOS X | I'm trying to install matplotlib for Python on MacOS X. If I use the system Python 2.6.1, the default compiler commands that matplotlib uses (presumably via distutils) are::
gcc-4.2 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes
g++-4.2 -Wl,-F. -bundle -undefined dynamic_lookup
However, if I simply add the python.org 2.6.6 Python to the PATH to use that instead, the default compilers suddenly change to
gcc-4.0 -DNDEBUG -g -O3
c++ -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk \
-g -bundle -undefined dynamic_lookup
This causes issues, so I was wondering what determines which C compilers are used when running python setup.py install? Why does using the python.org Python mean that different default compiler commands are used?
| [
"The python.org release is designed to work just as well on MacOsX 10.5 as on 10.6, therefore of course it has to stick with a gcc release that is commonly available for both. Apple's system Python, of course, labors under no such constraint -- it supports only a very specific version of MacOsX and therefore can u... | [
0
] | [] | [] | [
"compiler_construction",
"python"
] | stackoverflow_0003644399_compiler_construction_python.txt |
Q:
Language/GUI library to make map editor
I'm designing a cross-platform map editor for an application I've developed, and I'm unsure what approach to take regarding language/gui library choice. Just for some basic info, the editor needs to parse and output xml files.
I'm most comfortable with C++, Lua, and Perl, but I'd also be willing to use Python (could use the practice). I'd prefer doing it in a scripting language for productivity.
Any recommendations are appreciated, thanks.
I'd also like support for filling out forms, etc.
P.S. I've tested out extending existing map editors but it isn't really worth it since they don't provide the functionality I need on a fundamental level, requiring me to just re-write the whole thing anyway.
A:
My preference is always Gtk2 and Perl 5, but that combination works best on Linux. What OS are you going to run under?
Here is an example Perl 5 script using Gtk2:
#!/usr/bin/perl
use strict;
use warnings;
use Gtk2;
Gtk2->init;
my $window = Gtk2::Window->new;
my $vbox = Gtk2::VBox->new;
my $label = Gtk2::Label->new("click the button");
my $button = Gtk2::Button->new("click me");
my $i;
$window->signal_connect(destroy => sub { Gtk2->main_quit });
$button->signal_connect(clicked => sub { $label->set_text(++$i) });
$window->add($vbox);
$vbox->add($label);
$vbox->add($button);
$window->show_all;
Gtk2->main;
A:
I can recommend using Python and PyQt for the job. Qt offers a class for scene management (i.e. layered object placement, zooming, hit testing, events,coordinate transformations etc., even collision detection) called QGraphicsScene and a matching control to display it all, called QGraphicsView. It also offers support for drag&drop, thus enabling interactive object placement.
Implementing a map using these classes really is just creating QGraphicItems (Rectangles, Polygons etc.) and adding them to the scene, Qt does the rest. You can have a look at how it all fits together reading the documentation, especially the document "The Graphics View Framework". I had to implement something similar for a client recently and was very pleased with this approach.
A:
Building on the base of Lua, I would recommend IUP for the GUI. It is lightweight, portable to linux and Windows, and well integrated with Lua. For those who like Gtk, IUP includes a driver for Gtk so it can in principle be ported to any system where Gtk can port.
Another plausible choice is wxWidgets, which also has a wrapper integrating it with Lua.
Both IUP and wxWidgets are included in the Lua for Windows bundle.
| Language/GUI library to make map editor | I'm designing a cross-platform map editor for an application I've developed, and I'm unsure what approach to take regarding language/gui library choice. Just for some basic info, the editor needs to parse and output xml files.
I'm most comfortable with C++, Lua, and Perl, but I'd also be willing to use Python (could use the practice). I'd prefer doing it in a scripting language for productivity.
Any recommendations are appreciated, thanks.
I'd also like support for filling out forms, etc.
P.S. I've tested out extending existing map editors but it isn't really worth it since they don't provide the functionality I need on a fundamental level, requiring me to just re-write the whole thing anyway.
| [
"My preference is always Gtk2 and Perl 5, but that combination works best on Linux. What OS are you going to run under?\nHere is an example Perl 5 script using Gtk2:\n#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nuse Gtk2;\n\nGtk2->init;\n\nmy $window = Gtk2::Window->new;\nmy $vbox = Gtk2::VBox->new;\nmy $lab... | [
4,
2,
2
] | [] | [] | [
"c++",
"lua",
"perl",
"python",
"user_interface"
] | stackoverflow_0003644441_c++_lua_perl_python_user_interface.txt |
Q:
How do I get window attributes in Tkinter?
self.attributes("-alpha", Alpha)
How do I get window attributes in Tkinter? Currently I wan't my program to get the value of Alpha.
A:
In an earlier question you asked about transparency I gave an example that gets the alpha value for a window. See Having trouble with Tkinter transparency
| How do I get window attributes in Tkinter? | self.attributes("-alpha", Alpha)
How do I get window attributes in Tkinter? Currently I wan't my program to get the value of Alpha.
| [
"In an earlier question you asked about transparency I gave an example that gets the alpha value for a window. See Having trouble with Tkinter transparency\n"
] | [
2
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0003644515_python_tkinter.txt |
Q:
Python's getattr gets called twice?
I am using this simple example to understand Python's getattr function:
In [25]: class Foo:
....: def __getattr__(self, name):
....: print name
....:
....:
In [26]: f = Foo()
In [27]: f.bar
bar
bar
Why is bar printed twice? Using Python 2.6.5.
A:
I think it's due to IPython.
To "fix" it, you have to disable autocall: %autocall 0
It's an inevitable side-effect of
%autocall: since it has to analyze the
object in the command line to see if
it's callable, python triggers getattr
calls on it.
Source: http://mail.scipy.org/pipermail/ipython-user/2008-June/005562.html
A:
You're also using IPython. The stock CPython REPL doesn't exhibit this behavior.
| Python's getattr gets called twice? | I am using this simple example to understand Python's getattr function:
In [25]: class Foo:
....: def __getattr__(self, name):
....: print name
....:
....:
In [26]: f = Foo()
In [27]: f.bar
bar
bar
Why is bar printed twice? Using Python 2.6.5.
| [
"I think it's due to IPython.\nTo \"fix\" it, you have to disable autocall: %autocall 0\n\nIt's an inevitable side-effect of\n %autocall: since it has to analyze the\n object in the command line to see if\n it's callable, python triggers getattr\n calls on it.\n\nSource: http://mail.scipy.org/pipermail/ipython... | [
9,
3
] | [] | [] | [
"getattr",
"python",
"python_2.6",
"reflection"
] | stackoverflow_0003644545_getattr_python_python_2.6_reflection.txt |
Q:
PyGTK treeview and row_activated callback
I'm trying to retrieve the row data from a treemodel when the row_activated callback is fired.
When row_activated is called, the 'path' variable it passes is a tuple. How do I easily use this tuple to retrieve an iter and ultimately the data itself? The treemodel class has a function to convert a string into an iter, but it seems like there should be an easier way than converting the tuple to a string, then the string to an iter.
A:
Answering my own question, it makes sense after 45 minutes of googling I solve my own problem 30 seconds after posting on StackOverflow.
I needed to use the get_iter function, not the get_iter_from_string function.
| PyGTK treeview and row_activated callback | I'm trying to retrieve the row data from a treemodel when the row_activated callback is fired.
When row_activated is called, the 'path' variable it passes is a tuple. How do I easily use this tuple to retrieve an iter and ultimately the data itself? The treemodel class has a function to convert a string into an iter, but it seems like there should be an easier way than converting the tuple to a string, then the string to an iter.
| [
"Answering my own question, it makes sense after 45 minutes of googling I solve my own problem 30 seconds after posting on StackOverflow.\nI needed to use the get_iter function, not the get_iter_from_string function.\n"
] | [
2
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0003644777_pygtk_python.txt |
Q:
Setuptools not found
I am switching from Linux to OSX and when I run our build's setup.py script, I get an error message that contains the text
This script requires setuptools version 0.6c7.
I have tried several times to install setuptools, and have verified that the setuptools egg exists in /Library/Python/2.6/site-packages. I have no idea why it is not being recognized.
A:
It is very common to have multiple versions of Python on OS X systems. In recent releases of OS X, Apple has shipped two versions itself (in /usr/bin). You may have installed more recent versions using installers from python.org (which generally exist in /Library/Frameworks/Python.framework or using a package distributor like MacPorts (which install in /opt/local/Library/Frameworks/Python.framework). Keep in mind that each version of Python requires its own copy of setuptools.
Since the site package path you report is /Library/Python/2.6/site-packages, it is most likely you have used the Apple-supplied Python 2.6.1 in OS X 10.6 to try to install a new version of setuptools. Note that Apple already supplies setuptools for its Pythons (0.6c9 for 2.6.1 in 10.6); the corresponding easy_install commands are in /usr/bin.
$ /usr/bin/python2.6 -c 'import setuptools;print(setuptools.__file__,setuptools.__version__)'
('/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/setuptools/__init__.pyc', '0.6c9')
If you are using another non-Apple-supplied Python, follow the instructions to install a new version of setuptools (or Distribute) making sure you are invoking the right version of Python. Check your shell PATH and which python to make sure.
If that doesn't help, update your question with more information.
UPDATE: Based on your further comments, it seems something was amiss in your default site-packages directory. With that problem out of the way and having established that there is an Apple-supplied setuptools version 0.6c9 installed, it appears the package you are trying to install is looking for a specific, earlier version of setuptools, 0.6c7. If that is the case, you should first determine why that is and if it is necessary. Chances are that it is just an incorrect version specification in the package's setup.py file, i.e. using == rather than >=. If you can, edit the setup.py so it can use a newer version. In the unlikely event that the package really does need that specific older version of setuptools (which may not even work with that version of Python or OS X), you could try installing the older version, like so:
$ sudo /usr/bin/easy_install-2.6 setuptools==0.6c7
$ /usr/bin/python2.6 -c 'import setuptools;print(setuptools.__file__,setuptools.__version__)'
('/Library/Python/2.6/site-packages/setuptools-0.6c7-py2.6.egg/setuptools/__init__.pyc', '0.6c7')
But you really should avoid doing that if at all possible as that will install another older version of easy_install in /usr/local/bin and could cause problems with installing and using other packages.
A:
Have you tried to import setuptools in your setup.pyscript?
import setuptools
This solved my setuptool-ish build problems in the past.
| Setuptools not found | I am switching from Linux to OSX and when I run our build's setup.py script, I get an error message that contains the text
This script requires setuptools version 0.6c7.
I have tried several times to install setuptools, and have verified that the setuptools egg exists in /Library/Python/2.6/site-packages. I have no idea why it is not being recognized.
| [
"It is very common to have multiple versions of Python on OS X systems. In recent releases of OS X, Apple has shipped two versions itself (in /usr/bin). You may have installed more recent versions using installers from python.org (which generally exist in /Library/Frameworks/Python.framework or using a package di... | [
1,
0
] | [] | [] | [
"macos",
"python",
"setup.py",
"setuptools"
] | stackoverflow_0003644917_macos_python_setup.py_setuptools.txt |
Q:
How to parse a web use javascript to load .html by Python?
I'm using Python to parse an auction site.
If I use browser to open this site, it will go to a loading page, then jump to the search result page automatically.
If I use urllib2 to open the webpage, the read() method only return the loading page.
Is there any python package could wait until all contents are loaded then read() method return all results?
Thanks.
A:
How does the search page work? If it loads anything using Ajax, you could do some basic reverse engineering and find the URLs involved using Firebug's Net panel or Wireshark and then use urllib2 to load those.
If it's more complicated than that, you could simulate the actions JS performs manually without loading and interpreting JavaScript. It all depends on how the search page works.
Lastly, I know there are ways to run scripting on pages without a browser, since that's what some functional testing suites do, but my guess is that this could be the most complicated approach.
A:
After tracing for the auction web source code, I found that it uses .php to create loading page and redirect to result page. Reverse engineering to find the ture URLs is not working because it's the same URL as loading page.
And @Manoj Govindan, I've tried Mechanize, but even if I add
br.set_handle_refresh(True)
br.set_handle_redirect(True)
it still read the loading page.
After hours of searching on www, I found a possible solution : using pywin32
import win32com.client
import time
url = 'http://search.ruten.com.tw/search/s000.php?searchfrom=headbar&k=halo+reach'
ie = win32com.client.Dispatch("InternetExplorer.Application")
ie.Visible = 0
ie.Navigate(url)
while 1:
state = ie.ReadyState
if state == 4:
break
time.sleep(1)
print ie.Document.body.innerHTML
However this only works on win32 platform, I'm looking for a cross platform solutoin.
If anyone know how to deal this, please tell me.
| How to parse a web use javascript to load .html by Python? | I'm using Python to parse an auction site.
If I use browser to open this site, it will go to a loading page, then jump to the search result page automatically.
If I use urllib2 to open the webpage, the read() method only return the loading page.
Is there any python package could wait until all contents are loaded then read() method return all results?
Thanks.
| [
"How does the search page work? If it loads anything using Ajax, you could do some basic reverse engineering and find the URLs involved using Firebug's Net panel or Wireshark and then use urllib2 to load those.\nIf it's more complicated than that, you could simulate the actions JS performs manually without loading ... | [
0,
0
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0003637681_javascript_python.txt |
Q:
pkg_resources.VersionConflict when I try to start paster serve
Im trying to use port 80.
So when i use the command "sudo paster serve development.ini --reload"
I get this error
pkg_resources.VersionConflict: (Pylons 0.9.7 (/usr/lib/pymodules/python2.6), Requirement.parse('Pylons>=1.0'))
I tried to do "easy_install pylons"
but I get
"Pylons 1.0 is already the active version in easy-install.pth"
How do I fix this?
A:
It sounds like Python is finding Pylons 0.9.7 before 1.0 in the module search path.
If that's the case, the simplest solution is probably to use your package manager to uninstall Pylons 0.9.7 and then use easy_install to restore anything that got removed as a side-effect.
If that doesn't do it, try also removing Pylons 1.0 and re-running easy_install... though I prefer using virtualenv to keep my system packages cleanly separated from the stuff installed by easy_install.
As an alternative, you could create a clean virtual environment with virtualenv --no-site-packages whatever and then easy_install Pylons 1.0 into that.
| pkg_resources.VersionConflict when I try to start paster serve | Im trying to use port 80.
So when i use the command "sudo paster serve development.ini --reload"
I get this error
pkg_resources.VersionConflict: (Pylons 0.9.7 (/usr/lib/pymodules/python2.6), Requirement.parse('Pylons>=1.0'))
I tried to do "easy_install pylons"
but I get
"Pylons 1.0 is already the active version in easy-install.pth"
How do I fix this?
| [
"It sounds like Python is finding Pylons 0.9.7 before 1.0 in the module search path.\nIf that's the case, the simplest solution is probably to use your package manager to uninstall Pylons 0.9.7 and then use easy_install to restore anything that got removed as a side-effect.\nIf that doesn't do it, try also removing... | [
3
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0003644921_pylons_python.txt |
Q:
Floats incorrect? - Python 2.6
I have a programming question, as follows, for which my solution does not produce the desired output
This particle simulator operates in a universe with different laws of physics to ours. Each particle has a position (x, y), velocity (vx, vy) and an acceleration (ax, ay). Every particle exerts an attractive force on every other particle. This force is the same regardless of how far away the particle is.
The acceleration of a particle in the x direction is given by
(ax=number of particles to right of x−number of particles to left of x) / 10.0
The particle will then move left or right with velocity vx + ax.
Similarly, the acceleration of a particle in the y direction is given by
(ay=number of particles above y−number of particles below y) / 10.0
The particle will then move up or down with velocity vy + ay.
The particles are bound in a chamber with dimensions −300 < x < 300 and −200 < y < 200. If a particle hits the wall of the chamber it should bounce. Bouncing involves setting the x or y coordinate to the boundary, and reversing the direction of the velocity. For example, if a particle ends up with position x=305 then you should set x=300 and vx = -vx. Note that x must be set to the integer value 300 in order to get the same output values as our test cases.
Write a program to read in a file named particles.txt containing the initial positions, velocities and accelerations of a number of particles. The first line of the file contains the number of iterations to run the simulation for (5 in this example). Every other row contains data about one particle, in the format x y vx vy ax ay like this:
5
0 -30 3 0 0 0
100 50 0 1 0 0
20 10 0 3 0 0
-80 15 2 -2 0 0
Your program should create a Particle object to store the data for each particle. Then for every iteration of the simulation you should
calculate the acceleration on each particle (using the equations above)
then calculate the new velocity for each particle (vx = vx + ax)
then calculate the new position for each particle (x = x + vx)
The output of your program should be a list of positions for each particle at every step of the simulation, in CSV format x1,y1,x2,y2,x3,y3,x4,y4 for the 4-particle example shown above:
3.1,-29.7,99.7,50.7,19.9,13.1,-77.7,12.9
6.3,-29.1,99.1,51.1,19.7,16.1,-75.1,10.9
9.6,-28.2,98.2,51.2,19.4,19.0,-72.2,9.0
13.0,-27.0,97.0,51.0,19.0,21.8,-69.0,7.2
16.5,-25.5,95.5,50.5,18.5,24.5,-65.5,5.5
To produce these numbers, you should call str on the x and y coordinates of each of the particles.
My code is as follows:
class Particle(object):
def __init__(self, (x, y, vx, vy, ax, ay)):
# Set initial values
self.x, self.y = float(x), float(y)
self.vx, self.vy = float(vx), float(vy)
self.ax, self.ay = float(ax), float(ay)
def __str__(self):
return '(' + str(self.x) + ', ' + str(self.y) + ')'
# Calculate new acceleration
def calc_acc(self, part_list):
left, right = 0, 0
up, down = 0, 0
for particle in part_list:
# Count particles on left & right
if particle.x < self.x:
left += 1
elif particle.x > self.x:
right += 1
# Count particles above & below
if particle.y > self.y:
up += 1
elif particle.y < self.y:
down += 1
# Calculate x-acceleration
self.ax = (right - left) / 10.0
# Calculate y-acceleration
self.ay = (up - down) / 10.0
# Calculate new velocity
def calc_vel(self):
self.vx = self.vx + self.ax
self.vy = self.vy + self.ay
# Move the particle
def move(self, p_list):
# Calculate new acceleration & velocity
self.calc_acc(p_list)
self.calc_vel()
# Make move
self.x += self.vx
self.y += self.vy
# Check for bounce, and bounce
# X-axis
if self.x > 300.0:
self.x = 300
self.vx = -(self.vx)
elif self.x < -300.0:
self.x = -300
self.vx = -(self.vx)
# Y-axis
if self.y > 200.0:
self.y = 200
self.vy = -(self.vy)
elif self.y < -200.0:
self.y = -200
self.vy = -(self.vy)
# Return resulting position
return self.x, self.y
# Take file input
input_file = []
for line in open('particles2.txt', 'rU'):
input_file.append(line)
# Take number of iterations, and leave particle info only
times = int(input_file.pop(0))
# Remove '\n' from particle info, and convert particle info to a list of floats
for line in input_file:
input_file[input_file.index(line)] = line.strip('\n').split()
# Create list of Particle objects
particles = []
for line in input_file:
particles.append(Particle(line))
# Create result position array
results = []
for i in range(times):
results.append([None for x in range(len(particles))])
# Run simulation for 'times' iterations
for iteration in range(times):
i = 0
for particle in particles:
results[iteration][i] = particle.move(particles)
i += 1
# Create csv formatted string for output
result_output = ''
for iteration in results:
for particle in iteration:
result_output += str(particle[0]) + ',' + str(particle[1]) + ','
result_output += '\n'
result_output = result_output.replace(',\n', '\n')
print result_output
output is:
21.9,2.0,-18.9,10.1
23.7,4.1,-17.7,20.1
25.4,6.3,-16.4,30.0
27.0,8.6,-15.0,39.8
28.5,11.0,-13.5,49.5
29.9,13.5,-11.9,59.1
31.2,16.1,-10.2,68.6
32.4,18.8,-8.4,78.0
33.5,21.6,-6.5,87.3
34.5,24.5,-4.5,96.5
35.4,27.5,-2.4,105.6
36.2,30.6,-0.2,114.6
36.9,33.8,2.1,123.5
37.5,37.1,4.5,132.3
38.0,40.5,7.0,141.0
38.4,44.0,9.6,149.6
38.7,47.6,12.3,158.1
38.9,51.3,15.1,166.5
39.0,55.1,18.0,174.8
39.0,59.0,21.0,183.0
38.9,63.0,24.1,191.1
38.7,67.1,27.3,199.1
38.4,71.3,30.6,200
38.0,75.6,34.0,192.0
37.5,80.0,37.5,183.9
37.1,84.5,40.9,175.7
36.8,89.1,44.2,167.4
36.6,93.8,47.4,159.0
36.5,98.6,50.5,150.5
36.5,103.5,53.5,141.9
36.6,108.5,56.4,133.2
36.8,113.6,59.2,124.4
37.1,118.8,61.9,115.5
37.5,123.9,64.5,106.7
38.0,128.9,67.0,98.0
38.6,133.8,69.4,89.4
39.3,138.6,71.7,80.9
40.1,143.3,73.9,72.5
41.0,147.9,76.0,64.2
42.0,152.4,78.0,56.0
43.1,156.8,79.9,47.9
44.3,161.1,81.7,39.9
45.6,165.3,83.4,32.0
47.0,169.4,85.0,24.2
48.5,173.4,86.5,16.5
50.1,177.3,87.9,8.9
51.8,181.1,89.2,1.4
53.6,184.8,90.4,-6.0
55.5,188.4,91.5,-13.3
57.5,191.9,92.5,-20.5
when it should be:
21.9,2.0,-18.9,10.0
23.7,4.1,-17.7,19.9
25.4,6.3,-16.4,29.7
27.0,8.6,-15.0,39.4
28.5,11.0,-13.5,49.0
29.9,13.5,-11.9,58.5
31.2,16.1,-10.2,67.9
32.4,18.8,-8.4,77.2
33.5,21.6,-6.5,86.4
34.5,24.5,-4.5,95.5
35.4,27.5,-2.4,104.5
36.2,30.6,-0.2,113.4
36.9,33.8,2.1,122.2
37.5,37.1,4.5,130.9
38.0,40.5,7.0,139.5
38.4,44.0,9.6,148.0
38.7,47.6,12.3,156.4
38.9,51.3,15.1,164.7
39.0,55.1,18.0,172.9
39.0,59.0,21.0,181.0
38.9,63.0,24.1,189.0
38.7,67.1,27.3,196.9
38.4,71.3,30.6,200
38.0,75.6,34.0,192.1
37.5,80.0,37.5,184.1
37.1,84.5,40.9,176.0
36.8,89.1,44.2,167.8
36.6,93.8,47.4,159.5
36.5,98.6,50.5,151.1
36.5,103.5,53.5,142.6
36.6,108.5,56.4,134.0
36.8,113.6,59.2,125.3
37.1,118.8,61.9,116.5
37.5,123.9,64.5,107.8
38.0,128.9,67.0,99.2
38.6,133.8,69.4,90.7
39.3,138.6,71.7,82.3
40.1,143.3,73.9,74.0
41.0,147.9,76.0,65.8
42.0,152.4,78.0,57.7
43.1,156.8,79.9,49.7
44.3,161.1,81.7,41.8
45.6,165.3,83.4,34.0
47.0,169.4,85.0,26.3
48.5,173.4,86.5,18.7
50.1,177.3,87.9,11.2
51.8,181.1,89.2,3.8
53.6,184.8,90.4,-3.5
55.5,188.4,91.5,-10.7
57.5,191.9,92.5,-17.8
For some reason, which I am unable to locate, the floats in the last column are not quite right. They differ from the desired output by anything between 2 and 0.5 or so.
I have no idea why this is the case!
Thanks for any help!
A:
You need to make a snapshot of the state and perform your calculations on the snapshot. If you move the particles around during the calculations as you are currently doing, you will get inconsistent results.
Something like this may work
from copy import deepcopy
for iteration in range(times):
i = 0
particles_snapshot = deepcopy(particles)
for particle in particles:
results[iteration][i] = particle.move(particles_snapshot)
i += 1
| Floats incorrect? - Python 2.6 | I have a programming question, as follows, for which my solution does not produce the desired output
This particle simulator operates in a universe with different laws of physics to ours. Each particle has a position (x, y), velocity (vx, vy) and an acceleration (ax, ay). Every particle exerts an attractive force on every other particle. This force is the same regardless of how far away the particle is.
The acceleration of a particle in the x direction is given by
(ax=number of particles to right of x−number of particles to left of x) / 10.0
The particle will then move left or right with velocity vx + ax.
Similarly, the acceleration of a particle in the y direction is given by
(ay=number of particles above y−number of particles below y) / 10.0
The particle will then move up or down with velocity vy + ay.
The particles are bound in a chamber with dimensions −300 < x < 300 and −200 < y < 200. If a particle hits the wall of the chamber it should bounce. Bouncing involves setting the x or y coordinate to the boundary, and reversing the direction of the velocity. For example, if a particle ends up with position x=305 then you should set x=300 and vx = -vx. Note that x must be set to the integer value 300 in order to get the same output values as our test cases.
Write a program to read in a file named particles.txt containing the initial positions, velocities and accelerations of a number of particles. The first line of the file contains the number of iterations to run the simulation for (5 in this example). Every other row contains data about one particle, in the format x y vx vy ax ay like this:
5
0 -30 3 0 0 0
100 50 0 1 0 0
20 10 0 3 0 0
-80 15 2 -2 0 0
Your program should create a Particle object to store the data for each particle. Then for every iteration of the simulation you should
calculate the acceleration on each particle (using the equations above)
then calculate the new velocity for each particle (vx = vx + ax)
then calculate the new position for each particle (x = x + vx)
The output of your program should be a list of positions for each particle at every step of the simulation, in CSV format x1,y1,x2,y2,x3,y3,x4,y4 for the 4-particle example shown above:
3.1,-29.7,99.7,50.7,19.9,13.1,-77.7,12.9
6.3,-29.1,99.1,51.1,19.7,16.1,-75.1,10.9
9.6,-28.2,98.2,51.2,19.4,19.0,-72.2,9.0
13.0,-27.0,97.0,51.0,19.0,21.8,-69.0,7.2
16.5,-25.5,95.5,50.5,18.5,24.5,-65.5,5.5
To produce these numbers, you should call str on the x and y coordinates of each of the particles.
My code is as follows:
class Particle(object):
def __init__(self, (x, y, vx, vy, ax, ay)):
# Set initial values
self.x, self.y = float(x), float(y)
self.vx, self.vy = float(vx), float(vy)
self.ax, self.ay = float(ax), float(ay)
def __str__(self):
return '(' + str(self.x) + ', ' + str(self.y) + ')'
# Calculate new acceleration
def calc_acc(self, part_list):
left, right = 0, 0
up, down = 0, 0
for particle in part_list:
# Count particles on left & right
if particle.x < self.x:
left += 1
elif particle.x > self.x:
right += 1
# Count particles above & below
if particle.y > self.y:
up += 1
elif particle.y < self.y:
down += 1
# Calculate x-acceleration
self.ax = (right - left) / 10.0
# Calculate y-acceleration
self.ay = (up - down) / 10.0
# Calculate new velocity
def calc_vel(self):
self.vx = self.vx + self.ax
self.vy = self.vy + self.ay
# Move the particle
def move(self, p_list):
# Calculate new acceleration & velocity
self.calc_acc(p_list)
self.calc_vel()
# Make move
self.x += self.vx
self.y += self.vy
# Check for bounce, and bounce
# X-axis
if self.x > 300.0:
self.x = 300
self.vx = -(self.vx)
elif self.x < -300.0:
self.x = -300
self.vx = -(self.vx)
# Y-axis
if self.y > 200.0:
self.y = 200
self.vy = -(self.vy)
elif self.y < -200.0:
self.y = -200
self.vy = -(self.vy)
# Return resulting position
return self.x, self.y
# Take file input
input_file = []
for line in open('particles2.txt', 'rU'):
input_file.append(line)
# Take number of iterations, and leave particle info only
times = int(input_file.pop(0))
# Remove '\n' from particle info, and convert particle info to a list of floats
for line in input_file:
input_file[input_file.index(line)] = line.strip('\n').split()
# Create list of Particle objects
particles = []
for line in input_file:
particles.append(Particle(line))
# Create result position array
results = []
for i in range(times):
results.append([None for x in range(len(particles))])
# Run simulation for 'times' iterations
for iteration in range(times):
i = 0
for particle in particles:
results[iteration][i] = particle.move(particles)
i += 1
# Create csv formatted string for output
result_output = ''
for iteration in results:
for particle in iteration:
result_output += str(particle[0]) + ',' + str(particle[1]) + ','
result_output += '\n'
result_output = result_output.replace(',\n', '\n')
print result_output
output is:
21.9,2.0,-18.9,10.1
23.7,4.1,-17.7,20.1
25.4,6.3,-16.4,30.0
27.0,8.6,-15.0,39.8
28.5,11.0,-13.5,49.5
29.9,13.5,-11.9,59.1
31.2,16.1,-10.2,68.6
32.4,18.8,-8.4,78.0
33.5,21.6,-6.5,87.3
34.5,24.5,-4.5,96.5
35.4,27.5,-2.4,105.6
36.2,30.6,-0.2,114.6
36.9,33.8,2.1,123.5
37.5,37.1,4.5,132.3
38.0,40.5,7.0,141.0
38.4,44.0,9.6,149.6
38.7,47.6,12.3,158.1
38.9,51.3,15.1,166.5
39.0,55.1,18.0,174.8
39.0,59.0,21.0,183.0
38.9,63.0,24.1,191.1
38.7,67.1,27.3,199.1
38.4,71.3,30.6,200
38.0,75.6,34.0,192.0
37.5,80.0,37.5,183.9
37.1,84.5,40.9,175.7
36.8,89.1,44.2,167.4
36.6,93.8,47.4,159.0
36.5,98.6,50.5,150.5
36.5,103.5,53.5,141.9
36.6,108.5,56.4,133.2
36.8,113.6,59.2,124.4
37.1,118.8,61.9,115.5
37.5,123.9,64.5,106.7
38.0,128.9,67.0,98.0
38.6,133.8,69.4,89.4
39.3,138.6,71.7,80.9
40.1,143.3,73.9,72.5
41.0,147.9,76.0,64.2
42.0,152.4,78.0,56.0
43.1,156.8,79.9,47.9
44.3,161.1,81.7,39.9
45.6,165.3,83.4,32.0
47.0,169.4,85.0,24.2
48.5,173.4,86.5,16.5
50.1,177.3,87.9,8.9
51.8,181.1,89.2,1.4
53.6,184.8,90.4,-6.0
55.5,188.4,91.5,-13.3
57.5,191.9,92.5,-20.5
when it should be:
21.9,2.0,-18.9,10.0
23.7,4.1,-17.7,19.9
25.4,6.3,-16.4,29.7
27.0,8.6,-15.0,39.4
28.5,11.0,-13.5,49.0
29.9,13.5,-11.9,58.5
31.2,16.1,-10.2,67.9
32.4,18.8,-8.4,77.2
33.5,21.6,-6.5,86.4
34.5,24.5,-4.5,95.5
35.4,27.5,-2.4,104.5
36.2,30.6,-0.2,113.4
36.9,33.8,2.1,122.2
37.5,37.1,4.5,130.9
38.0,40.5,7.0,139.5
38.4,44.0,9.6,148.0
38.7,47.6,12.3,156.4
38.9,51.3,15.1,164.7
39.0,55.1,18.0,172.9
39.0,59.0,21.0,181.0
38.9,63.0,24.1,189.0
38.7,67.1,27.3,196.9
38.4,71.3,30.6,200
38.0,75.6,34.0,192.1
37.5,80.0,37.5,184.1
37.1,84.5,40.9,176.0
36.8,89.1,44.2,167.8
36.6,93.8,47.4,159.5
36.5,98.6,50.5,151.1
36.5,103.5,53.5,142.6
36.6,108.5,56.4,134.0
36.8,113.6,59.2,125.3
37.1,118.8,61.9,116.5
37.5,123.9,64.5,107.8
38.0,128.9,67.0,99.2
38.6,133.8,69.4,90.7
39.3,138.6,71.7,82.3
40.1,143.3,73.9,74.0
41.0,147.9,76.0,65.8
42.0,152.4,78.0,57.7
43.1,156.8,79.9,49.7
44.3,161.1,81.7,41.8
45.6,165.3,83.4,34.0
47.0,169.4,85.0,26.3
48.5,173.4,86.5,18.7
50.1,177.3,87.9,11.2
51.8,181.1,89.2,3.8
53.6,184.8,90.4,-3.5
55.5,188.4,91.5,-10.7
57.5,191.9,92.5,-17.8
For some reason, which I am unable to locate, the floats in the last column are not quite right. They differ from the desired output by anything between 2 and 0.5 or so.
I have no idea why this is the case!
Thanks for any help!
| [
"You need to make a snapshot of the state and perform your calculations on the snapshot. If you move the particles around during the calculations as you are currently doing, you will get inconsistent results.\nSomething like this may work \nfrom copy import deepcopy\nfor iteration in range(times):\n i = 0\n ... | [
5
] | [] | [] | [
"floating_point",
"python",
"python_2.6"
] | stackoverflow_0003645185_floating_point_python_python_2.6.txt |
Q:
Why are mutable strings slower than immutable strings?
Why are mutable strings slower than immutable strings?
EDIT:
>>> import UserString
... def test():
... s = UserString.MutableString('Python')
... for i in range(3):
... s[0] = 'a'
...
... if __name__=='__main__':
... from timeit import Timer
... t = Timer("test()", "from __main__ import test")
... print t.timeit()
13.5236170292
>>> import UserString
... def test():
... s = UserString.MutableString('Python')
... s = 'abcd'
... for i in range(3):
... s = 'a' + s[1:]
...
... if __name__=='__main__':
... from timeit import Timer
... t = Timer("test()", "from __main__ import test")
... print t.timeit()
6.24725079536
>>> import UserString
... def test():
... s = UserString.MutableString('Python')
... for i in range(3):
... s = 'a' + s[1:]
...
... if __name__=='__main__':
... from timeit import Timer
... t = Timer("test()", "from __main__ import test")
... print t.timeit()
38.6385951042
i think it is obvious why i put s = UserString.MutableString('Python') on second test.
A:
In a hypothetical language that offers both mutable and immutable, otherwise equivalent, string types (I can't really think of one offhand -- e.g., Python and Java both have immutable strings only, and other ways to make one through mutation which add indirectness and therefore can of course slow things down a bit;-), there's no real reason for any performance difference -- for example, in C++, interchangeably using a std::string or a const std::string I would expect to cause no performance difference (admittedly a compiler might be able to optimize code using the latter better by counting on the immutability, but I don't know any real-world ones that do perform such theoretically possible optimizations;-).
Having immutable strings may and does in fact allow very substantial optimizations in Java and Python. For example, if the strings get hashed, the hash can be cached, and will never have to be recomputed (since the string can't change) -- that's especially important in Python, which uses hashed strings (for look-ups in sets and dictionaries) so lavishly and even "behind the scenes". Fresh copies never need to be made "just in case" the previous one has changed in the meantime -- references to a single copy can always be handed out systematically whenever that string is required. Python also copiously uses "interning" of (some) strings, potentially allowing constant-time comparisons and many other similarly fast operations -- think of it as one more way, a more advanced one to be sure, to take advantage of strings' immutability to cache more of the results of operations often performed on them.
That's not to say that a given compiler is going to take advantage of all possible optimizations, of course. For example, when a slice of a string is requested, there is no real need to make a new object and copy the data over -- the new slice might refer to the old one with an offset (and an independently stored length), potentially a great optimization for big strings out of which many slices are taken. Python doesn't do that because, unless particular care is taken in memory management, this might easily result in the "big" string being all kept in memory when only a small slice of it is actually needed -- but it's a tradeoff that a different implementation might definitely choose to perform (with that burden of extra memory management, to be sure -- more complex, harder-to-debug compiler and runtime code for the hypothetical language in question).
I'm just scratching the surface here -- and many of these advantages would be hard to keep if otherwise interchangeable string types could exist in both mutable and immutable versions (which I suspect is why, to the best of my current knowledge at least, C++ compilers actually don't bother with such optimizations, despite being generally very performance-conscious). But by offering only immutable strings as the primitive, fundamental data type (and thus implicitly accepting some disadvantage when you'd really need a mutable one;-), languages such as Java and Python can clearly gain all sorts of advantages -- performance issues being only one group of them (Python's choice to allow only immutable primitive types to be hashable, for example, is not a performance-centered design decision -- it's more about clarity and predictability of behavior for sets and dictionaries!-).
A:
I don't know if they are really a lot slower but they make thinking about programming easier a lot of the times, because the state of the object/string can't change. That's the most important property to immutability to me.
Furthermore you might assume that immutable string are faster because they have less state(which can change), which might mean lower memory consumption, CPU-cycles.
I also found this interesting article while googling which I would like to quote:
knowing that a string is immutable
makes it easy to lay it out at
construction time — fixed and
unchanging storage requirements
A:
with an immutable string, python can intern it and refer to it internally by it's address in memory. This means that to compare two strings, it only has to compare their addresses in memory (unless one of them isn't interned). Also, keep in mind that not all strings are interned. I've seen example of constructed strings that are not interned.
with mutable strings, string comparison would involve comparing them character by character and would also require either storing identical strings in different locations (malloc is not free) or adding logic to keep track of how many times a given string is referred to and making a copy for every mutation if there were more than one referrer.
It seems like python is optimized for string comparison. This makes sense because even string manipulation involves string comparison in most cases so for most use cases, it's the lowest common denominator.
Another advantage of immutable strings is that it makes it possible for them to be hashable which is a requirement for using them for dictionary keys. imagine a scenario where they were mutable:
s = 'a'
d = {s : 1}
s = s + 'b'
d[s] = ?
I suppose python could keep track of which dicts have which strings as keys and update all of their hashtables when a string was modified but that's just adding more overhead to dict insertion. It's not to far off the mark to say that you can't do anything in python without a dict insertion/lookup so that would be very very bad. It also adds overhead to string manipulation.
A:
The obvious answer to your question is that normal strings are implemented in C, while MutableString is implemented in Python.
Not only does every operation on a mutable string have the overhead of going through one or more Python function calls, but the implementation is essentially a wrapper round an immutable string - when you modify the string it creates a new immutable string and throws the old one away. You can read the source in the UserString.py file in your Python lib directory.
To quote the Python docs:
Note:
This UserString class from this module
is available for backward
compatibility only. If you are writing
code that does not need to work with
versions of Python earlier than Python
2.2, please consider subclassing directly from the built-in str type
instead of using UserString (there is
no built-in equivalent to
MutableString).
This module defines a class that acts
as a wrapper around string objects. It
is a useful base class for your own
string-like classes, which can inherit
from them and override existing
methods or add new ones. In this way
one can add new behaviors to strings.
It should be noted that these classes
are highly inefficient compared to
real string or Unicode objects; this
is especially the case for
MutableString.
(Emphasis added).
| Why are mutable strings slower than immutable strings? | Why are mutable strings slower than immutable strings?
EDIT:
>>> import UserString
... def test():
... s = UserString.MutableString('Python')
... for i in range(3):
... s[0] = 'a'
...
... if __name__=='__main__':
... from timeit import Timer
... t = Timer("test()", "from __main__ import test")
... print t.timeit()
13.5236170292
>>> import UserString
... def test():
... s = UserString.MutableString('Python')
... s = 'abcd'
... for i in range(3):
... s = 'a' + s[1:]
...
... if __name__=='__main__':
... from timeit import Timer
... t = Timer("test()", "from __main__ import test")
... print t.timeit()
6.24725079536
>>> import UserString
... def test():
... s = UserString.MutableString('Python')
... for i in range(3):
... s = 'a' + s[1:]
...
... if __name__=='__main__':
... from timeit import Timer
... t = Timer("test()", "from __main__ import test")
... print t.timeit()
38.6385951042
i think it is obvious why i put s = UserString.MutableString('Python') on second test.
| [
"In a hypothetical language that offers both mutable and immutable, otherwise equivalent, string types (I can't really think of one offhand -- e.g., Python and Java both have immutable strings only, and other ways to make one through mutation which add indirectness and therefore can of course slow things down a bit... | [
26,
3,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003644576_python.txt |
Q:
Ways to implement Flex [Bindable] in other languages
As you may know, ActionScript allows you to mark a variable as [Bindable], causing any changes to that variable to have immediate effect all over your application. Pretty neat.
How would you implement this feature in your favourite programming language? My first guess was to use events or wrapper classes, but I couldn't come up with a clean solution to this. I am especially interested in doing this with Python or JavaScript.
A:
You'd use the Observer Pattern.
| Ways to implement Flex [Bindable] in other languages | As you may know, ActionScript allows you to mark a variable as [Bindable], causing any changes to that variable to have immediate effect all over your application. Pretty neat.
How would you implement this feature in your favourite programming language? My first guess was to use events or wrapper classes, but I couldn't come up with a clean solution to this. I am especially interested in doing this with Python or JavaScript.
| [
"You'd use the Observer Pattern.\n"
] | [
1
] | [] | [] | [
"apache_flex",
"bindable",
"python"
] | stackoverflow_0003645598_apache_flex_bindable_python.txt |
Q:
In Google App Engine, how do I avoid creating duplicate entities with the same attribute?
I am trying to add a transaction to keep from creating two entities with the same attribute. In my application, I am creating a new Player each time I see a new Google user logged in. My current implementation occasionally creates duplicate players when multiple json calls are made by a new Google user within a few milliseconds. When I add the transaction like the one commented out here, I get various errors. What is the easiest way to ensure that I never create two player entities with the same user_id?
def get_player_from_user(self, user_id):
player = Player.all().filter('user_id =', user_id).get()
if not player:
#This can result in duplicate players with the same user_id being created.
player = self.create_new_player(user_id)
#This is what I'm trying to do.
#player = db.run_in_transaction(self.create_new_player, user_id=user_id)
return player
def create_new_player(self,user_id):
#Check one more time for an existing user_id match.
player = Player.all().filter('user_id =', user_id).get()
if player:
return player
player = Player()
player.user_id = user.user_id()
player.put()
return player
A:
Use the username (or other identifier) as the key name, and use get_or_insert to transactionally create a new entity or return the existing one. Sahid's code won't work, because without a transaction, a race condition is still possible.
A:
Maybe you can use key name and get_by_key_name is better than filter.
def create_new_player(self,user_id):
key_name = "player/%s" % user_id
player = Player.get_by_key_name (key_name)
if player is None:
player = Player (key_name=key_name, user_id=user_id)
player.put ()
return player
With the last comment of Nick, i have updated my code,
so the better solution is:
def create_new_player(self,user_id):
key_name = "player/%s" % user_id
player = Player.get_or_insert (key_name=key_name, user_id=user_id)
return player
| In Google App Engine, how do I avoid creating duplicate entities with the same attribute? | I am trying to add a transaction to keep from creating two entities with the same attribute. In my application, I am creating a new Player each time I see a new Google user logged in. My current implementation occasionally creates duplicate players when multiple json calls are made by a new Google user within a few milliseconds. When I add the transaction like the one commented out here, I get various errors. What is the easiest way to ensure that I never create two player entities with the same user_id?
def get_player_from_user(self, user_id):
player = Player.all().filter('user_id =', user_id).get()
if not player:
#This can result in duplicate players with the same user_id being created.
player = self.create_new_player(user_id)
#This is what I'm trying to do.
#player = db.run_in_transaction(self.create_new_player, user_id=user_id)
return player
def create_new_player(self,user_id):
#Check one more time for an existing user_id match.
player = Player.all().filter('user_id =', user_id).get()
if player:
return player
player = Player()
player.user_id = user.user_id()
player.put()
return player
| [
"Use the username (or other identifier) as the key name, and use get_or_insert to transactionally create a new entity or return the existing one. Sahid's code won't work, because without a transaction, a race condition is still possible.\n",
"Maybe you can use key name and get_by_key_name is better than filter.\n... | [
4,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003645582_google_app_engine_python.txt |
Q:
Simple RESTFUL client/server example in Python?
Is there an online resource that shows how to write a simple (but robust) RESTFUL server/client (preferably with authentication), written in Python?
The objective is to be able to write my own lightweight RESTFUL services without being encumbered by an entire web framework. Having said that, if there is a way to do this (i.e. write RESFUL services) in a lightweight manner using Django, I'd be equally interested.
Actually, coming to thing of it, I may even PREFER a Django based solution (provided its lightweight enough - i.e. does not bring the whole framework into play), since I will be able to take advantage of only the components I need, in order to implement better security/access to the services.
A:
Well, first of all you can use django-piston, as @Tudorizer already mentioned.
But then again, as I see it (and I might be wrong!), REST is more of a set of design guidelines, rather than a concrete API. What it essentially says is that the interaction with your service should not be based on 'things you can do' (typical RPC-style methods), but rather 'things, you can act on in predictable ways, organized in a certain way' (the 'resource' entity and http verbs).
That being said, you don't need anything extra to write REST-style services using django.
Consider the following:
# urlconf
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('',
url(r'^tickets$', 'myapp.views.tickets', name='tickets'),
url(r'^ticket/(?P<id>\d+)$', 'myapp.views.tickets', name='ticket'),
url(r'^ticket$', 'myapp.views.tickets', name='ticket'),
)
# views
def tickets(request):
tickets = Ticket.objects.all()
return render_to_response('tickets.html', {'tickets':tickets})
def ticket(request, id=None):
if id is not None:
ticket = get_object_or_404(Ticket, id=id)
if request.method == 'POST':
# create or update ticket here
else:
# just render the ticket (GET)
...
... and so on.
What matters is how your service is exposed to its user, not the library/toolkit/framework it uses.
A:
This one looks promising. http://parand.com/say/index.php/2009/04/30/django-piston-rest-framework-for-django/ I've used it before and it's pretty nifty. Having said that, it doesn't seem maintained recently.
| Simple RESTFUL client/server example in Python? | Is there an online resource that shows how to write a simple (but robust) RESTFUL server/client (preferably with authentication), written in Python?
The objective is to be able to write my own lightweight RESTFUL services without being encumbered by an entire web framework. Having said that, if there is a way to do this (i.e. write RESFUL services) in a lightweight manner using Django, I'd be equally interested.
Actually, coming to thing of it, I may even PREFER a Django based solution (provided its lightweight enough - i.e. does not bring the whole framework into play), since I will be able to take advantage of only the components I need, in order to implement better security/access to the services.
| [
"Well, first of all you can use django-piston, as @Tudorizer already mentioned.\nBut then again, as I see it (and I might be wrong!), REST is more of a set of design guidelines, rather than a concrete API. What it essentially says is that the interaction with your service should not be based on 'things you can do' ... | [
5,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003645543_django_python.txt |
Q:
How to get the original value of changed fields?
I'm using sqlalchemy as my orm, and use declarative as Base.
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
My question is, how do I know a user has been modified, and how to get the original values without query database again?
user = Session.query(User).filter_by(id=user_id).first()
# some operations on user
....
# how do I know if the user.name has been changed or not?
...
# How do get the original name?
Thanks in advance!
UPDATE
I found a method get_history can get the history value of a field, but I'm not sure if it is the correct method for my purpose.
from sqlalchemy.orm.attributes import get_history
user = Session.query(User).first()
print user.name # 'Jack'
print get_history(user, 'name') # ((),['Jack'],())
user.name = 'Mike'
print get_history(user, 'name') # (['Mike'], (),['Jack'])
So, we can check the value of get_history, but is it the best method?
A:
\To see if user has been modified you can check if user in session.dirty. If it is and you want to undo it, you can execute
session.rollback()
but be advised that this will rollback everything for the session to the last session.commit().
If you want to get the original values and memory serves me correctly, it's the second element of the tuple returned by the sqlalchemy.orm.attributes.get_history utility function. You would have to do
old_value = sqlalchemy.orm.attributes.get_history(user, 'attribute')[2]
for each attribute that you want.
| How to get the original value of changed fields? | I'm using sqlalchemy as my orm, and use declarative as Base.
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
My question is, how do I know a user has been modified, and how to get the original values without query database again?
user = Session.query(User).filter_by(id=user_id).first()
# some operations on user
....
# how do I know if the user.name has been changed or not?
...
# How do get the original name?
Thanks in advance!
UPDATE
I found a method get_history can get the history value of a field, but I'm not sure if it is the correct method for my purpose.
from sqlalchemy.orm.attributes import get_history
user = Session.query(User).first()
print user.name # 'Jack'
print get_history(user, 'name') # ((),['Jack'],())
user.name = 'Mike'
print get_history(user, 'name') # (['Mike'], (),['Jack'])
So, we can check the value of get_history, but is it the best method?
| [
"\\To see if user has been modified you can check if user in session.dirty. If it is and you want to undo it, you can execute\nsession.rollback()\n\nbut be advised that this will rollback everything for the session to the last session.commit().\nIf you want to get the original values and memory serves me correctly,... | [
13
] | [] | [] | [
"insert_update",
"python",
"sqlalchemy"
] | stackoverflow_0003645802_insert_update_python_sqlalchemy.txt |
Q:
How to dynamically update values to arguments in Python loop?
Python newbie here:
I'm writing a market simulation in Python using Pysage, and want to generate an arbitrary number of agents (either buyers or sellers) using the mgr.register_actor() function, as follows:
for name, maxValuation, endowment, id in xrange(5):
mgr.register_actor(Buyer(name="buyer001", maxValuation=100, endowment=500),"buyer001")
update name, maxValuation, endowment, id
What is a succinct, pythonic way to run that function call so that, each time the loop is run, the values of name, maxValuation, endowment, and id are changed, e.g. to name="buyer002", name="buyer003"...; maxValuation=95, maxValuation=90...; endowment=450, endowment=400...; "buyer002", "buyer003"... and so on.
I have tried different for-loops and list comprehensions, but haven't found a way yet to dynamically update the function arguments without running into type issues.
Thanks in advance!
A:
You can prepare the names, maxValuations, and endowments as lists (or iterators), then use zip to group corresponding elements together:
names=['buyer{i:0>3d}'.format(i=i) for i in range(1,6)]
maxValuations=range(100,75,-5)
endowments=range(500,250,-50)
for name, maxValuation, endowment in zip(names,maxValuations,endowments):
mgr.register_actor(
Buyer(name=name, maxValuation=maxValuation, endowment=endowment),name)
Regarding the format string, '{i:0>3d}':
I refer to this "cheat sheet" when I need to build a format string:
http://docs.python.org/library/string.html#format-string-syntax
replacement_field ::= "{" field_name ["!" conversion] [":" format_spec] "}"
field_name ::= (identifier|integer)("."attribute_name|"["element_index"]")*
attribute_name ::= identifier
element_index ::= integer
conversion ::= "r" | "s"
format_spec ::= [[fill]align][sign][#][0][width][.precision][type]
fill ::= <a character other than '}'>
align ::= "<" | ">" | "=" | "^"
"=" forces the padding to be placed after the sign (if any)
but before the digits. (for numeric types)
sign ::= "+" | "-" | " "
" " places a leading space for positive numbers
width ::= integer
precision ::= integer
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" |
"o" | "x" | "X" | "%"
So, it breaks down like this:
field_name
/
{i:0>3d}
\\\\
\\\`-type ("d" means integer)
\\`-width
\`-alignment (">" means right adjust)
`-fill character
| How to dynamically update values to arguments in Python loop? | Python newbie here:
I'm writing a market simulation in Python using Pysage, and want to generate an arbitrary number of agents (either buyers or sellers) using the mgr.register_actor() function, as follows:
for name, maxValuation, endowment, id in xrange(5):
mgr.register_actor(Buyer(name="buyer001", maxValuation=100, endowment=500),"buyer001")
update name, maxValuation, endowment, id
What is a succinct, pythonic way to run that function call so that, each time the loop is run, the values of name, maxValuation, endowment, and id are changed, e.g. to name="buyer002", name="buyer003"...; maxValuation=95, maxValuation=90...; endowment=450, endowment=400...; "buyer002", "buyer003"... and so on.
I have tried different for-loops and list comprehensions, but haven't found a way yet to dynamically update the function arguments without running into type issues.
Thanks in advance!
| [
"You can prepare the names, maxValuations, and endowments as lists (or iterators), then use zip to group corresponding elements together:\nnames=['buyer{i:0>3d}'.format(i=i) for i in range(1,6)]\nmaxValuations=range(100,75,-5)\nendowments=range(500,250,-50)\nfor name, maxValuation, endowment in zip(names,maxValuati... | [
4
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0003646142_for_loop_python.txt |
Q:
Why would one use accelerators with fastcgi for PHP?
I'm a newbie to web technology, and still on a learning curve.
Heard that, fastcgi would keep the compiled(interpreted) php code in memory, so why would one has to use op-code caching (apc or eaccelerators) for PHP?
But I never heard of any such accelerators for Python. I'd expect as python and php are both interpreted language, it makes me think that, there has to be a room for python accelerators ? pls correct me if I'm wrong.
Many thanks
A:
Unlike PHP, (C)Python does not throw the bytecode away after running it. When module.py is imported and there is no module.pyc, it is bytecode-compiled and the result is copied to module.pyc; is it already exists, compilation is skipped and the ready-made module.pyc is used. One can do the same thing for the main script manually, too.
As for
fastcgi would keep the compiled(interpreted) php code in memory, so why would one has to use op-code caching (apc or eaccelerators) for PHP?
I never head of this - FastCGI doesn't start a new process for each request (as opposed to plain old CGI, which starts basically starts the interpreter as a new process), but that's it. This benchmark shows that FastCGI doesn't perform any better than mod_php (i.e. interpreter embedded in the Apache process).
A:
PHP on its forgets a just-in-time compilation as soon as it has done with that file. This means PHP has to recompile the file every time it wants something from it. An OpCode cache (like you're talking about side-steps this and keeps PHP classes compiled in memory for a predetermined time).
Python on the other hand natively compiles things down a much faster interpretable code on their first run. You see all the .pyc files around your project, they're equivalent to PHP's OpCode.
PHP OpCode caches often bundle in other features (memory-resident data stores) and these are also provided out-the-box by Python.
There are a couple of "accelerators" for Python though. The most notable is Psyco that claims a "2x to 100x" speed improvement in ideal conditions. But this comes at a monstrously heavy cost of RAM and it only runs on i386 archs.
A:
Python is compiled to bytecode when executed (the .pyc files), and the bytecode is kept around, not discarded. The compiled python is used instead of the source if it is present. Therefore, there is no need for additional opcode caching in python as it is already built in.
| Why would one use accelerators with fastcgi for PHP? | I'm a newbie to web technology, and still on a learning curve.
Heard that, fastcgi would keep the compiled(interpreted) php code in memory, so why would one has to use op-code caching (apc or eaccelerators) for PHP?
But I never heard of any such accelerators for Python. I'd expect as python and php are both interpreted language, it makes me think that, there has to be a room for python accelerators ? pls correct me if I'm wrong.
Many thanks
| [
"Unlike PHP, (C)Python does not throw the bytecode away after running it. When module.py is imported and there is no module.pyc, it is bytecode-compiled and the result is copied to module.pyc; is it already exists, compilation is skipped and the ready-made module.pyc is used. One can do the same thing for the main ... | [
2,
2,
0
] | [] | [] | [
"fastcgi",
"php",
"python"
] | stackoverflow_0003646205_fastcgi_php_python.txt |
Q:
Python "ImportError: No module named" Problem
I'm running Python 2.6.1 on Windows XP SP3. My IDE is PyCharm 1.0-Beta 2 build PY-96.1055.
I'm storing my .py files in a directory named "src"; it has an __init__.py file that's empty except for an "__author__" attribute at the top.
One of them is called Matrix.py:
#!/usr/bin/env python
"""
"Core Python Programming" chapter 6.
A simple Matrix class that allows addition and multiplication
"""
__author__ = 'Michael'
__credits__ = []
__version__ = "1.0"
__maintainer__ = "Michael"
__status__ = "Development"
class Matrix(object):
"""
exercise 6.16: MxN matrix addition and multiplication
"""
def __init__(self, rows, cols, values = []):
self.rows = rows
self.cols = cols
self.matrix = values
def show(self):
""" display matrix"""
print '['
for i in range(0, self.rows):
print '(',
for j in range(0, self.cols-1):
print self.matrix[i][j], ',',
print self.matrix[i][self.cols-1], ')'
print ']'
def get(self, row, col):
return self.matrix[row][col]
def set(self, row, col, value):
self.matrix[row][col] = value
def rows(self):
return self.rows
def cols(self):
return self.cols
def add(self, other):
result = []
for i in range(0, self.rows):
row = []
for j in range(0, self.cols):
row.append(self.matrix[i][j] + other.get(i, j))
result.append(row)
return Matrix(self.rows, self.cols, result)
def mul(self, other):
result = []
for i in range(0, self.rows):
row = []
for j in range(0, other.cols):
sum = 0
for k in range(0, self.cols):
sum += self.matrix[i][k]*other.get(k,j)
row.append(sum)
result.append(row)
return Matrix(self.rows, other.cols, result)
def __cmp__(self, other):
"""
deep equals between two matricies
first check rows, then cols, then values
"""
if self.rows != other.rows:
return self.rows.cmp(other.rows)
if self.cols != other.cols:
return self.cols.cmp(other.cols)
for i in range(0, self.rows):
for j in range(0, self.cols):
if self.matrix[i][j] != other.get(i,j):
return self.matrix[i][j] == (other.get(i,j))
return True # if you get here, it means size and values are equal
if __name__ == '__main__':
a = Matrix(3, 3, [[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = Matrix(3, 3, [[6, 5, 4], [1, 1, 1], [2, 1, 0]])
c = Matrix(3, 3, [[2, 0, 0], [0, 2, 0], [0, 0, 2]])
a.show()
b.show()
c.show()
a.add(b).show()
a.mul(c).show()
I've created a new directory named "test" that also has an __init__.py file that's empty except for an "__author__" attribute at the top. I've created a MatrixTest.py to unit my Matrix class:
#!/usr/bin/env python
"""
Unit test case for Matrix class
See http://jaynes.colorado.edu/PythonGuidelines.html#module_formatting for Python coding guidelines
"""
import unittest #use my unittestfp instead for floating point
from src import Matrix # Matrix class to be tested
__author__ = 'Michael'
__credits__ = []
__license__ = "GPL"
__version__ = "1.0"
__maintainer__ = "Michael"
__status__ = "Development"
class MatrixTest(unittest.TestCase):
"""Unit tests for Matrix class"""
def setUp(self):
self.a = Matrix.Matrix(3, 3, [[1, 2, 3], [4, 5, 6], [7, 8, 9]])
self.b = Matrix.Matrix(3, 3, [[6, 5, 4], [1, 1, 1], [2, 1, 0]])
self.c = Matrix.Matrix(3, 3, [[2, 0, 0], [0, 2, 0], [0, 0, 2]])
def testAdd(self):
expected = Matrix.Matrix(3, 3, [[7, 7, 7], [5, 6, 7], [9, 9, 9]]) # need to learn how to write equals for Matrix
self.a.add(self.b)
assert self.a == expected
if __name__ == '__main__': #run tests if called from command-line
suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
unittest.TextTestRunner(verbosity=2).run(suite)
Yet when I try to run my MatrixTest I get this error:
C:\Tools\Python-2.6.1\python.exe "C:/Documents and Settings/Michael/My Documents/Projects/Python/learning/core/test/MatrixTest.py"
Traceback (most recent call last):
File "C:/Documents and Settings/Michael/My Documents/Projects/Python/learning/core/test/MatrixTest.py", line 8, in <module>
from src import Matrix # Matrix class to be tested
ImportError: No module named src
Process finished with exit code 1
Everything I've read tells me that having the init.py in all my directories should take care of this.
If someone could point out what I've missed I'd greatly appreciate it.
I'd also like advice on the best way to develop and maintain source and unit test classes. I'm thinking about this the way I usually do when I write Java: /src and /test directories, with identical package structures underneath. Is this "Pythonic" thinking, or should I consider another organization scheme?
UPDATE:
Thanks to those who have answered, here's the solution that worked for me:
Change import to from src import Matrix # Matrix class to be tested
Add sys.path as an environment variable to my unittest configuration, with ./src and ./test directories separated by semi-colon.
Change declarations in MatrixTest.py as shown.
A:
This is a bit of a guess, but I think you need to
change your PYTHONPATH environment variable to include the src and test directories.
Running programs in the src directory may have been working, because Python automatically inserts the directory of the script it is currently running into sys.path. So importing modules in src would have worked as long as you are also executing a script that resides in src.
But now that you are running a script from test, the test directory is automatically added to sys.path, while src is not.
All directories listed in PYTHONPATH get added to sys.path, and Python searches sys.path to find modules.
Also, if you say
from src import Matrix
then Matrix would refer to the package, and you'd need to say Matrix.Matrix to access the class.
A:
Regarding best practices, PycURL uses a tests directory at the same level as the main source code. On the other hand projects like Twisted or sorl-thumbnail use a test(s) subdirectory under the main source code.
The other half of the question has been already answered by ~unutbu.
| Python "ImportError: No module named" Problem | I'm running Python 2.6.1 on Windows XP SP3. My IDE is PyCharm 1.0-Beta 2 build PY-96.1055.
I'm storing my .py files in a directory named "src"; it has an __init__.py file that's empty except for an "__author__" attribute at the top.
One of them is called Matrix.py:
#!/usr/bin/env python
"""
"Core Python Programming" chapter 6.
A simple Matrix class that allows addition and multiplication
"""
__author__ = 'Michael'
__credits__ = []
__version__ = "1.0"
__maintainer__ = "Michael"
__status__ = "Development"
class Matrix(object):
"""
exercise 6.16: MxN matrix addition and multiplication
"""
def __init__(self, rows, cols, values = []):
self.rows = rows
self.cols = cols
self.matrix = values
def show(self):
""" display matrix"""
print '['
for i in range(0, self.rows):
print '(',
for j in range(0, self.cols-1):
print self.matrix[i][j], ',',
print self.matrix[i][self.cols-1], ')'
print ']'
def get(self, row, col):
return self.matrix[row][col]
def set(self, row, col, value):
self.matrix[row][col] = value
def rows(self):
return self.rows
def cols(self):
return self.cols
def add(self, other):
result = []
for i in range(0, self.rows):
row = []
for j in range(0, self.cols):
row.append(self.matrix[i][j] + other.get(i, j))
result.append(row)
return Matrix(self.rows, self.cols, result)
def mul(self, other):
result = []
for i in range(0, self.rows):
row = []
for j in range(0, other.cols):
sum = 0
for k in range(0, self.cols):
sum += self.matrix[i][k]*other.get(k,j)
row.append(sum)
result.append(row)
return Matrix(self.rows, other.cols, result)
def __cmp__(self, other):
"""
deep equals between two matricies
first check rows, then cols, then values
"""
if self.rows != other.rows:
return self.rows.cmp(other.rows)
if self.cols != other.cols:
return self.cols.cmp(other.cols)
for i in range(0, self.rows):
for j in range(0, self.cols):
if self.matrix[i][j] != other.get(i,j):
return self.matrix[i][j] == (other.get(i,j))
return True # if you get here, it means size and values are equal
if __name__ == '__main__':
a = Matrix(3, 3, [[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = Matrix(3, 3, [[6, 5, 4], [1, 1, 1], [2, 1, 0]])
c = Matrix(3, 3, [[2, 0, 0], [0, 2, 0], [0, 0, 2]])
a.show()
b.show()
c.show()
a.add(b).show()
a.mul(c).show()
I've created a new directory named "test" that also has an __init__.py file that's empty except for an "__author__" attribute at the top. I've created a MatrixTest.py to unit my Matrix class:
#!/usr/bin/env python
"""
Unit test case for Matrix class
See http://jaynes.colorado.edu/PythonGuidelines.html#module_formatting for Python coding guidelines
"""
import unittest #use my unittestfp instead for floating point
from src import Matrix # Matrix class to be tested
__author__ = 'Michael'
__credits__ = []
__license__ = "GPL"
__version__ = "1.0"
__maintainer__ = "Michael"
__status__ = "Development"
class MatrixTest(unittest.TestCase):
"""Unit tests for Matrix class"""
def setUp(self):
self.a = Matrix.Matrix(3, 3, [[1, 2, 3], [4, 5, 6], [7, 8, 9]])
self.b = Matrix.Matrix(3, 3, [[6, 5, 4], [1, 1, 1], [2, 1, 0]])
self.c = Matrix.Matrix(3, 3, [[2, 0, 0], [0, 2, 0], [0, 0, 2]])
def testAdd(self):
expected = Matrix.Matrix(3, 3, [[7, 7, 7], [5, 6, 7], [9, 9, 9]]) # need to learn how to write equals for Matrix
self.a.add(self.b)
assert self.a == expected
if __name__ == '__main__': #run tests if called from command-line
suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
unittest.TextTestRunner(verbosity=2).run(suite)
Yet when I try to run my MatrixTest I get this error:
C:\Tools\Python-2.6.1\python.exe "C:/Documents and Settings/Michael/My Documents/Projects/Python/learning/core/test/MatrixTest.py"
Traceback (most recent call last):
File "C:/Documents and Settings/Michael/My Documents/Projects/Python/learning/core/test/MatrixTest.py", line 8, in <module>
from src import Matrix # Matrix class to be tested
ImportError: No module named src
Process finished with exit code 1
Everything I've read tells me that having the init.py in all my directories should take care of this.
If someone could point out what I've missed I'd greatly appreciate it.
I'd also like advice on the best way to develop and maintain source and unit test classes. I'm thinking about this the way I usually do when I write Java: /src and /test directories, with identical package structures underneath. Is this "Pythonic" thinking, or should I consider another organization scheme?
UPDATE:
Thanks to those who have answered, here's the solution that worked for me:
Change import to from src import Matrix # Matrix class to be tested
Add sys.path as an environment variable to my unittest configuration, with ./src and ./test directories separated by semi-colon.
Change declarations in MatrixTest.py as shown.
| [
"This is a bit of a guess, but I think you need to \nchange your PYTHONPATH environment variable to include the src and test directories.\nRunning programs in the src directory may have been working, because Python automatically inserts the directory of the script it is currently running into sys.path. So importing... | [
17,
1
] | [] | [] | [
"pycharm",
"python",
"unit_testing"
] | stackoverflow_0003646307_pycharm_python_unit_testing.txt |
Q:
Is it Pythonic to mimic method overloading?
Is it pythonic to mimic method overloading as found in statically typed languages? By that I mean writing a function that checks the types of its arguments and behaves differently based on those types.
Here is an example:
class EmployeeCollection(object):
@staticmethod
def find(value):
if isinstance(value, str):
#find employee by name and return
elif isinstance(value, int):
#find employee by employee number and return
else:
raise TypeError()
A:
Not really, since you lose the ability to use types that are not-quite-that-but-close-enough. Create two separate methods (find_by_name() and find_by_number()) instead.
A:
Not very Pythonic, except perhaps, in 2.6 or better, if all the checks rely on the new abstract base classes, which are intended in part exactly to facilitate such use. If you ever find yourself typechecking for concrete classes, then you know you're making your code fragile and curtailing its use.
So, for example, checking if you have an instance of numbers.Integral is not too bad -- that new ABC exists in good part exactly to ease such checking. Checking if you have an instance of int is a disaster, ruling out long, gmpy.mpz, and a bazillion other kinds of integer-like numbers, to absolutely no good purpose: never check for concrete classes!
Strings are a difficult case, but the basestring abstract class (not one of the new kind of ABCs) is a possibility. A bit too restrictive, perhaps, but if you're using other ABCs around it, it might kinda, sorta work, if you really have to. Most definitely not str -- why ever rule out unicode?!
A:
No, type checking here isn't Pythonic. Another option if you don't fancy multiple methods is to stick with one method but use multiple parameters:
def find(name=None, employee_number=None):
if sum(x != None for x in (name, employee_number)) != 1:
#raise exception - exactly one value should be passed in
if name is not None:
#find employee by name and return
if employee_number is not None:
#find employee by employee number and return
When used the intent is as obvious as with multiple methods:
employee1 = x.find(name="John Smith")
employee2 = x.find(employee_number=90210)
A:
I would say yes, it is 'Pythonic' And there are examples to back this up (which the other posters have not given). To answer this properly there should be examples!
From python core:
string.startswith() It accepts either a string or a tuple (of strings).
string.endswith()
In pymongo:
find_one() accepts either a dict object to lookup, or it will use another other object as the id.
Sorry I don't know more, but I think there are MANY examples of methods that behave differently according to the parameters given. That is part of the beauty of not enforcing types.
A:
A more pythonic way of getting to this kind of functionality is to just try and use it in the preferred way (whatever that might mean) and if the argument doesn't support that, try an alternative.
Here'd two ways to do that:
class EmployeeCollection(object):
def find(value):
try:
#find employee by name and return
catch:
try:
#find employee by employee number and return
catch:
raise TypeError()
but thats kind of yucky. here's how I usually do this:
class EmployeeCollection(object):
def find(value):
if hasattr(value, 'join'):
#find employee by name and return
elif hasattr(value, '__div__'):
#find employee by employee number and return
else:
raise TypeError()
In reality, the actual attribute I'd check for depends on what happens in those comments, I'll prefer to check for an attribute that I actually use.
| Is it Pythonic to mimic method overloading? | Is it pythonic to mimic method overloading as found in statically typed languages? By that I mean writing a function that checks the types of its arguments and behaves differently based on those types.
Here is an example:
class EmployeeCollection(object):
@staticmethod
def find(value):
if isinstance(value, str):
#find employee by name and return
elif isinstance(value, int):
#find employee by employee number and return
else:
raise TypeError()
| [
"Not really, since you lose the ability to use types that are not-quite-that-but-close-enough. Create two separate methods (find_by_name() and find_by_number()) instead.\n",
"Not very Pythonic, except perhaps, in 2.6 or better, if all the checks rely on the new abstract base classes, which are intended in part ex... | [
13,
13,
5,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003642748_python.txt |
Q:
Neural Network, python
I am trying to write a simple neural network that can come up with weights to for, say, the y=x function. Here's my code:
http://codepad.org/rPdZ7fOz
As you can see, the error level never really goes down much. I tried changing the momentum and learning rate but it did not help much. Is my number of input, hidden and output correct for what I want to do? If not, what should it be? If so, what else could be wrong?
A:
You're attempting to train the network to give output values 1,2,3,4 as far as I understood. Yet, at the output you use a sigmoid (math.tanh(..)) whose values are always between -1 and 1.
So the output of your Neural network is always between -1 and 1 and thus you always get a large error when trying to fit output values outside that range.
(I just checked that when scaling your input and output values by 0.1, there seems to be a nice training progress and I get at the end:
error 0.00025
)
The Neural Network you're using is useful if you want to do classification (e.g. assign the data point to class A if the NN output is < 0 or B if it is > 0). It looks like what you want to do is regression (fit a real-valued function).
You can remove the sigmoid at the output node but you will have to slightly modify your backpropagation procedure to take this into account.
| Neural Network, python | I am trying to write a simple neural network that can come up with weights to for, say, the y=x function. Here's my code:
http://codepad.org/rPdZ7fOz
As you can see, the error level never really goes down much. I tried changing the momentum and learning rate but it did not help much. Is my number of input, hidden and output correct for what I want to do? If not, what should it be? If so, what else could be wrong?
| [
"You're attempting to train the network to give output values 1,2,3,4 as far as I understood. Yet, at the output you use a sigmoid (math.tanh(..)) whose values are always between -1 and 1. \nSo the output of your Neural network is always between -1 and 1 and thus you always get a large error when trying to fit outp... | [
2
] | [] | [] | [
"backpropagation",
"neural_network",
"python"
] | stackoverflow_0003644795_backpropagation_neural_network_python.txt |
Q:
Abstract Django Application from "Project"
I'm struggling to work out how best to do what I think I want to do - now it may be I don't have a correct understanding of what's best practice, so if not, feel free to howl at me etc.
Basically, my question is, how do I abstract application functionality correctly, said functionality being found in an application that is part of a project?
To put some context on this (this is not far away from what I'm trying to achieve):
Suppose, I am building a website. My website has a look and feel and I've defined a base.html piece of boilerplate and various css-items in a model-less django app.
Now, I'm also writing a django blog application. I know how to include it so that the models appear in my current application and I'm more than happy that I can use any method I like from the various packages and manipulate the models and do thing all python with it.
What I don't understand is how to deal with views. It seems counter-intuitive to have the models stored elsewhere but have to build the user interface in my current project (and by implication any subsequent project). So, I thought, fine, include urls from my app folder in my project, done.
Then of course I have to write views, which is fine. I can do that.
What I can't get my head around is how templates fit in: in my app, I want to serve a template like this:
<div class="entry">
<a href=""><h2>{{ entry.Title }}</h2></a>
<p>Published on: {{ entry.date_published|date:"j F Y" }}</p>
{{ entry.body_html }}
</div>
<a href="">X comments.</a> <a href=""">Add Comment</a> <a href="">Link</a>
<div id="commentdiv">
{% if comments %}
<ul id="commentlist">
{% for comment in Comments %}
<li></li>
{% endfor %}
</ul>
{% else %}
<p>There are no comments on this entry.</p>
{% endif %}
</div>
for viewing an entry, so on my site I go to sitename.com/blog/...someparameters.../entryname' where blog is theincludeinurls.py` of the root project in question. All fine and well, but how do I also attach the boilerplate from that project i.e. the look and feel? I could go all out and design a base template for the blog application, fair enough, but what about navigation etc? I might want to include the same header on every page even if the content is fairly diverse.
Now, I'm aware of the {% extends "template" %} directive and {% include template %} directive. Why these don't work as far as I understand it:
{% extends %} - how do I know/provide what I want to extend from the root project? If you can provide a mechanism for this I think it would solve the problem very well.
{% include %} - implies I have to provide views for the blog in a bootstrap application in the root project. I really don't want to do this - I might as well move the entire project into that if that's the case.
So my question is, how do I put it all together?
Edit: I think this question is quite similar to what I'm asking and have noted the answers. However, they're still don't satisfy.
A:
If I understand your problem correctly, then I would suggest doing a Custom Template Tag. In it you can do anything you want: use 0 or more args to the tag to get at and manipulate arbitrary objects, and then invoke the template engine "by hand" to get a snippet to return. E.g.
[...]
t = loader.get_template('sometemplate.html')
c = Context({
'my_data': my_data, # or whatever
})
return t.render(c) # this gets inserted into the invoking template
If you don't want to have the various "main templates" of the site do a {% load ... %} then you can stick something like the following in the __init__.py of the app directory:
from django import template
template.add_to_builtins('myapp.templatetags.myapptags')
Which makes it available anywhere in the site, just like any other built-in.
A:
If you want to use template inheritance with django in a way that makes sense, you do not only need to use the {% extends %} tag but also the {% block %}tag! Specify in your base template the blocks that your app needs to replace: E.g.:
<html>
<body>
<div id="content">
{% block "content" %}
{% endblock %}
</div>
</body>
</html>
You can then easily fill the content of the div with your app with template inheritance:
{% extends "base.html" %}
{% block "content" %}
The content generated by your app.
{% endblock %}
You should keep in mind that also Django's template language tries to fulfill the concept of not repeating yourself, so try to avoid repeating block's with inheritance / inclusion, it will give you a project that is much nicer to maintain!
A:
The typical way to do this is to use a base template, extend it in your app and replace any blocks you like with your app's content, and use template tags to bring in content from other apps.
For example:
base.html (in your project's templates):
<html>
<head>
<title>{% block "title" %}Default title{% endblock %}</title>
</head>
<body>
<div id="nav">{% block "nav" %}{% endblock %}</div>
<div id="content">{% block "content" %}{% endblock %}</div>
</body>
</html>
template_name.html (in the app's templates):
{% extends "base.html" %}
{% load other_app_tags %}
{% block "nav" %}
{% other_app_nav_tag %}
{% endblock %}
{% block "content" %}
lotsa good junk.
{% endblock %}
other_app_tags.py (in the other app's templatetags dir):
from django import template
register = template.Library()
@register.inclusion_tag('navigation.html')
def other_app_nav_tag():
# You could give this tag arguments to change how it behaves
return {
'links': {
'Home': '/home'
}
}
navigation.html (in the other app's templates):
<ul>
{% for text, target in links %}
<li><a href="{{ target }}">{{ text }}</a></li>
{% endfor %}
</ul>
This uses inclusion tags to render from your other app's templates. It's a good way to contain templates to their own relevant apps and still make them available throughout the site.
| Abstract Django Application from "Project" | I'm struggling to work out how best to do what I think I want to do - now it may be I don't have a correct understanding of what's best practice, so if not, feel free to howl at me etc.
Basically, my question is, how do I abstract application functionality correctly, said functionality being found in an application that is part of a project?
To put some context on this (this is not far away from what I'm trying to achieve):
Suppose, I am building a website. My website has a look and feel and I've defined a base.html piece of boilerplate and various css-items in a model-less django app.
Now, I'm also writing a django blog application. I know how to include it so that the models appear in my current application and I'm more than happy that I can use any method I like from the various packages and manipulate the models and do thing all python with it.
What I don't understand is how to deal with views. It seems counter-intuitive to have the models stored elsewhere but have to build the user interface in my current project (and by implication any subsequent project). So, I thought, fine, include urls from my app folder in my project, done.
Then of course I have to write views, which is fine. I can do that.
What I can't get my head around is how templates fit in: in my app, I want to serve a template like this:
<div class="entry">
<a href=""><h2>{{ entry.Title }}</h2></a>
<p>Published on: {{ entry.date_published|date:"j F Y" }}</p>
{{ entry.body_html }}
</div>
<a href="">X comments.</a> <a href=""">Add Comment</a> <a href="">Link</a>
<div id="commentdiv">
{% if comments %}
<ul id="commentlist">
{% for comment in Comments %}
<li></li>
{% endfor %}
</ul>
{% else %}
<p>There are no comments on this entry.</p>
{% endif %}
</div>
for viewing an entry, so on my site I go to sitename.com/blog/...someparameters.../entryname' where blog is theincludeinurls.py` of the root project in question. All fine and well, but how do I also attach the boilerplate from that project i.e. the look and feel? I could go all out and design a base template for the blog application, fair enough, but what about navigation etc? I might want to include the same header on every page even if the content is fairly diverse.
Now, I'm aware of the {% extends "template" %} directive and {% include template %} directive. Why these don't work as far as I understand it:
{% extends %} - how do I know/provide what I want to extend from the root project? If you can provide a mechanism for this I think it would solve the problem very well.
{% include %} - implies I have to provide views for the blog in a bootstrap application in the root project. I really don't want to do this - I might as well move the entire project into that if that's the case.
So my question is, how do I put it all together?
Edit: I think this question is quite similar to what I'm asking and have noted the answers. However, they're still don't satisfy.
| [
"If I understand your problem correctly, then I would suggest doing a Custom Template Tag. In it you can do anything you want: use 0 or more args to the tag to get at and manipulate arbitrary objects, and then invoke the template engine \"by hand\" to get a snippet to return. E.g.\n[...]\nt = loader.get_template('s... | [
1,
0,
0
] | [] | [] | [
"django",
"django_templates",
"django_views",
"python"
] | stackoverflow_0003646112_django_django_templates_django_views_python.txt |
Q:
When to use WSGI middleware?
I write a router that takes the path of a request, match it against a regex and calls a WSGI handler, if the regex matches. The dict with the matching capturing groups is added to the envrion. Is it bad style to modify the environ with WSGI middleware?
But is that what WSGI middleware was invented for? I've just read WSGI Middleware Considered Harmful and wonder whether I should rewrite my router to be no longer a middleware. An application becomes dependend on my middleware, if it uses the dict with capturing groups. On the other hand no application has to use this additional dict. I could also forego the path param extraction and reduce the router to the routing, but then each application has to rerun the regex a second time for path parameter extraction.
So what to do:
leaving as is; with routing, path param extraction and environ manipulation
make the router a WSGI application and the current WSGI applications framework specific handlers
reduce the router to routing and extract perform regex matching a second time for path parameter extraction in the application to which the request was routed
A:
If you add things to the environ and then use those things in applications, without any fallbacks, then you have to some degree bound the application to the middleware.
In this particular case there is a convention for how to add those captured values to the environ: wsgiorg.routing_args. So while you would be putting references to this capturing into your application, it's not an entirely ad hoc communication.
(Though you can certainly overuse middleware, I consider that particular article to overstate the case; middleware can be a good abstraction to consider, implement, and test different pieces of an application separately, even if initially those pieces are implemented for a singular goal by a single person)
| When to use WSGI middleware? | I write a router that takes the path of a request, match it against a regex and calls a WSGI handler, if the regex matches. The dict with the matching capturing groups is added to the envrion. Is it bad style to modify the environ with WSGI middleware?
But is that what WSGI middleware was invented for? I've just read WSGI Middleware Considered Harmful and wonder whether I should rewrite my router to be no longer a middleware. An application becomes dependend on my middleware, if it uses the dict with capturing groups. On the other hand no application has to use this additional dict. I could also forego the path param extraction and reduce the router to the routing, but then each application has to rerun the regex a second time for path parameter extraction.
So what to do:
leaving as is; with routing, path param extraction and environ manipulation
make the router a WSGI application and the current WSGI applications framework specific handlers
reduce the router to routing and extract perform regex matching a second time for path parameter extraction in the application to which the request was routed
| [
"If you add things to the environ and then use those things in applications, without any fallbacks, then you have to some degree bound the application to the middleware.\nIn this particular case there is a convention for how to add those captured values to the environ: wsgiorg.routing_args. So while you would be p... | [
5
] | [] | [] | [
"python",
"wsgi"
] | stackoverflow_0003646237_python_wsgi.txt |
Q:
Removing SOCKS 4/5 proxy
This question is sort of the opposite of this:
How can I use a SOCKS 4/5 proxy with urllib2?
Let's say I use a SOCKS 5 proxy using the method accepted in that question. How would I revert it back to no proxy in the same process?
i.e
start process
use proxy
..
remove proxy
...
Maybe there is a better way to use the proxy so that it's easier to remove it later?
A:
Abra kadabra
import socks,socket,urllib2
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 8080)
temp = socket.socket
socket.socket = socks.socksocket
print urllib2.urlopen('http://www.google.com').read() // Proxy
socket.socket=temp
print urllib2.urlopen('http://www.google.com').read() // No proxy
| Removing SOCKS 4/5 proxy | This question is sort of the opposite of this:
How can I use a SOCKS 4/5 proxy with urllib2?
Let's say I use a SOCKS 5 proxy using the method accepted in that question. How would I revert it back to no proxy in the same process?
i.e
start process
use proxy
..
remove proxy
...
Maybe there is a better way to use the proxy so that it's easier to remove it later?
| [
"Abra kadabra\nimport socks,socket,urllib2\nsocks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, \"127.0.0.1\", 8080)\ntemp = socket.socket\nsocket.socket = socks.socksocket \nprint urllib2.urlopen('http://www.google.com').read() // Proxy\nsocket.socket=temp\nprint urllib2.urlopen('http://www.google.com').read() // No p... | [
11
] | [] | [] | [
"proxy",
"python",
"sockets"
] | stackoverflow_0003632821_proxy_python_sockets.txt |
Q:
Best practice for a recursive console tool in Python
What is the best practice (interface and implementation) for a command line tool
that processes selected files in a directory tree?
I give an example that comes to my mind, but I am looking for a 'best practice':
flipcase foo.txt foo2.txt
could process foo.txt and save the result as foo2.txt.
flipcase -rv *.txt
could process all text files in the current directory.
-r or --recursive will include all subdirectories.
-v will print some infos to stdout while processing.
One problem that I see with this example is, that the *.txt argument is
sometimes expanded by the shell (Unix and Vista), so I can't apply this pattern
when walking sub directories.
I guess the reason is, that on Unix such tools are comined with a call to find,
but this seems not to be common on Windows. It also makes it hard to print a
summary at the end.
Requirements:
MUST run on Unix, Windows XP, Windows 7 and Mac
SHOULD follow common conventions on these platforms.
(Yes, I know. But I am looking for a reasonable compromise.
For example it's Ok to use - instead of / on Windows.)
SHOULD not rely on a separate find command, like grep does.
MUST work for single files, file patterns and patterns in directory
hierarchies.
SHOULD be build with standard Python libs, e.g. OptionParser and os.walk.
COULD handle multiple patterns, e.g. *.txt,*.html.
Other questions on design decisions:
What should this tool return (status code)?
Which ctrl-keys should this tool handle, and in what way?
Should stdin be supported instead of a single file? Configurable or
auto-detect?
Should output redirection be supported? Configurable or auto-detect?
How deal with debug output in this case?
Should the pattern be glob syntax, or a regular expression?
Is there a common pattern syntax that supports recursion?
Maybe recursive:*.txt
In this case the -r option would not be neccesary.
What is best practice to create backups of modified files?
Option -b, or rather have backups by default and add --no-backup option
For single files it should be possible to specify a target file name. How?
What status info should be printed, and hot configure this?
Should it be verbose by default and we allow -q for quiet?
Or always print a little bit and allow -v (or -vv) to boost this or -q to
shut up completely?
I don't really expect to get one single right answer, but may be a handful of
thoughts and pointers to good sample projects.
A:
In my experience, the best starting point is to build a tool that follows basic Unix principles -- namely, to read from standard input and write to standard output. This allows people to use your tool in a flexible way:
flipcase input.txt > output.txt
othercommand | flipcase > output.txt
flipcase | othercommand > ouput.txt
flipcase input1.txt input2.txt > output.txt
The next feature might be in-place editing:
# Modify input files directly.
flipcase -i input.txt
# Create backup copies before modifying originals.
flipcase -i --backup-suffix '_BAK' input.txt
flipcase -i --backup-prefix 'BAK_' input.txt
# Regex for power users.
flipcase -i --backup-regex 's/foo/bar/' input.txt
In verbose mode, the tool should not write to standard output, because that would conflict with the core principles above. It should write to standard error or a user-defined log file.
flipcase -v input.txt > output.txt
flipcase -v log.txt input.txt > output.txt
After that, you add recursive behavior. The direction is less clear-cut here, but I'll toss out a few ideas. In the typical recursive case, the program's arguments are probably directories, and the user would need to supply additional options to define various types of filtering behavior (that is, which types of files to process).
flipcase -r -i --backup-suffix '_BAK' --filter-glob '*.txt' dir1 dir2
flipcase -r -i --backup-suffix '_BAK' --filter-glob '*.txt' --filter-glob 'log*.dat' dir
flipcase -r -i --backup-suffix '_BAK' --filter-regex 'log\w+\.(txt|log)$' dir1 dir2
# Don't do in-place editing. Instead create new files within the structure.
flipcase -r --newname-suffix '_NEW' --filter-glob '*.txt' dir1 dir2
flipcase -r --newname-regex 's/\.txt$/_new.txt/' --filter-glob '*.txt' dir1 dir2
# Create the backups or the new files in a parallel directory
# structure rather than within the original structure.
flipcase -r -i --backup-tree 'backup_dir' --filter-glob '*.txt' dir1 dir2
flipcase -r -i --new-tree 'newfiles_dir' --filter-glob '*.txt' dir1 dir2
A:
What is the best practice (interface
and implementation) for a command line
tool that processes selected files in
a directory tree?
I don't think there's a single standard or "best practice" when it comes to the implementation of a command line tool. Although, you'll gain lots of insights by looking at and experimenting with well built tools like the GNU coreutils for example.
Also, I think you're looking for something like this as well: http://www.gnu.org/prep/standards/html_node/Command_002dLine-Interfaces.html
Reading and experimenting about the Unix way of doing this actually addresses many of your concerns regarding design decisions.
One problem that I see with this
example is, that the *.txt argument is
sometimes expanded by the shell (Unix
and Vista), so I can't apply this
pattern when walking sub directories.
In Unix, the * is automatically expanded. I'm not sure about Windows but if I'm not mistaken, * is not expanded so you can simply use glob.glob(sys.argv[1]). A workaround for Unix would be to escape the wildcard but there must be a better way.
A:
To address the globbing part of your question, the odd man out in your list is really supporting Windows. The UNIX way, and also a good way, to do it is to let the shell handle the globbing. You just get a list of files. I know no UNIX tool what does its own globbing (in basic cases like this). I'd suggest you don't do it yourself either, but rely on the shell.
On Windows, you could refer people to using a shell with Cygwin, or something like that. Of course, Windows users usually eschew the command line, so if you build a GUI they'll be happy too.
That doesn't cover your -r switch. But it gets difficult there. Do you want to provide to users the ability to specify "all files in subdirectories that have the extension .txt"? Note that modern shells like ZSH can do globs that recurse into directories, like:
rm **/*.tmp
and, as you say, you can always use find instead. So a recommendation here really needs to factor in the specifics of your tool. rsync benefits from implementing its own -r switch, but an hypothetical flipcase probably wouldn't.
A:
Recursive processing is usually done using os.path.walk, but you can create your own version to use Python generators which is much more command line friendly: piping will get the output as it's processed. Here is a tested and documented proof of concept.
With Python 3, you don't have to do it, as it provides os.walk that create a generator.
Then after, follow FM advices to create the CLI interface using optparse.
| Best practice for a recursive console tool in Python | What is the best practice (interface and implementation) for a command line tool
that processes selected files in a directory tree?
I give an example that comes to my mind, but I am looking for a 'best practice':
flipcase foo.txt foo2.txt
could process foo.txt and save the result as foo2.txt.
flipcase -rv *.txt
could process all text files in the current directory.
-r or --recursive will include all subdirectories.
-v will print some infos to stdout while processing.
One problem that I see with this example is, that the *.txt argument is
sometimes expanded by the shell (Unix and Vista), so I can't apply this pattern
when walking sub directories.
I guess the reason is, that on Unix such tools are comined with a call to find,
but this seems not to be common on Windows. It also makes it hard to print a
summary at the end.
Requirements:
MUST run on Unix, Windows XP, Windows 7 and Mac
SHOULD follow common conventions on these platforms.
(Yes, I know. But I am looking for a reasonable compromise.
For example it's Ok to use - instead of / on Windows.)
SHOULD not rely on a separate find command, like grep does.
MUST work for single files, file patterns and patterns in directory
hierarchies.
SHOULD be build with standard Python libs, e.g. OptionParser and os.walk.
COULD handle multiple patterns, e.g. *.txt,*.html.
Other questions on design decisions:
What should this tool return (status code)?
Which ctrl-keys should this tool handle, and in what way?
Should stdin be supported instead of a single file? Configurable or
auto-detect?
Should output redirection be supported? Configurable or auto-detect?
How deal with debug output in this case?
Should the pattern be glob syntax, or a regular expression?
Is there a common pattern syntax that supports recursion?
Maybe recursive:*.txt
In this case the -r option would not be neccesary.
What is best practice to create backups of modified files?
Option -b, or rather have backups by default and add --no-backup option
For single files it should be possible to specify a target file name. How?
What status info should be printed, and hot configure this?
Should it be verbose by default and we allow -q for quiet?
Or always print a little bit and allow -v (or -vv) to boost this or -q to
shut up completely?
I don't really expect to get one single right answer, but may be a handful of
thoughts and pointers to good sample projects.
| [
"In my experience, the best starting point is to build a tool that follows basic Unix principles -- namely, to read from standard input and write to standard output. This allows people to use your tool in a flexible way:\nflipcase input.txt > output.txt\nothercommand | flipcase > output.txt\nflipcase | othercommand... | [
2,
1,
1,
0
] | [] | [] | [
"command_line",
"python"
] | stackoverflow_0003646620_command_line_python.txt |
Q:
Why does Python (with twill) not want to log me in to a Yahoo mail box here?
Can anyone, please, explain to me what's going on here. It seems that Python refuses to work (with twill) when I am trying to log in to my mailbox on Yahoo:
Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
****************************************************************
Personal firewall software may warn about the connection IDLE
makes to its subprocess using this computer's internal loopback
interface. This connection is not visible on any external
interface and no data is sent to or received from the Internet.
****************************************************************
IDLE 1.2.4
>>> import twill
>>> twill.shell.main()
-= Welcome to twill! =-
current page: *empty page*
>> go http://us.yahoo.com
==> at http://us.yahoo.com
current page: http://us.yahoo.com
>> follow Mail
==> at https://login.yahoo.com/config/login_verify2?.intl=us&.src=ym
current page: https://login.yahoo.com/config/login_verify2?.intl=us&.src=ym
>> showforms
Form name=login_form (#1)
## ## __Name__________________ __Type___ __ID________ __Value__________________
1 .tries hidden (None) 1
2 .src hidden (None) ym
3 .md5 hidden (None)
4 .hash hidden (None)
5 .js hidden (None)
6 .last hidden (None)
7 promo hidden (None)
8 .intl hidden (None) us
9 .bypass hidden (None)
10 .partner hidden (None)
11 .u hidden (None) 68gre5567rq16
12 .v hidden (None) 0
13 .challenge hidden (None) 9wKUoOWDdP5Fho0kPfqPKEhPZBdK
14 .yplus hidden (None)
15 .emailCode hidden (None)
16 pkg hidden (None)
17 stepid hidden (None)
18 .ev hidden (None)
19 hasMsgr hidden (None) 0
20 .chkP hidden (None) Y
21 .done hidden (None) http://mail.yahoo.com
22 .pd hidden (None) ym_ver=0&c=&ivt=&sg=
23 pad hidden pad 6
24 aad hidden aad 6
25 login text username
26 passwd password passwd
27 .persistent checkbox persistent [] of ['y']
28 1 .save submi ... .save
current page: https://login.yahoo.com/config/login_verify2?.intl=us&.src=ym
>> fv 1 login *****************
current page: https://login.yahoo.com/config/login_verify2?.intl=us&.src=ym
>> fv 1 passwd ***************
current page: https://login.yahoo.com/config/login_verify2?.intl=us&.src=ym
>> submit
Note: submit is using submit button: name=".save", value=""
Following HTTP-EQUIV=REFRESH to http://us.mg5.mail.yahoo.com/dc/launch?.gx=1&.rand=b3a02cc8lb0aa
current page: http://us.mg5.mail.yahoo.com/dc/launch?.gx=1&.rand=b3a02cc8lb0aa
>> info
Page information:
URL: http://us.mg5.mail.yahoo.com/dc/launch?.gx=1&.rand=b3a02cc8lb0aa
HTTP code: 200
Content type: text/html; charset=utf-8 (HTML)
Page title: Yahoo! Mail
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
twill.shell.main()
File "C:\Python25\Lib\site-packages\twill\shell.py", line 383, in main
shell.cmdloop(welcome_msg)
File "C:\Python25\lib\cmd.py", line 142, in cmdloop
stop = self.onecmd(line)
File "C:\Python25\lib\cmd.py", line 219, in onecmd
return func(arg)
File "C:\Python25\Lib\site-packages\twill\shell.py", line 42, in do_cmd
print '\nERROR: %s\n' % (str(e),)
File "C:\Python25\lib\HTMLParser.py", line 59, in __str__
result = self.msg
AttributeError: 'ParseError' object has no attribute 'msg'
>>>
Update 1:
(this update is my answer to Robus)
Hello, Robus!!!
First of all, I assume it was a typo when You wrote:
Here's what I did: Went to
C:\Python26\Lib\site-packages\twill-0.9-py2.6.egg\twill\other_packages\
I think You meant this path: "C:\Python26\Lib\site-packages\twill\other_packages". Otherwise, I can't see any such folder/directory there named "twill-0.9-py2.6.egg" - there is only a file with this name (the one that I think was downloaded during the installation of mechanize.) Please tell me if my assumption is wrong - I may well be not seeing something very obvious here as I am just a newbie.
So, following Your instructions, I did this:
I found "C:\Python25\Lib\site-packages\twill\other_packages_mechanize_dist" on my computer (as You can see, I don't have python26, but rather python 25 installed - that might also be a problem)
Changed its name to "_mechanize_dist_backup" (the full path now being "C:\Python25\Lib\site-packages\twill\other_packages_mechanize_dist_backup")
Copied my downloaded and unzipped "mechanize-0.2.2" into "C:\Python25\Lib\site-packages\twill\other_packages" (the full path being "C:\Python25\Lib\site-packages\twill\other_packages\mechanize-0.2.2")
Changed its name to "_mechanize_dist" (the full path being "C:\Python25\Lib\site-packages\twill\other_packages_mechanize_dist")
Copied "ClientForm" file from "_mechanize_dist_backup" and pasted it in "_mechanize_dist" (in fact, I found two files there named "ClientForm": one is a python file, another one is a compiled python file - I copied and pasted both of them).
Having done that, I tried running all those commands and got stuck at the very beginning - I couldn't even import twill now:
IDLE 1.2.4
>>> import twill
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import twill
File "C:\Python25\Lib\site-packages\twill\__init__.py", line 52, in <module>
from shell import TwillCommandLoop
File "C:\Python25\Lib\site-packages\twill\shell.py", line 9, in <module>
from twill import commands, parse, __version__
File "C:\Python25\Lib\site-packages\twill\commands.py", line 7, in <module>
import _mechanize_dist as mechanize
ImportError: No module named _mechanize_dist
It seems that the system doesn't recognize the newly-created "_mechanize_dist".
Could it be because I have Python 25 instead of Python 26? Or, perhaps, there is some other reason?
A:
The problem lies in Mechanize. You need the newest version
su
git clone git://github.com/jjlee/mechanize.git
cd mechanize
python setup.py install
| Why does Python (with twill) not want to log me in to a Yahoo mail box here? | Can anyone, please, explain to me what's going on here. It seems that Python refuses to work (with twill) when I am trying to log in to my mailbox on Yahoo:
Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
****************************************************************
Personal firewall software may warn about the connection IDLE
makes to its subprocess using this computer's internal loopback
interface. This connection is not visible on any external
interface and no data is sent to or received from the Internet.
****************************************************************
IDLE 1.2.4
>>> import twill
>>> twill.shell.main()
-= Welcome to twill! =-
current page: *empty page*
>> go http://us.yahoo.com
==> at http://us.yahoo.com
current page: http://us.yahoo.com
>> follow Mail
==> at https://login.yahoo.com/config/login_verify2?.intl=us&.src=ym
current page: https://login.yahoo.com/config/login_verify2?.intl=us&.src=ym
>> showforms
Form name=login_form (#1)
## ## __Name__________________ __Type___ __ID________ __Value__________________
1 .tries hidden (None) 1
2 .src hidden (None) ym
3 .md5 hidden (None)
4 .hash hidden (None)
5 .js hidden (None)
6 .last hidden (None)
7 promo hidden (None)
8 .intl hidden (None) us
9 .bypass hidden (None)
10 .partner hidden (None)
11 .u hidden (None) 68gre5567rq16
12 .v hidden (None) 0
13 .challenge hidden (None) 9wKUoOWDdP5Fho0kPfqPKEhPZBdK
14 .yplus hidden (None)
15 .emailCode hidden (None)
16 pkg hidden (None)
17 stepid hidden (None)
18 .ev hidden (None)
19 hasMsgr hidden (None) 0
20 .chkP hidden (None) Y
21 .done hidden (None) http://mail.yahoo.com
22 .pd hidden (None) ym_ver=0&c=&ivt=&sg=
23 pad hidden pad 6
24 aad hidden aad 6
25 login text username
26 passwd password passwd
27 .persistent checkbox persistent [] of ['y']
28 1 .save submi ... .save
current page: https://login.yahoo.com/config/login_verify2?.intl=us&.src=ym
>> fv 1 login *****************
current page: https://login.yahoo.com/config/login_verify2?.intl=us&.src=ym
>> fv 1 passwd ***************
current page: https://login.yahoo.com/config/login_verify2?.intl=us&.src=ym
>> submit
Note: submit is using submit button: name=".save", value=""
Following HTTP-EQUIV=REFRESH to http://us.mg5.mail.yahoo.com/dc/launch?.gx=1&.rand=b3a02cc8lb0aa
current page: http://us.mg5.mail.yahoo.com/dc/launch?.gx=1&.rand=b3a02cc8lb0aa
>> info
Page information:
URL: http://us.mg5.mail.yahoo.com/dc/launch?.gx=1&.rand=b3a02cc8lb0aa
HTTP code: 200
Content type: text/html; charset=utf-8 (HTML)
Page title: Yahoo! Mail
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
twill.shell.main()
File "C:\Python25\Lib\site-packages\twill\shell.py", line 383, in main
shell.cmdloop(welcome_msg)
File "C:\Python25\lib\cmd.py", line 142, in cmdloop
stop = self.onecmd(line)
File "C:\Python25\lib\cmd.py", line 219, in onecmd
return func(arg)
File "C:\Python25\Lib\site-packages\twill\shell.py", line 42, in do_cmd
print '\nERROR: %s\n' % (str(e),)
File "C:\Python25\lib\HTMLParser.py", line 59, in __str__
result = self.msg
AttributeError: 'ParseError' object has no attribute 'msg'
>>>
Update 1:
(this update is my answer to Robus)
Hello, Robus!!!
First of all, I assume it was a typo when You wrote:
Here's what I did: Went to
C:\Python26\Lib\site-packages\twill-0.9-py2.6.egg\twill\other_packages\
I think You meant this path: "C:\Python26\Lib\site-packages\twill\other_packages". Otherwise, I can't see any such folder/directory there named "twill-0.9-py2.6.egg" - there is only a file with this name (the one that I think was downloaded during the installation of mechanize.) Please tell me if my assumption is wrong - I may well be not seeing something very obvious here as I am just a newbie.
So, following Your instructions, I did this:
I found "C:\Python25\Lib\site-packages\twill\other_packages_mechanize_dist" on my computer (as You can see, I don't have python26, but rather python 25 installed - that might also be a problem)
Changed its name to "_mechanize_dist_backup" (the full path now being "C:\Python25\Lib\site-packages\twill\other_packages_mechanize_dist_backup")
Copied my downloaded and unzipped "mechanize-0.2.2" into "C:\Python25\Lib\site-packages\twill\other_packages" (the full path being "C:\Python25\Lib\site-packages\twill\other_packages\mechanize-0.2.2")
Changed its name to "_mechanize_dist" (the full path being "C:\Python25\Lib\site-packages\twill\other_packages_mechanize_dist")
Copied "ClientForm" file from "_mechanize_dist_backup" and pasted it in "_mechanize_dist" (in fact, I found two files there named "ClientForm": one is a python file, another one is a compiled python file - I copied and pasted both of them).
Having done that, I tried running all those commands and got stuck at the very beginning - I couldn't even import twill now:
IDLE 1.2.4
>>> import twill
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import twill
File "C:\Python25\Lib\site-packages\twill\__init__.py", line 52, in <module>
from shell import TwillCommandLoop
File "C:\Python25\Lib\site-packages\twill\shell.py", line 9, in <module>
from twill import commands, parse, __version__
File "C:\Python25\Lib\site-packages\twill\commands.py", line 7, in <module>
import _mechanize_dist as mechanize
ImportError: No module named _mechanize_dist
It seems that the system doesn't recognize the newly-created "_mechanize_dist".
Could it be because I have Python 25 instead of Python 26? Or, perhaps, there is some other reason?
| [
"The problem lies in Mechanize. You need the newest version\nsu\ngit clone git://github.com/jjlee/mechanize.git\ncd mechanize\npython setup.py install\n\n"
] | [
2
] | [] | [] | [
"authentication",
"python",
"twill",
"yahoo_mail"
] | stackoverflow_0003615355_authentication_python_twill_yahoo_mail.txt |
Q:
Python Software design
I am starting to use python,more. Is there a good way to keep python disk access to a minimum.
Seems to me that everytime a *.py file runs, it hits a hard disk. Is there way to avoid hitting the harddisk, and keep *.py file in memory and access it there.
Would creating a small gui using Wxframe, keep code in memory, and reuse work or is it more pain vs benefit.
A:
If you run a .py file from the harddisk, the harddisk will be accessed.
In your GUI, just import your code and it will be loaded once and you can access it later.
A:
Modern operating systems cache file access pretty efficiently, as long as there is enough spare RAM available. You most likely won't notice any difference, fi you're not loading thousand of python files at once.
And as always, before trying to optimize one aspect, make sure that this is really the bottleneck. Chances are, your percieved slowness is not due to loading of the .py files.
A:
I think if you took the time to measure how much time it takes to load your python code from disk you would end up with a very, very tiny number unless you are doing something very wrong. And if you are doing something really wrong, solving that problem will be a better use of your time.
Using wxpython to create a guy to work around what you perceive to be a problem wouldn't likely make any difference.
| Python Software design | I am starting to use python,more. Is there a good way to keep python disk access to a minimum.
Seems to me that everytime a *.py file runs, it hits a hard disk. Is there way to avoid hitting the harddisk, and keep *.py file in memory and access it there.
Would creating a small gui using Wxframe, keep code in memory, and reuse work or is it more pain vs benefit.
| [
"If you run a .py file from the harddisk, the harddisk will be accessed.\nIn your GUI, just import your code and it will be loaded once and you can access it later.\n",
"Modern operating systems cache file access pretty efficiently, as long as there is enough spare RAM available. You most likely won't notice any ... | [
2,
2,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003647368_python_wxpython.txt |
Q:
How to control the size of the Windows shell window from within a python script?
When launching a script-type python file from Windows you get a windows shell type window where the script runs. How can the script determine and also set/control the Window Size, Screen Buffer Size and Window Position of said window?. I suspect this can be done with the pywin32 module but I can't find how.
A:
You can do this using the SetConsoleWindowInfo function from the win32 API. The following should work:
from ctypes import windll, byref
from ctypes.wintypes import SMALL_RECT
STDOUT = -11
hdl = windll.kernel32.GetStdHandle(STDOUT)
rect = wintypes.SMALL_RECT(0, 50, 50, 80) # (left, top, right, bottom)
windll.kernel32.SetConsoleWindowInfo(hdl, True, byref(rect))
UPDATE:
The window position is basically what the rect variable above sets through the left, top, right, bottom arguments. The actual size is derived from these arguments:
width = right - left + 1
height = bottom - top + 1
To set the screen buffer size to, say, 100 rows by 80 columns, you can use the SetConsoleScreenBufferSize API:
bufsize = wintypes._COORD(100, 80) # rows, columns
windll.kernel32.SetConsoleScreenBufferSize(h, bufsize)
| How to control the size of the Windows shell window from within a python script? | When launching a script-type python file from Windows you get a windows shell type window where the script runs. How can the script determine and also set/control the Window Size, Screen Buffer Size and Window Position of said window?. I suspect this can be done with the pywin32 module but I can't find how.
| [
"You can do this using the SetConsoleWindowInfo function from the win32 API. The following should work:\nfrom ctypes import windll, byref\nfrom ctypes.wintypes import SMALL_RECT\n\nSTDOUT = -11\n\nhdl = windll.kernel32.GetStdHandle(STDOUT)\nrect = wintypes.SMALL_RECT(0, 50, 50, 80) # (left, top, right, bottom)\nwi... | [
12
] | [] | [] | [
"python",
"pywin32",
"windows_shell"
] | stackoverflow_0003646362_python_pywin32_windows_shell.txt |
Q:
How to ignore pyc files in Netbeans project browser (regex question)
I want to ignore .pyc files in the Netbeans project browser.
I think I found a way: TOOLS -> MISCELLANEOUS -> FILES .
Here is a section called: Files ignored by the IDE .
The field there is waiting for a regex describing the file pattern . The default value for that field is:
^(CVS|SCCS|vssver.?\.scc|#.*#|%.*%|_svn)$|~$|^\.(?!htaccess$).*$
How do I modify this expression in order to (additionally) ignore the .pyc files ?
A:
Try this :
^(CVS|SCCS|vssver.?\.scc|#.*#|%.*%|_svn|.*\.pyc)$|~$|^\.(?!htaccess$).*$
I just added the .*\.pyc in the first group capture.
| How to ignore pyc files in Netbeans project browser (regex question) | I want to ignore .pyc files in the Netbeans project browser.
I think I found a way: TOOLS -> MISCELLANEOUS -> FILES .
Here is a section called: Files ignored by the IDE .
The field there is waiting for a regex describing the file pattern . The default value for that field is:
^(CVS|SCCS|vssver.?\.scc|#.*#|%.*%|_svn)$|~$|^\.(?!htaccess$).*$
How do I modify this expression in order to (additionally) ignore the .pyc files ?
| [
"Try this :\n^(CVS|SCCS|vssver.?\\.scc|#.*#|%.*%|_svn|.*\\.pyc)$|~$|^\\.(?!htaccess$).*$\n\nI just added the .*\\.pyc in the first group capture.\n"
] | [
9
] | [] | [] | [
"netbeans",
"python",
"regex"
] | stackoverflow_0003647771_netbeans_python_regex.txt |
Q:
Clear the screen in python
Possible Duplicate:
clear terminal in python
How can I clear the window for all text, so that it looks like it has just been opened?
I've heard os.system("clear") works, but it didn't.
Using Python 2.6.5 on Windows 7
A:
clear is for linux, I believe. cls should do the trick:
os.system("cls")
A:
os.system('cls')
That should work
| Clear the screen in python |
Possible Duplicate:
clear terminal in python
How can I clear the window for all text, so that it looks like it has just been opened?
I've heard os.system("clear") works, but it didn't.
Using Python 2.6.5 on Windows 7
| [
"clear is for linux, I believe. cls should do the trick:\nos.system(\"cls\")\n",
"os.system('cls')\nThat should work\n"
] | [
1,
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0003647175_python_windows.txt |
Q:
Is there a limit on the number of asynchronous urlfetch calls I can run simultaneously?
I noticed what appears to be a limit on simultaneous asynchronous calls of urlfetch in the Java implementation (as noted here: http://code.google.com/appengine/docs/java/urlfetch/overview.html)
but not in the python documentation:
http://code.google.com/appengine/docs/python/urlfetch/asynchronousrequests.html
So is it the case that the python version of async urlfetch also has an upper limit of 10 and it's just not documented (or documented elsewhere)? Or is the limit something else (or non-existant)?
A:
The limit for Python is just not documented in that page but in another one, which says (in the middle of the last paragraph of this section):
The app can have up to 10 simultaneous
asynchronous URL Fetch calls.
As you see, that's the same limit as for Java.
A:
umm - that may be true for non-billable apps, but try this in a billable app:
from google.appengine.api import urlfetch
rpc = []
for x in range(1,30):
rpc.append(urlfetch.create_rpc())
urlfetch.make_fetch_call(rpc[-1],"http://stackoverflow.com/questions/3639855/what-happens-if-i-call-more-than-10-asynchronous-url-fetch")
for r in rpc:
response = r.get_result()
logging.info("Response: %s", str(response.status_code))
It just works... So the limit for billable apps is in fact higher (but isn't documented!)
| Is there a limit on the number of asynchronous urlfetch calls I can run simultaneously? | I noticed what appears to be a limit on simultaneous asynchronous calls of urlfetch in the Java implementation (as noted here: http://code.google.com/appengine/docs/java/urlfetch/overview.html)
but not in the python documentation:
http://code.google.com/appengine/docs/python/urlfetch/asynchronousrequests.html
So is it the case that the python version of async urlfetch also has an upper limit of 10 and it's just not documented (or documented elsewhere)? Or is the limit something else (or non-existant)?
| [
"The limit for Python is just not documented in that page but in another one, which says (in the middle of the last paragraph of this section):\n\nThe app can have up to 10 simultaneous\n asynchronous URL Fetch calls.\n\nAs you see, that's the same limit as for Java.\n",
"umm - that may be true for non-billable ... | [
5,
1
] | [] | [] | [
"google_app_engine",
"python",
"urlfetch"
] | stackoverflow_0003146349_google_app_engine_python_urlfetch.txt |
Q:
When is the `==` operator not equivalent to the `is` operator? (Python)
I noticed I can use the == operator to compare all the native data types (integers, strings, booleans, floating point numbers etc) and also lists, tuples, sets and dictionaries which contain native data types. In these cases the == operator checks if two objects are equal. But in some other cases (trying to compare instances of classes I created) the == operator just checks if the two variables reference the same object (so in these cases the == operator is equivalent to the is operator)
My question is: When does the == operator do more than just comparing identities?
EDIT: I'm using Python 3
A:
In Python, the == operator is implemented in terms of the magic method __eq__, which by default implements it by identity comparison. You can, however, override the method in order to provide your own concept of object equality. Note, that if you do so, you will usually also override at least __ne__ (which implements the != operator) and __hash__, which computes a hash code for the instance.
I found it very helpful, even in Python, to make my __eq__ implementations comply with the rules set out in the Java language for implementations of the equals method, namely:
It is reflexive: for any non-null reference value x, x.equals(x) should return true.
It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
For any non-null reference value x, x.equals(null) should return false.
the last one should probably replace null with None, but the rules are not as easy here in Python as in Java.
A:
== and is are always conceptually distinct: the former delegates to the left-hand object's __eq__ [1], the latter always checks identity, without any delegation. What seems to be confusing you is that object.__eq__ (which gets inherited by default by user-coded classes that don't override it, of course!) is implemented in terms of identity (after all, a bare object has absolutely nothing to check except its identity, so what else could it possibly do?!-).
[1] omitting for simplicity the legacy concept of the __cmp__ method, which is just a marginal complication and changes nothing important in the paragraph's gist;-).
A:
The == does more than comparing identity when ints are involved. It doesn't just check that the two ints are the same object; it actually ensures their values match. Consider:
>>> x=10000
>>> y=10000
>>> x==y,x is y
(True, False)
>>> del x
>>> del y
>>> x=10000
>>> y=x
>>> x==y,x is y
(True, True)
The "standard" Python implementation does some stuff behind the scenes for small ints, so when testing with small values you may get something different. Compare this to the equivalent 10000 case:
>>> del y
>>> del x
>>> x=1
>>> y=1
>>> x==y,x is y
(True, True)
A:
What is maybe most important point is that recommendation is to always use:
if myvalue is None:
not
if myvalue == None:
And never to use:
if myvalue is True:
but use:
if myvalue:
This later point is not so supper clear to me as I think there is times to separate the boolean True from other True values like "Alex Martelli" , say there is not False in "Alex Martelli" (absolutely not, it even raises exception :) ) but there is '' in "Alex Martelli" (as is in any other string).
| When is the `==` operator not equivalent to the `is` operator? (Python) | I noticed I can use the == operator to compare all the native data types (integers, strings, booleans, floating point numbers etc) and also lists, tuples, sets and dictionaries which contain native data types. In these cases the == operator checks if two objects are equal. But in some other cases (trying to compare instances of classes I created) the == operator just checks if the two variables reference the same object (so in these cases the == operator is equivalent to the is operator)
My question is: When does the == operator do more than just comparing identities?
EDIT: I'm using Python 3
| [
"In Python, the == operator is implemented in terms of the magic method __eq__, which by default implements it by identity comparison. You can, however, override the method in order to provide your own concept of object equality. Note, that if you do so, you will usually also override at least __ne__ (which impleme... | [
20,
18,
7,
4
] | [] | [] | [
"comparison",
"equality",
"python"
] | stackoverflow_0003647692_comparison_equality_python.txt |
Q:
socket.error errno.EWOULDBLOCK
i'm reading some code and i've come across this line
socket.error errno.EWOULDBLOCK
can anyone tell me what the conditions have to be to raise this error?
A:
From Python's socket module: http://docs.python.org/library/socket.html
Initially all sockets are in blocking
mode. In non-blocking mode, if a
recv() call doesn’t find any data, or
if a send() call can’t immediately
dispose of the data, a error exception
is raised.
The error exception it's referring to is errno.EWOULDBLOCK
For this to happen, the socket object must be set to non-blocking mode using: socketObj.setblocking(0)
A:
Note that EWOULDBLOCK is error number 11:
In [80]: import errno
In [83]: errno.EWOULDBLOCK
Out[84]: 11
And the associated error message is:
In [86]: import os
In [87]: os.strerror(errno.EWOULDBLOCK)
Out[89]: 'Resource temporarily unavailable'
Here is some toy code which exhibits the EWOULDBLOCK error.
It sets up a server and client which try to talk to each other over a socket connection. When s.setblocking(0) is called to put the socket in non-blocking mode, a subsequent call to s.recv raises the socket.error. I think this happens because both ends of the connection are trying to receive data:
import socket
import multiprocessing as mp
import sys
import time
def server():
HOST='localhost'
PORT=6000
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr=s.accept()
while True:
data=conn.recv(1024)
if data:
conn.send(data)
conn.close()
def client():
HOST='localhost'
PORT=6000
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.setblocking(0) # Comment this out, and the EWOULDBLOCK error goes away
s.send('Hello, world')
try:
data=s.recv(1024)
except socket.error as err:
print(err)
# [Errno 11] Resource temporarily unavailable
sys.exit()
finally:
s.close()
print('Received {0}'.format(repr(data)))
def run():
server_process=mp.Process(target=server)
server_process.daemon=True
server_process.start()
time.sleep(0.1)
client()
run()
If s.setblocking(0) is commented-out, you should see
Received 'Hello, world'
| socket.error errno.EWOULDBLOCK | i'm reading some code and i've come across this line
socket.error errno.EWOULDBLOCK
can anyone tell me what the conditions have to be to raise this error?
| [
"From Python's socket module: http://docs.python.org/library/socket.html\n\nInitially all sockets are in blocking\n mode. In non-blocking mode, if a\n recv() call doesn’t find any data, or\n if a send() call can’t immediately\n dispose of the data, a error exception\n is raised.\n\nThe error exception it's ref... | [
6,
3
] | [] | [] | [
"networking",
"python",
"twisted"
] | stackoverflow_0003647539_networking_python_twisted.txt |
Q:
'import feedparser' works via SSH, but fails when in browser
I installed feedparser via SSH, using
$ python setup.py install --home=~/httpdocs/python-libraries/feedparser-4.1/
I did that because I don't seem to have permission to properly run 'python setup.py install'
I am running the following python code in 'test.py'.
print "Content-type: text/html\n\n"
try:
import feedparser
except:
print "Cannot import feedparser.\n"
The code runs fine when I am logged in by SSH. But when I view it in a browser, it prints
Cannot import feedparser.
Any ideas?
A:
Maybe it's the problem with setting correct sys.path while running from shell vs from web server.
More about sys.path here: sys module.
I'd recomend to try adding ~/httpdocs/python-libraries/feedparser-4.1/ (best using full path, without ~/) to your sys.path before the import.
import sys
sys.path.append('/home/user/httpdocs/python-libraries/feedparser-4.1/')
print "Content-type: text/html\n\n"
try:
import feedparser
except:
print "Cannot import feedparser.\n"
Oh, and by the way, the httpdocs seems like a document root for your web server. Is it the best idea to put the library there? (well, unless there's the only place you can use...)
edit (as a general note)
It's best to avoid the syntax like:
try:
something
except:
print "error"
This gives you absolutly no information about the actual error you encounter. You can assume that if you try to import a module, you have ImportError there, but can't be sure.
This makes debugging a real hell. Been there, done that, have lost dozens of hours due to this :)
Whenever you can, try catching one exception type at a time. So:
try:
import SomeModule
except ImportError:
print "SomeModule can't be imported"
You can also get familiar with the traceback module. It's in the standard library and it's there so you can use it. So, your exception handling code could be something like this:
sys.path.append('/home/user/httpdocs/python-libraries/feedparser-4.1/')
try:
import feedparser
except ImportError:
print "Content-type: text/plain\n\n" # text/plain so we get the stacktrace printed well
import traceback
import sys
traceback.print_exc(sys.stdout) # default is sys.stderr, which is error log in case of web server running your script, we want it on standart output
sys.exit(1)
# here goes your code to execute when all is ok, including:
print "Content-type: text/html\n\n"
A:
Sounds like a PYTHONPATH problem. Try changing the code to this and see what happens:
import sys
print "Content-type: text/html\n\n"
try:
print sys.path
import feedparser
except:
print "Cannot import feedparser.\n"
print sys.path
This probably will show that your ~/httpdocs/python-libraries/ directory is not in the path and you will need to either change sys.path or arrage for a PYTHONPATH environment variable, to correct the problem.
When you change the path, make sure that you use the full directory name, not the ~ shortcut.
A:
I tried both the sys.path and the $PYTHONPATH solutions, but they didn't seem to work.
I didn't try adding PythonPath to httpd.conf or python.conf - that could have worked.
I ended up asking a root user to run # python setup.py install for me. That worked.
I was using Python 2.3.
A:
Rather than catching the exception yourself, use the cgitb module just once at the top of your program, and you'll get better information about all errors.
import cgitb
cgitb.enable()
| 'import feedparser' works via SSH, but fails when in browser | I installed feedparser via SSH, using
$ python setup.py install --home=~/httpdocs/python-libraries/feedparser-4.1/
I did that because I don't seem to have permission to properly run 'python setup.py install'
I am running the following python code in 'test.py'.
print "Content-type: text/html\n\n"
try:
import feedparser
except:
print "Cannot import feedparser.\n"
The code runs fine when I am logged in by SSH. But when I view it in a browser, it prints
Cannot import feedparser.
Any ideas?
| [
"Maybe it's the problem with setting correct sys.path while running from shell vs from web server.\nMore about sys.path here: sys module.\nI'd recomend to try adding ~/httpdocs/python-libraries/feedparser-4.1/ (best using full path, without ~/) to your sys.path before the import. \nimport sys\nsys.path.append('/hom... | [
7,
3,
0,
0
] | [] | [] | [
"browser",
"feedparser",
"import",
"python"
] | stackoverflow_0001755043_browser_feedparser_import_python.txt |
Q:
Python: how to pass a reference to a function
IMO python is pass by value if the parameter is basic types, like number, boolean
func_a(bool_value):
bool_value = True
Will not change the outside bool_value, right?
So my question is how can I make the bool_value change takes effect in the outside one(pass by reference?
A:
You can use a list to enclose the inout variable:
def func(container):
container[0] = True
container = [False]
func(container)
print container[0]
The call-by-value/call-by-reference misnomer is an old debate. Python's semantics are more accurately described by CLU's call-by-sharing. See Fredrik Lundh's write up of this for more detail:
Call By Object
A:
Python (always), like Java (mostly) passes arguments (and, in simple assignment, binds names) by object reference. There is no concept of "pass by value", neither does any concept of "reference to a variables" -- only reference to a value (some express this by saying that Python doesn't have "variables"... it has names, which get bound to values -- and that is all that can ever happen).
Mutable objects can have mutating methods (some of which look like operators or even assignment, e.g a.b = c actually means type(a).__setattr__(a, 'b', c), which calls a method which may likely be a mutating ones).
But simple assignment to a barename (and argument passing, which is exactly the same as simple assignment to a barename) never has anything at all to do with any mutating methods.
Quite independently of the types involved, simple barename assignment (and, identically, argument passing) only ever binds or rebinds the specific name on the left of the =, never affecting any other name nor any object in any way whatsoever. You're very mistaken if you believe that types have anything to do with the semantics of argument passing (or, identically, simple assignment to barenames).
A:
Unmutable types can't, but if you send a user-defined class instance, a list or a dictionary, you can change it and keep with only one object.
Like this:
def add1(my_list):
my_list.append(1)
a = []
add1(a)
print a
But, if you do my_list = [1], you obtain a new instance, losing the original reference inside the function, that's why you can't just do "my_bool = False" and hope that outside of the function your variable get that False
| Python: how to pass a reference to a function | IMO python is pass by value if the parameter is basic types, like number, boolean
func_a(bool_value):
bool_value = True
Will not change the outside bool_value, right?
So my question is how can I make the bool_value change takes effect in the outside one(pass by reference?
| [
"You can use a list to enclose the inout variable:\ndef func(container):\n container[0] = True\n\n\ncontainer = [False]\nfunc(container)\nprint container[0]\n\nThe call-by-value/call-by-reference misnomer is an old debate. Python's semantics are more accurately described by CLU's call-by-sharing. See Fredrik L... | [
6,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0003648473_python.txt |
Q:
Python: Nested for loops or "next" statement
I'm a rookie hobbyist and I nest for loops when I write python, like so:
dict = {
key1: {subkey/value1: value2}
...
keyn: {subkeyn/valuen: valuen+1}
}
for key in dict:
for subkey/value in key:
do it to it
I'm aware of a "next" keyword that would accomplish the same goal in one line (I asked a question about how to use it but I didn't quite understand it).
So to me, a nested for loop is much more readable. Why, then do people use "next"? I read somewhere that Python is a dynamically-typed and interpreted language and because + both concontinates strings and sums numbers, that it must check variable types for each loop iteration in order to know what the operators are, etc. Does using "next" prevent this in some way, speeding up the execution or is it just a matter of style/preference?
A:
next is precious to advance an iterator when necessary, without that advancement controlling an explicit for loop. For example, if you want "the first item in S that's greater than 100", next(x for x in S if x > 100) will give it to you, no muss, no fuss, no unneeded work (as everything terminates as soon as a suitable x is located) -- and you get an exception (StopIteration) if unexpectedly no x matches the condition. If a no-match is expected and you want None in that case, next((x for x in S if x > 100), None) will deliver that. For this specific purpose, it might be clearer to you if next was actually named first, but that would betray its much more general use.
Consider, for example, the task of merging multiple sequences (e.g., a union or intersection of sorted sequences -- say, sorted files, where the items are lines). Again, next is just what the doctor ordered, because none of the sequences can dominate over the others by controlling A "main for loop". So, assuming for simplicity no duplicates can exist (a condition that's not hard to relax if needed), you keep pairs (currentitem, itsfile) in a list controlled by heapq, and the merging becomes easy... but only thanks to the magic of next to advance the correct file once its item has been used, and that file only.
import heapq
def merge(*theopentextfiles):
theheap = []
for afile in theopentextfiles:
theitem = next(afile, '')
if theitem: theheap.append((theitem, afile))
heapq.heapify(theheap)
while theheap:
theitem, afile = heapq.heappop(theheap)
yielf theitem
theitem = next(afile, '')
if theitem: heapq.heappush(theheap, (theitem, afile))
Just try to do anything anywhere this elegant without next...!-)
One could go on for a long time, but the two use cases "advance an iterator by one place (without letting it control a whole for loop)" and "get just the first item from an iterator" account for most important uses of next.
| Python: Nested for loops or "next" statement | I'm a rookie hobbyist and I nest for loops when I write python, like so:
dict = {
key1: {subkey/value1: value2}
...
keyn: {subkeyn/valuen: valuen+1}
}
for key in dict:
for subkey/value in key:
do it to it
I'm aware of a "next" keyword that would accomplish the same goal in one line (I asked a question about how to use it but I didn't quite understand it).
So to me, a nested for loop is much more readable. Why, then do people use "next"? I read somewhere that Python is a dynamically-typed and interpreted language and because + both concontinates strings and sums numbers, that it must check variable types for each loop iteration in order to know what the operators are, etc. Does using "next" prevent this in some way, speeding up the execution or is it just a matter of style/preference?
| [
"next is precious to advance an iterator when necessary, without that advancement controlling an explicit for loop. For example, if you want \"the first item in S that's greater than 100\", next(x for x in S if x > 100) will give it to you, no muss, no fuss, no unneeded work (as everything terminates as soon as a ... | [
24
] | [] | [] | [
"for_loop",
"optimization",
"python"
] | stackoverflow_0003648602_for_loop_optimization_python.txt |
Q:
Issue Replacing Already Existing Strings with ConfigParser
I am using ConfigParser to save simple settings to a .ini file, and one of these settings is a directory. Whenever I replace a directory string such as D:/Documents/Data, with a shorter directory string such as D:/, the remaining characters are placed two lines under the option. So the .ini file now looks like this:
[Settings]
directory = D:/
Documents/Data
What am I doing wrong? Here is my code:
import ConfigParser
class Settings():
self.config = ConfigParser.ConfigParser()
def SetDirectory(self, dir): #dir is the directory string
self.config.readfp(open('settings.ini'))
self.config.set('Settings', 'directory', dir)
with open('settings.ini', 'r+') as configfile: self.config.write(configfile)
A:
The r+ option (in the open in the with) is telling Python to keep the file's previous contents, just overwriting the specific bytes that will be written to it but leaving all others alone. Use w to open a file for complete overwriting, which seems to be what you should be doing here. Overwriting just selected bytes inside an existing file is very rarely what you want to do, particularly for text files, which you're more likely to want to see as sequence of lines of text, rather than bunches of bytes! (It can be useful in very specialized cases, mostly involving large binary files, where the by-byte view may make some sense).
The "by-line organization" with which we like to view text files is not reflected in the underlying filesystem (on any OS that is currently popular, at least -- back in the dark past some file organizations were meant to mimic packs of punched cards, for example, so each line had to be exactly 80 bytes, no more, no less... but that's a far-off ancient memory, at most, for the vast majority of computer programmers and users today;-).
So, "overwriting part of a file in-place" (where the file contains text lines of different lengths) becomes quite a problem. Should you ever need to do that, btw, consider the fileinput module of the standard Python library, which mimics this often-desired but-running-against-the-filesystem's-grain operation quite competently. But, it wouldn't help you much in this case, where simple total overwriting seems to be exactly right;-).
| Issue Replacing Already Existing Strings with ConfigParser | I am using ConfigParser to save simple settings to a .ini file, and one of these settings is a directory. Whenever I replace a directory string such as D:/Documents/Data, with a shorter directory string such as D:/, the remaining characters are placed two lines under the option. So the .ini file now looks like this:
[Settings]
directory = D:/
Documents/Data
What am I doing wrong? Here is my code:
import ConfigParser
class Settings():
self.config = ConfigParser.ConfigParser()
def SetDirectory(self, dir): #dir is the directory string
self.config.readfp(open('settings.ini'))
self.config.set('Settings', 'directory', dir)
with open('settings.ini', 'r+') as configfile: self.config.write(configfile)
| [
"The r+ option (in the open in the with) is telling Python to keep the file's previous contents, just overwriting the specific bytes that will be written to it but leaving all others alone. Use w to open a file for complete overwriting, which seems to be what you should be doing here. Overwriting just selected by... | [
1
] | [] | [] | [
"configparser",
"python"
] | stackoverflow_0003648612_configparser_python.txt |
Q:
python subclass access to class variable of parent
I was surprised to to learn that a class variable of a subclass can't access a class variable of the parent without specifically indicating the class name of the parent:
>>> class A(object):
... x = 0
...
>>> class B(A):
... y = x+1
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in B
NameError: name 'x' is not defined
>>> class B(A):
... y = A.x + 1
...
>>> B.x
0
>>> B.y
1
Why is it that in defining B.y I have to refer to A.x and not just x? This is counter to my intuition from instance variables, and since I can refer to B.x after B is defined.
A:
Python's scoping rules for barenames are very simple and straightforward: local namespace first, then (if any) outer functions in which the current one is nested, then globals, finally built-ins. That's all that ever happens when a barename is looked up, and there's no need to memorize or apply any complicated rules (nor is there any need for a Python compiler to enforce more complicated rules).
Any time you want a different lookup, you'll be using a qualified name, not a bare name. Qualified names are vastly more powerful because the lookup can always be delegated to the objects whose attributes can be requested, and those object can implement whatever lookup rules they need. In particular, in an instance method within a class, self.x is the way to ask the self object to look up attribute name 'x' -- and in that lookup it can delegate to classes, including the implementation of the concept of inheritance (and multiple inheritance, method resolution order, and so on).
The body of a class (as opposed to the bodies of the methods defined in a class) executes as part of the class statement, before the class object is created or its name is bound (in particular, before any of the bases have been defined as being bases -- though this latest detail can never matter when referring to barenames, anyway!-).
So, in your example, in class B, barename x is looked up with the universal rules -- is it a name bound locally? If no, is it bound in any outer function in which this scope is nested? If no, is it bound as a global or built-in? If none of the above, using the barename in question of course causes a name-error exception.
Since you want a different lookup sequence than the barename lookup rules universally enforce, then clearly you need to use a qualified name, not a barename; and a moment's reflection will clearly show that the "one obvious choice" for a qualified name to use for your purpose has to be A.x -- since that's where you want it to be looked up (the bases haven't been recorded anywhere yet at that point, after all... it will be the metaclass, normally type, that will do the bases-binding as part of its job when it gets called after the class body is done executing!-).
Some people are so keenly attached to other "magical" rules for the lookup of barenames that they just can't stand this aspect of Python (originally inspired, I believe, by Modula-3, a little known language that's very well considered in theoreticians' circles;-) -- having to write self.x in a method to specify that x must be looked up on self rather than using the universal barename rules, for example, drives such people batty.
Me, I love the simplicity and universality of the barename lookup rules, and I love using qualified names instead of barenames any time I want any other form of lookup... but then, it's not a secret that I'm madly in love with Python (I have my own grumbles -- e.g., global x as a statement always makes my skin crawl, where I'd much rather write global.x, i.e., have global be a built-in name for "the currently executing module"... I do love qualified names!-), is it?-)
A:
In Python, the body of a class is executed in its own namespace before the class is created (after which, the members of that namespace become the members of the class). So when the interpreter reaches y = x+1, class B does not exist yet at that point and, therefore, has no parent.
For more details, see http://docs.python.org/reference/compound_stmts.html#class-definitions
| python subclass access to class variable of parent | I was surprised to to learn that a class variable of a subclass can't access a class variable of the parent without specifically indicating the class name of the parent:
>>> class A(object):
... x = 0
...
>>> class B(A):
... y = x+1
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in B
NameError: name 'x' is not defined
>>> class B(A):
... y = A.x + 1
...
>>> B.x
0
>>> B.y
1
Why is it that in defining B.y I have to refer to A.x and not just x? This is counter to my intuition from instance variables, and since I can refer to B.x after B is defined.
| [
"Python's scoping rules for barenames are very simple and straightforward: local namespace first, then (if any) outer functions in which the current one is nested, then globals, finally built-ins. That's all that ever happens when a barename is looked up, and there's no need to memorize or apply any complicated ru... | [
51,
33
] | [] | [] | [
"class_variables",
"python",
"subclass"
] | stackoverflow_0003648564_class_variables_python_subclass.txt |
Q:
Python Lxml - Append a existing xml with new data
I am new to python/lxml After reading the lxml site and dive into python I could not find the solution to my n00b troubles. I have the below xml sample:
---------------
<addressbook>
<person>
<name>Eric Idle</name>
<phone type='fix'>999-999-999</phone>
<phone type='mobile'>555-555-555</phone>
<address>
<street>12, spam road</street>
<city>London</city>
<zip>H4B 1X3</zip>
</address>
</person>
</addressbook>
-------------------------------
I am trying to append one child to the root element and write the entire file back out as a new xml or over write the existing xml. Currently all I am writing is one line.
from lxml import etree
tree = etree.parse('addressbook.xml')
root = tree.getroot()
oSetroot = etree.Element(root.tag)
NewSub = etree.SubElement ( oSetroot, 'CREATE_NEW_SUB' )
doc = etree.ElementTree (oSetroot)
doc.write ( 'addressbook1.xml' )
TIA
A:
You could make a new tree by copying over all of the old one (not just the root tag!-), but it's much simpler to edit the existing tree in-place (and, why not?-)...:
tree = etree.parse('addressbook.xml')
root = tree.getroot()
NewSub = etree.SubElement ( root, 'CREATE_NEW_SUB' )
tree.write ( 'addressbook1.xml' )
which puts in addressbook1.xml:
<addressbook>
<person>
<name>Eric Idle</name>
<phone type="fix">999-999-999</phone>
<phone type="mobile">555-555-555</phone>
<address>
<street>12, spam road</street>
<city>London</city>
<zip>H4B 1X3</zip>
</address>
</person>
<CREATE_NEW_SUB /></addressbook>
(which I hope is the effect you're looking for...?-)
| Python Lxml - Append a existing xml with new data | I am new to python/lxml After reading the lxml site and dive into python I could not find the solution to my n00b troubles. I have the below xml sample:
---------------
<addressbook>
<person>
<name>Eric Idle</name>
<phone type='fix'>999-999-999</phone>
<phone type='mobile'>555-555-555</phone>
<address>
<street>12, spam road</street>
<city>London</city>
<zip>H4B 1X3</zip>
</address>
</person>
</addressbook>
-------------------------------
I am trying to append one child to the root element and write the entire file back out as a new xml or over write the existing xml. Currently all I am writing is one line.
from lxml import etree
tree = etree.parse('addressbook.xml')
root = tree.getroot()
oSetroot = etree.Element(root.tag)
NewSub = etree.SubElement ( oSetroot, 'CREATE_NEW_SUB' )
doc = etree.ElementTree (oSetroot)
doc.write ( 'addressbook1.xml' )
TIA
| [
"You could make a new tree by copying over all of the old one (not just the root tag!-), but it's much simpler to edit the existing tree in-place (and, why not?-)...:\ntree = etree.parse('addressbook.xml')\nroot = tree.getroot()\nNewSub = etree.SubElement ( root, 'CREATE_NEW_SUB' )\ntree.write ( 'addressbook1.xml' ... | [
17
] | [] | [] | [
"lxml",
"python",
"xml"
] | stackoverflow_0003648689_lxml_python_xml.txt |
Q:
how to crawl a 403 forbidden SNS
i'm crawling an SNS with crawler written in python
it works for a long time, but few days ago, the webpages got from my severs were ERROR 403 FORBIDDEN.
i tried to change the cookie, change the browser, change the account, but all failed.
and it seems that are the forbidden severs are in the same network segment.
what can i do? steal someone else's ip? = =...
thx a lot
A:
Looks like you've been blacklisted at the router level in that subnet, perhaps because you (or somebody else in the subnet) was violating terms of use, robots.txt, max crawling frequency as specified in a site-map, or something like that.
The solution is not technical, but social: contact the webmaster, be properly apologetic, learn what exactly you (or one of your associates) had done wrong, convincingly promise to never do it again, apologize again until they remove the blacklisting. If you can give that webmaster any reason why they should want to let you crawl that site (e.g., your crawling feeds a search engine that will bring them traffic, or something like this), so much the better!-)
| how to crawl a 403 forbidden SNS | i'm crawling an SNS with crawler written in python
it works for a long time, but few days ago, the webpages got from my severs were ERROR 403 FORBIDDEN.
i tried to change the cookie, change the browser, change the account, but all failed.
and it seems that are the forbidden severs are in the same network segment.
what can i do? steal someone else's ip? = =...
thx a lot
| [
"Looks like you've been blacklisted at the router level in that subnet, perhaps because you (or somebody else in the subnet) was violating terms of use, robots.txt, max crawling frequency as specified in a site-map, or something like that.\nThe solution is not technical, but social: contact the webmaster, be proper... | [
1
] | [] | [] | [
"http_status_code_403",
"python",
"web_crawler"
] | stackoverflow_0003648525_http_status_code_403_python_web_crawler.txt |
Q:
printing unicode through a QProcess
I'm having some trouble handling unicode output from a QProcess. When I run the following example I get ?? instead of 中文. Can anyone tell me how to get the unicode output?
from PyQt4.QtCore import *
def on_ready_stdout():
byte_array = proc.readAllStandardOutput()
print 'byte_array: ', byte_array
print 'unicode: ', unicode(byte_array)
proc = QProcess()
proc.connect(proc, SIGNAL('readyReadStandardOutput()'), on_ready_stdout)
proc.start(u'python -c "print \'hello 中文\'"')
proc.waitForFinished()
@serge
I tried running your modified code, but I get an error:
byte_array: hello Σ╕¡µ??
unicode:
Traceback (most recent call last):
File "python_temp.py", line 7, in on_ready_stdout
print 'unicode: ', unicode(byte_array)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 6: ordinal
not in range(128)
A:
I've changed your code a little and got the expected output:
byte_array: hello 中文
unicode: hello 中文
my changes were:
I added # -- coding: utf-8 -- magic comment (details here)
Removed "u" string declaration from the proc.start call
below is your code with my changes:
# -*- coding: utf-8 -*-
from PyQt4.QtCore import *
def on_ready_stdout():
byte_array = proc.readAllStandardOutput()
print 'byte_array: ', byte_array
print 'unicode: ', unicode(byte_array)
proc = QProcess()
proc.connect(proc, SIGNAL('readyReadStandardOutput()'), on_ready_stdout)
proc.start('python -c "print \'hello 中文\'"')
proc.waitForFinished()
hope this helps, regards
| printing unicode through a QProcess | I'm having some trouble handling unicode output from a QProcess. When I run the following example I get ?? instead of 中文. Can anyone tell me how to get the unicode output?
from PyQt4.QtCore import *
def on_ready_stdout():
byte_array = proc.readAllStandardOutput()
print 'byte_array: ', byte_array
print 'unicode: ', unicode(byte_array)
proc = QProcess()
proc.connect(proc, SIGNAL('readyReadStandardOutput()'), on_ready_stdout)
proc.start(u'python -c "print \'hello 中文\'"')
proc.waitForFinished()
@serge
I tried running your modified code, but I get an error:
byte_array: hello Σ╕¡µ??
unicode:
Traceback (most recent call last):
File "python_temp.py", line 7, in on_ready_stdout
print 'unicode: ', unicode(byte_array)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 6: ordinal
not in range(128)
| [
"I've changed your code a little and got the expected output:\nbyte_array: hello 中文\n\nunicode: hello 中文\n\nmy changes were:\n\nI added # -- coding: utf-8 -- magic comment (details here)\nRemoved \"u\" string declaration from the proc.start call\n\nbelow is your code with my changes:\n# -*- coding: utf-8 -*-\nfro... | [
0
] | [] | [] | [
"pyqt",
"python",
"qprocess",
"qt",
"unicode"
] | stackoverflow_0003074969_pyqt_python_qprocess_qt_unicode.txt |
Q:
DB-API with Python
I'm trying to insert some data into a local MySQL database by using MySQL Connector/Python -- apparently the only way to integrate MySQL into Python 3 without breaking out the C Compiler.
I tried all the examples that come with the package; Those who execute can enter data just fine. Unfortunately my attempts to write anything into my tables fail.
Here is my code:
import mysql.connector
def main(config):
db = mysql.connector.Connect(**config)
cursor = db.cursor()
stmt_drop = "DROP TABLE IF EXISTS urls"
cursor.execute(stmt_drop)
stmt_create = """
CREATE TABLE urls (
id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT,
str VARCHAR(50) DEFAULT '' NOT NULL,
PRIMARY KEY (id)
) CHARACTER SET 'utf8'"""
cursor.execute(stmt_create)
cursor.execute ("""
INSERT INTO urls (str)
VALUES
('reptile'),
('amphibian'),
('fish'),
('mammal')
""")
print("Number of rows inserted: %d" % cursor.rowcount)
db.close()
if __name__ == '__main__':
import config
config = config.Config.dbinfo().copy()
main(config)
OUTPUT:
Number of rows inserted: 4
I orientate my code strictly on what was given to me in the examples and can't, for the life of mine, figure out what the problem is. What am I doing wrong here?
Fetching table data with the script works just fine so I am not worried about the configuration files. I'm root on the database so rights shouldn't be a problem either.
A:
You need to add a db.commit() to commit your changes before you db.close()!
| DB-API with Python | I'm trying to insert some data into a local MySQL database by using MySQL Connector/Python -- apparently the only way to integrate MySQL into Python 3 without breaking out the C Compiler.
I tried all the examples that come with the package; Those who execute can enter data just fine. Unfortunately my attempts to write anything into my tables fail.
Here is my code:
import mysql.connector
def main(config):
db = mysql.connector.Connect(**config)
cursor = db.cursor()
stmt_drop = "DROP TABLE IF EXISTS urls"
cursor.execute(stmt_drop)
stmt_create = """
CREATE TABLE urls (
id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT,
str VARCHAR(50) DEFAULT '' NOT NULL,
PRIMARY KEY (id)
) CHARACTER SET 'utf8'"""
cursor.execute(stmt_create)
cursor.execute ("""
INSERT INTO urls (str)
VALUES
('reptile'),
('amphibian'),
('fish'),
('mammal')
""")
print("Number of rows inserted: %d" % cursor.rowcount)
db.close()
if __name__ == '__main__':
import config
config = config.Config.dbinfo().copy()
main(config)
OUTPUT:
Number of rows inserted: 4
I orientate my code strictly on what was given to me in the examples and can't, for the life of mine, figure out what the problem is. What am I doing wrong here?
Fetching table data with the script works just fine so I am not worried about the configuration files. I'm root on the database so rights shouldn't be a problem either.
| [
"You need to add a db.commit() to commit your changes before you db.close()!\n"
] | [
5
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003648861_mysql_python.txt |
Q:
C++ and python simultaneously. Is it doable
I am totally new to programming as though I have my PhD as a molecular biologist for the last 10 years. Can someone please tell me: Would it be too hard to handle if I enrolled simultaneously in C++ and python? I am a full time employee too. Both courses start and finish on the same dates and is for 3 months. For a variety of complicated reasons, this fall is the only time I can learn both languages. Please advise.
GillingsT
Update:
A little more detail about myself: as I said I did a PhD in Molecular Genetic. I now wish to be able to obtain programming skills so that I can apply it to do bioinformatics- like sequence manipulation and pathway analysis. I was told that Python is great for that but our course does not cover basics for beginners. I approached a Comp Sci Prof. who suggested that I learn C++ first before learning Python. So I got into this dilemma (added to other logistics).
A:
You'll get holes in the head.
Python's data structures and memory management are radically different from C++.
Whichever language you "get" first, you'll love. The other you'll hate. Indeed, you'll be confused at the weird things one language lacks that the other has. One language will be reasonable, logical, unsurprising. The other will be a mess of ad-hoc decisions and quirks.
If you learn one all the way through -- by itself -- you'll probably be happier.
I find that most folks can more easily add a language to a base of expertise.
[Not all, however. Some folks are so mired in the first language they ever learned that they challenge every feature of a new language as being nonsensical. I had a guy in a Java class who only wanted to complain about the numerous ways that Java wasn't Fortran. All the type-specific stuff in Java gave him fits. A lot of discussions had to be curtailed with "That's the way it is. If you don't like it, take it up with Gosling. My job isn't to justify Java; my job is to get you to be able to work with java. Can we move on, now?"]
A:
If you are new to programming, I would say start with the C++ class. If you get the hang of it and enjoy programming, you can always learn Python later. There are a wealth of good books and Internet resources on pretty much any programming language out there that you should be able to teach yourself any language in your spare time. I would recommend learning that first language in a formal classroom, however, to help make it easier to learn the general concepts behind programming.
Edit: To clarify the point I was trying to make, my recommendation is to take whichever course is geared more towards beginning programmers. The important things to learn first are the basic fundamentals of programming. These apply towards almost any language. Thanks to the wealth of resources available online or in your bookstore/library, you can teach yourself practically any programming language that you want to learn. First, however, you must grasp the basics, and intro C/C++ classes typically (in my experiences, at least) do a good job of teaching programming fundamentals as well as the language itself.
Since you are a beginning programmer, I would not recommend trying to learn two languages at once (especially if you are trying to learn fundamentals at the same time). That's a lot of very similar (yet very different) information to keep track of in your head, almost like trying to learn two brand new spoken languages at the same time. You may be able to handle it perfectly fine but at least for most programmers that I know, it is much easier to get a good grasp on one language first and then start learning the second.
A:
I think that given the circumstances (fulltime employee, etc) studying one language will be hard enough. Pick one, then study another. You'll learn basics from either language.
As for "which language to pick"... I specialize in C++, and know a bit of python. C++ is much more difficult, more flexible, and more suitable for making "traditional" executables.
I'd recommend to start with C++. You'll learn more concepts (some of them doesn't exist in python), and learning python after C++ won't be a problem.
A:
edit:
From your comment on this question, it appears the Python course is not geared towards beginner programmers. They'll probably be covering some of the more advanced topics of programming without touching on the basics of program flow which are really essential. So if the C++ course is geared towards beginners, then I would recommend that you take the C++ course and teach yourself Python on the side.
There is a wealth of Python tutorials out there. The official one is also really good. You don't have to wait to learn Python, of course, you can do it right now by going to any of those tutorials. The first tutorial I linked, by Alan Gauld, is geared towards non-programmers and is really high quality. He's also a regular contributor/moderator of the python tutor list. If you want to really learn Python, subscribe to that list and ask questions when you have them and do your best to answer questions that are posed - that's how I learned Python and I credit that process with much of my knowledge and understanding. As a PhD you've probably seen countless times that teaching someone else helps you retain your knowledge better and forces you to really understand the concepts.
When you do start learning, there's a great package of Python tools called Python (X,Y) that is designed for doing scientific type computing. It has all sorts of great tools packaged with it.
If you've had any experience programming, then you should easily be able to handle both course loads. What I mean is that if you can understand the following two programs, you should be able to easily perform the course loads.
Python:
elements = ['Sn', 'Pb', 'Au', 'Fr', 'F', 'Xe', 'H']
for element in elements:
if element == 'Sn':
print 'Tin'
elif element == 'Pb':
print 'Lead'
elif element == 'Au':
print 'Gold'
else:
print 'Other'
C++
#include <stdio>
#include <string>
using namespace std;
int main(){
string name;
int age = 0;
cout << "Please enter your name: ";
cin >> name;
cout << "Please enter your age: ";
cin >> age;
cout << "Hello " << name << "! You are " << age << " years old!" << endl;
return 0;
}
Even if you don't know exactly what's going on, in the programs, if you kind of have an idea, you should do just fine. These are typical programs that you'd expect to see in the first few weeks of class, and if you can look at them and figure out what's going on you're probably at least better off than the average student.
If you look at both of these programs and think, "What in the...??? I'm so confused!", then you should only take the Python course. Python makes it a lot easier to grasp the concepts (and write programs) than C++. The knowledge you gain in either language easily translates to the other, but you have to be exposed to a lot more in C++ than Python. For example, that C++ program looks like this in python:
name = raw_input("Please enter your name: ")
age = raw_input("Please enter your age: ")
print "Hello", name, "! You are", age, "years old!"
You can usually focus on one concept at a time without having to worry about possible bugs being introduced by other language features.
But if you can guess what's going on in both programs within 5 minutes, I'd go ahead and take both classes - as a molecular biologist you've had to do plenty of logical thinking which is essential to programming (not so essential to being a high-schooler).
Good luck!
A:
I think it all depends on the level or difficulty of the of the class and that the languages in and of themselves really don't make that much of a difference.
To me, programming is 95% logical and about 5% dealing with syntax and the actual language. I started programming in high school and up through college (a senior a Computer Eng Currently) the focus was all about understanding the mindset of things and learning how to logically think through a problem and then develop a solution. Very few of our classes were a C++ or Java or Python based class. Of course there were some that focused on the more obscure languages such as x86 Assembly, but even then the idea was more of learning how to attack a problem. As a MCB person you should be fine with that.
For the other 5%, which is the actual language, taking two classes in two different languages will lead to crossovers. Of course a lot of what you learn in both can be applied to the others such as loops, conditionals, classes etc. However syntax is what is going to mess you up. You'll find yourself writing the syntax for the other language when you don't mean to. Simple things such as an if statement
Python:
if x > y
C++:
if (x > y)
But other than syntax issues, I really think all languages are pretty much the same. Sure people are going to disagree and that yes different languages are better at things than others but if you're not taking a graduate level class and these are both pretty basic intro classes what you learn could actually complement the other class you're taking.
But of course the biggest question for you to consider is time. Even being a full time student taking multiple heavy programming classes is not smart. Often times assignments are longer than expected or more difficult than first realized. So if you're going to have multiple long involved projects dealing with coding you may want to pick just one class. Especially seeing as a lot of what you learn in one can easily be translated to the other and vice-versa.
A:
I think you pretty much answered this question yourself:
I was told that Python is great for that but our course does not cover basics for beginners.
In other words, the Python course is not an introductory course -- it assumes you already know how the basics of programming. That's probably why the professor suggested you take the C++ course first.
A:
I come from a computational maths background, and have written sizeable (commercial and accademic) programs in both C++ and python. They are very different languages and I would probably learn one first (or only one).
Which one would depend on what you want to be able to do with the language.
If you want to build something useful with your language that is not (overly) compute or data heavy, go with python, you'll get something useful quicker.
If you need to do something useful that is either compute heavy or data heavy, then you'll probably need to go with C++. But it will take you longer to get to something to do what you need --- It will take a while to learn C++, then additional time to code data-heavy or compute-heavy code effectively.
Now some will say that python can handle data/compute heavy jobs well enough.. but in molecular biology "heavy" can mean very heavy.
Having said this, my suggestion is go with python if you can.
A:
You've got to find out what people in your field are programming with so you can leverage existing libraries/APIs/projects. It won't do you any good re-inventing the wheel in C++ or Python if there's some wicked-cool FORTRAN library out there that is standard in your field. (And, if that is the case, God help you, I'm sorry.) Anyway, the CS prof you talked to might not have any idea what computational molecular geneticists use.
| C++ and python simultaneously. Is it doable | I am totally new to programming as though I have my PhD as a molecular biologist for the last 10 years. Can someone please tell me: Would it be too hard to handle if I enrolled simultaneously in C++ and python? I am a full time employee too. Both courses start and finish on the same dates and is for 3 months. For a variety of complicated reasons, this fall is the only time I can learn both languages. Please advise.
GillingsT
Update:
A little more detail about myself: as I said I did a PhD in Molecular Genetic. I now wish to be able to obtain programming skills so that I can apply it to do bioinformatics- like sequence manipulation and pathway analysis. I was told that Python is great for that but our course does not cover basics for beginners. I approached a Comp Sci Prof. who suggested that I learn C++ first before learning Python. So I got into this dilemma (added to other logistics).
| [
"You'll get holes in the head.\nPython's data structures and memory management are radically different from C++. \nWhichever language you \"get\" first, you'll love. The other you'll hate. Indeed, you'll be confused at the weird things one language lacks that the other has. One language will be reasonable, logi... | [
7,
2,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0003416342_c++_python.txt |
Q:
smart automatic C code generator with nested if in python
I'm generating automatic C++ code from python, in particular I need to select some events for a list of events. I declare some selections:
selectionA = Selection(name="selectionA", formula="A>10")
selectionB = Selection(name="selectionB", formula="cobject->f()>50")
selectionC = selectionA * selectionB # * means AND
this generate the C++ code:
for(...) { // cicle on events
event = GetEvent(i);
bool selectionA = A>10;
bool selectionB = cobject->f()>50;
bool selectionC = (A>10) and (cobject->f()>50);
if (selectionA) { histo_selectionA->Fill(event); }
if (selectionB) { histo_selectionB->Fill(event); }
if (selectionC) { histo_selectionC->Fill(event); }
}
This is not very smart, because the smartest code will be:
bool selectionC = selectionA and selectionB
This problem seems to be simple, but it is not, because I have 100+ base selections (as selectionA or selectionB) and 300+ derived selections, and of course a derived selection can be derived from derived selection. Obvious derived selections are not derived from base selections using a regular pattern.
I understand that it is diffult to answer, but can someone give me some hints? For example: is it really necessary to write smart code? I mean, compilers are not able to optimize this code?
A:
It's unlikely that a compiler could optimize this code. Partly because cobject->f() might have side effects the compiler can't see.
You could help in a minor way by declaring your bools as const.
Otherwise, it looks like you're already overloading operators to compose selections. So it shouldn't be too hard to make a composed selection use the names of the selections its composed from instead of the expressions. This does some optimization for you and will allow the compiler to optimize further if possible, especially if you declare your selection bools as const.
You will also have to be careful to emit the code to initialize the bool flags in the same order the selection objects are created in Python. This will make sure a bool is always declared and initialized before its used later. You can do this by having a list in the Python Selection class and have the __init__ method add the new Selection to that list. Of course, if you create Selection objects that you then throw away that might be a problem. But if you keep them all, it works.
A:
Compilers might be able to optimize this code, but if you have hundreds of complicated expressions that depend on each other I would doubt that it would work that well.
But a more basic question is: Do you really need optimization? Computers are fast, and if you don't run that code very often it might very well not matter if cobject->f()>50 is run once or ten times.
On the other hand, if cobject->f() has side effects (like, for example, it prints something) the compiler will never optimize away the repeated calls and you will have to make sure that it is only called in your generated code as often as you want it to print something.
The best solution would be if your Selection class could just output name instead of formula when used as part of a derived definition. How hard or easy that is depends on your generating code.
A:
As an amendment to my comment, I don't even think you'll need a tracking variable as I suggested. Why not try this?
import string
class Selection:
selections = []
letters = string.letters[26:] + string.letters[:26]
def __init__(self, name, formula):
self.name = name
self.formula = formula
Selection.selections.append(self)
def __mul__(self, selection):
name = 'selection' + letters[len(selections)]
return Selection(name, self.name + ' and ' + selection.name)
@classmethod
def generate(c):
code = []
for selection in c.selections:
code.append('bool ')
code.append(selection.name)
code.append(' = ')
code.append(selection.formula)
code.append(';\n')
code.append('\n')
for selection in c.selections:
code.append('if (')
code.append(selection.name)
code.append(') { histo_')
code.append(selection.name)
code.append('->Fill(event); }\n')
return ''.join(code)
This only works of course, assuming you have only 52 selection objects, but that limitation only exists because this class only generates names of the form selection[A-Za-z]
A:
So, if I understand your example correctly, you are creating a set of Selection objects and then using them to generate the code?
First of all, why not just write the code in C++? As it is, you're embedding C++ expressions in Python as string variables, and using overloading mathematical operators to construct boolean expressions (the fact that you felt the need to comment that * means AND is an indication that this is a poor choice)? That's just plain ugly!
That being said, you have all the information you need -- in the Python code, selectionA knows its name is "selectionA" and selectionB knows its name is "selectionB". The only thing is, you don't provide enough context to know what type of object selectionC is. I'm assuming it's something like AndExpression, and holds references selectionA and selectionB (maybe as param1 and param2?). Just have it output "(" + self.param1.name + " && " + self.param2.name + ")".
| smart automatic C code generator with nested if in python | I'm generating automatic C++ code from python, in particular I need to select some events for a list of events. I declare some selections:
selectionA = Selection(name="selectionA", formula="A>10")
selectionB = Selection(name="selectionB", formula="cobject->f()>50")
selectionC = selectionA * selectionB # * means AND
this generate the C++ code:
for(...) { // cicle on events
event = GetEvent(i);
bool selectionA = A>10;
bool selectionB = cobject->f()>50;
bool selectionC = (A>10) and (cobject->f()>50);
if (selectionA) { histo_selectionA->Fill(event); }
if (selectionB) { histo_selectionB->Fill(event); }
if (selectionC) { histo_selectionC->Fill(event); }
}
This is not very smart, because the smartest code will be:
bool selectionC = selectionA and selectionB
This problem seems to be simple, but it is not, because I have 100+ base selections (as selectionA or selectionB) and 300+ derived selections, and of course a derived selection can be derived from derived selection. Obvious derived selections are not derived from base selections using a regular pattern.
I understand that it is diffult to answer, but can someone give me some hints? For example: is it really necessary to write smart code? I mean, compilers are not able to optimize this code?
| [
"It's unlikely that a compiler could optimize this code. Partly because cobject->f() might have side effects the compiler can't see.\nYou could help in a minor way by declaring your bools as const.\nOtherwise, it looks like you're already overloading operators to compose selections. So it shouldn't be too hard to... | [
2,
1,
0,
0
] | [] | [] | [
"c++",
"code_generation",
"compiler_construction",
"python"
] | stackoverflow_0003595174_c++_code_generation_compiler_construction_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.