CGI, anydbm.open() and linux file permissions

2005-01-11 Thread Derek Basch
Hello,

I have a CGI script which uses anydb.open() to create a DBM. However I get this
traceback:

 /usr/lib/python2.3/bsddb/__init__.py in
hashopen(file='/var/www/bp/predictor/tools.dbm', flag='c', mode=438,
pgsize=None, ffactor=None, nelem=None, cachesize=None, lorder=None, hflags=0)
  190 if ffactor is not None:   d.set_h_ffactor(ffactor)
  191 if nelem is not None: d.set_h_nelem(nelem)
  192 d.open(file, db.DB_HASH, flags, mode)
  193 return _DBWithCursor(d)
  194 
d = , d.open = , file =
'/var/www/bp/predictor/tools.dbm', global db = , db.DB_HASH = 2, flags = 65, mode =
438

DBAccessError: (13, 'Permission denied')
  args = (13, 'Permission denied')

The permissions on the CGI script (/usr/lib/cgi-bin/evaluator.py) are:

-rwxr-xr-x   1 bpeters bpeters  2446 Jan 11 14:42 evaluator.py

and the permissions on the target DBM creation directory
(/var/www/bp/predictor/) are:

drwxr-xr-x  2 bpeters bpeters  4096 Jan 11 14:45 predictor

Can anyone tell me what I need to do to allow the CGI script to create the DBM
in the target directory? That is short of changing everything to root.

Thanks everyone,
Derek Basch





__ 
Do you Yahoo!? 
Meet the all-new My Yahoo! - Try it today! 
http://my.yahoo.com 
 

-- 
http://mail.python.org/mailman/listinfo/python-list


spawn syntax + os.P_WAIT mode behavior + spawn stdout redirection

2005-01-20 Thread Derek Basch
Hello,

*First question*

If the syntax of spawnl is:

spawnl(mode, path, ...)

Why does everyone write it like:

os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')

or:

os.spawnl(os.P_WAIT, "/var/www/db/smm/smm_train", "smm_train",
"SMMTrainInput.xml")

How is the first 'cp' a path to a file? why does the desired executable have to
be named again as the first parameter?

*Second question*

I have a script test.py which calls another script sleep.py using a spawn.

--
#test.py
import os

os.spawnv(os.P_WAIT, "/var/www/db/cgi-bin/sleep.py", ["python", "sleep.py"])
#pid = os.spawnl(os.P_WAIT, 'sh', 'sh', '-cv', 'sleep 10; echo fark >
/tmp/test.out')
--

--
#sleep.py
import time

time.sleep(10)
--

I would expect that the test.py script should take 10sec to return. However it
returns immediatly. Perhaps I am calling the sleep.py script incorrectly?
Shouldn't it take 10sec to execute since the spawn mode argument is os.P_WAIT?

*Third question*

If I uncomment the second spawn call in test.py I do not get any output to
/tmp/test.out and it also returns immediatly. Can anyone tell me why? 

Thank You Mighty Python Guru's,
Derek Basch



__ 
Do you Yahoo!? 
Yahoo! Mail - now with 250MB free storage. Learn more.
http://info.mail.yahoo.com/mail_250
-- 
http://mail.python.org/mailman/listinfo/python-list


CGI and HTTP Header Location redirects

2005-02-03 Thread Derek Basch
Hello,

I have been dealing with some strange behavior using CGI, python and an HTTP
Header "Location:" redirect on an Apache 1.3 server.

If I call a CGI script and perform a "Location:" redirect the script seems to
silently run off the tracks immediately after the redirect. For example "0.xml"
and "1.xml" are created when there is no redirect and only "0.xml" is created
when a redirect does occur (see below).

Also, after enabling suEXEC on the apache server the script executes perfectly
with the redirect. Can anyone explain this behavior? I would guess that it is
related to apache user rights but I can't find any reference to such problems
via Google.

Thanks everyone!,
Derek Basch

-

#! /usr/bin/python

import sys
import cgitb

class Trainer:

def train(self):
fs = open("/tmp/0.xml", "w")
fs.close()
##  print "Location: " + "http://www.yahoo.com"; + "\n\n"
sys.stdout.flush()
fs = open("/tmp/1.xml", "w")
fs.close()

def main():
try:
cgitb.enable()  
trainer = Trainer()
trainer.train()

except Exception, inst:
cgitb.handler()

if __name__ == '__main__':
main()




__ 
Do you Yahoo!? 
Take Yahoo! Mail with you! Get it on your mobile phone. 
http://mobile.yahoo.com/maildemo 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: CGI and HTTP Header Location redirects

2005-02-04 Thread Derek Basch
A... I should have been more specific before. The Apache error log doesn't
produce an error. You are probably correct that it is most likely an
Apache/Unix problem. I thought perhaps someone had maybe run into this before
since it seems like such a basic function to not work. Thanks for the help.

Paul Rubin wrote:
> Derek Basch <[EMAIL PROTECTED]> writes:
> 
>>Also, after enabling suEXEC on the apache server the script executes
>>perfectly with the redirect. Can anyone explain this behavior? I
>>would guess that it is related to apache user rights but I can't
>>find any reference to such problems via Google.
> 
> 
> Apache probably isn't able to run the cgi because of lack of exec
> permission or something like that.  The best way to diagnose such
> probs is by checking the apache error log, if you have access to it.
> 
> Best newsgroup for this type of question is
> comp.infosystems.www.servers.unix.  Lots of apache experts hang out there.



__ 
Do you Yahoo!? 
Yahoo! Mail - now with 250MB free storage. Learn more.
http://info.mail.yahoo.com/mail_250
-- 
http://mail.python.org/mailman/listinfo/python-list


Minidom empty script element bug

2005-03-15 Thread Derek Basch
Hello All,

I ran into a problem while dynamically constructing XHTML documents using
minidom. If you create a script tag such as:

script_node_0 = self.doc.createElement("script")
script_node_0.setAttribute("type", "text/javascript")
script_node_0.setAttribute("src", "../test.js")

minidom renders it as:



Which is incorrect because:

XHTML 1.0 specs, Appendix C
[EMAIL PROTECTED]
C.3 Element Minimization and Empty Element Content

Given an empty instance of an element whose content model is not EMPTY (for
example, an empty title or paragraph) do not use the minimized form (e.g.
use   and not )
[EMAIL PROTECTED]

reference for further explanation:
http://lists.evolt.org/archive/Week-of-Mon-20020304/105951.html

So, the rendered page completely fails on IE6 because it actually handles the
empty script element correctly. Mozilla handles the element incorrectly and
instantiates the javascript.

How do I get minidom to NOT render an empty script element? Should I submit a
bug report?

Thanks for the help,
Derek Basch






__ 
Do you Yahoo!? 
Yahoo! Small Business - Try our new resources site!
http://smallbusiness.yahoo.com/resources/ 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Minidom empty script element bug

2005-03-15 Thread Derek Basch

Martin v. Löwis wrote:
> Derek Basch wrote:
> > XHTML 1.0 specs, Appendix C
> > [EMAIL PROTECTED]
> > C.3 Element Minimization and Empty Element Content
> >
> > Given an empty instance of an element whose content model is not
EMPTY (for
> > example, an empty title or paragraph) do not use the minimized form
(e.g.
> > use   and not )
> > [EMAIL PROTECTED]
>
> I'd like to point out that this is *not* a minidom bug. minidom
cannot
> possibly know that the document type is XHTML, and that strange,
non-XML
> rules apply to XHTML (i.e. rules which are not present in XML
itself).
>
> I'd also like to point out that XHTML Appendix C is informative (i.e.
> non-normative), meaning that failure to comply to it does not imply
> non-compliance with XHTML. An XML file which uses the minimized form
> for the script element is still proper, well-formed, valid XHTML.
>
> > How do I get minidom to NOT render an empty script element? Should
I submit a
> > bug report?
>
> That said, I think there is a simple solution: add an empty Text node
> to the script element:
>
> script_node_0.appendChild(doc.createText(u""))
>
> [Disclaimer: this is untested; from reading the source, I think it
> should work]
>
> Regards,
> Martin


Thanks Martin. That fixed it. I had to change your code a bit to this:

script_node_0.appendChild(self.doc.createTextNode(""))

maybe you meant createTextNode?

I started digging through the dom modules on this path:

XHTMLPrettyPrint -> XHTMLPrinter -> Printer

and found this comment:

try:
#The following stanza courtesy Martin von Loewis
import codecs # Python 1.6+ only
from types import UnicodeType

So I guess you are pretty qualified to answer my question! You are
correct that this is not a minidom bug now that I think about it.

However, it seems proper that XHTMLPrinter (or some other module)
should allow the developer to use either normative or non-normative
XHTML design guidlines to achieve some sane degree of HTML user agent
compatablilty. Maybe something like this in Printer.py:

def visitElement(self, node):
...
if len(node.childNodes):
self._write('>')
self._depth = self._depth + 1
self.visitNodeList(node.childNodes)
self._depth = self._depth - 1
if not self._html or (node.tagName not in
HTML_FORBIDDEN_END):
not (self._inText and inline) and self._tryIndent()
self._write('' % node.tagName)
elif not self._html and node.tagName not in
XHTML_NON_NORMATIVES:
self._write('/>')
elif node.tagName not in HTML_FORBIDDEN_END:
self._write('>' % node.tagName)
else:
self._write('>')

of course this would only take care of the "C.3. Element Minimization
and Empty Element Content" guideline but you get the general idea.

Anyways, thanks for the help again and feel free to shoot down my
suggestions :)

Derek Basch

--
http://mail.python.org/mailman/listinfo/python-list


Re: Minidom empty script element bug

2005-03-16 Thread Derek Basch
Cross post from XML-SIG:

--- Walter Dörwald <[EMAIL PROTECTED]> wrote:
> Martin v. Löwis sagte:
> > Derek Basch wrote:
> > >[...]
> >> How do I get minidom to NOT render an empty script element? Should
I
> submit a bug report?
> >
> > That said, I think there is a simple solution: add an empty Text
node to
> the script element:
> >
> > script_node_0.appendChild(doc.createText(u""))
> >
> > [Disclaimer: this is untested; from reading the source, I think it
should
> work]
>
> If this doesn't work, you might want to try XIST
> (http://www.livinglogic.de/Python/xist)
> instead of minidom. XIST knows that the script element is not EMPTY,
and when
> the
> output is in HTML compatible XML an end tag will be produced:
>
> >> from ll.xist.ns import html
> >>> print html.script(type="text/javascript",
> src="../test.js").asBytes(xhtml=1)
> 
>
> Using pure XML mode gives:
>
> >>> print html.script(type="text/javascript",
> src="../test.js").asBytes(xhtml=2)
> 
>
> Bye,
>Walter Dörwald

Wow! XIST is very elegant. Perfectly designed for what it is supposed
to do.

"XIST is an extensible HTML/XML generator written in Python."

I guess there isn't much point in "fixing" the pyXML XHTMLPrinter when
something as cool as XIST exists (pun intended).

Kid also seems really neat. I like the TAL like features. However, it
seems less mature than XIST.

There seems to be lots of functionality crossover between the two but
it is good that there is enough demand for XML output functionality in
python to support two distinct modules.

Thanks Everyone!,
Derek Basch

--
http://mail.python.org/mailman/listinfo/python-list


string join() method

2005-03-23 Thread Derek Basch
Can anyone tell me why this CGI code outputs a blank page?

self.output = []
self.setContentType("text/plain")
ascii_temp.seek(0)
self.output.extend(ascii_temp.read())
print ''.join(self.output)

def setContentType(self, type="text/xml"):
self.output.extend(["Content-type: ", type, "\n\r"])
-

but this code works?:
-
self.output = []
self.setContentType("text/plain")
print ''.join(self.output)
ascii_temp.seek(0)
print ascii_temp.read()

def setContentType(self, type="text/xml"):
self.output.extend(["Content-type: ", type, "\n\r"])
-

ascii_temp is just some tab seperated data:
-
Allele  Seq:Start-End   Length  SequenceScore
A01 1: 1-8  8   1410538.0
A01 1: 2-9  8   1410538.0
-

Thanks everyone.
Derek Basch

-- 
http://mail.python.org/mailman/listinfo/python-list


Minidom output of XML escaped characters

2005-03-24 Thread Derek Basch
Hello,

If I want minidom to output XHTML that includes normally XML escaped
characters how would I do it?

For instance if I use doc.createCDATASection() I get:



and without the CDATASection:

<!--#include virtual="/top.html" -->

when I really need:



Any suggestions?

Thanks,
Derek Basch

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Minidom output of XML escaped characters

2005-03-25 Thread Derek Basch
Thanks effbot. I haven't had much use for XML comments so far and I
guess other people haven't either because it seems they are hardly ever
mentioned.

http://groups-beta.google.com/groups?hl=en&lr=&c2coff=1&q=xml+comment+python&qt_s=Search+Groups

-- 
http://mail.python.org/mailman/listinfo/python-list


Counting iterations

2005-04-08 Thread Derek Basch
Is there a better way to count iterations that this?:

pets = 0
for i in pets:
pets += 1
print "pet" + "#" + pets

Thanks,
Derek Basch

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Counting iterations

2005-04-08 Thread Derek Basch
ooops you are right. Should have been:

pets = ["cat", "dog", "bird"]
num_pets = 0
for i in pets:
num_pets += 1
print "pet" + "#" + num_pets

That's the problem with one offs. I don't read them :).

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Counting iterations

2005-04-10 Thread Derek Basch
Interesting stuff Andrew. I do generally avoid string concantination
for the reason listed in the Python Performance Tips but your analysis
kinda puts that in question. Such a dense discussion for me just trying
to find the enumerate() function :). I guess that is why the python
list is so great. You guys always rip my code apart and correct my
style. Even if it is just a stupid one off example.

Thanks everyone,
Derek Basch

-- 
http://mail.python.org/mailman/listinfo/python-list


List comprehension and FieldStorage

2005-04-26 Thread Derek Basch
Given this FieldStorage object:

FieldStorage(None, None, [MiniFieldStorage('Checkbox1', 'on'),
MiniFieldStorage('Checkbox2', 'on')])

I am trying to cgi.urlencode the FieldStorage object to POST to another
cgi script. The documentation for urlencode,
http://docs.python.org/lib/module-urllib.html , says that urlencode
takes a mapping object or a list of double tuples. I see that I could
use cgi.parse_qs and cgi.parse_qsl to create these object types. Should
I just use that or should I continue using FieldStorage? Also how would
I create an object of either type from a FieldStorage object? Here is
my attempt at creating the double tuple list (It sucksI know):

print [(key, value) for key, value in form.keys() and form[key].value]

Thanks for the help,
Derek Basch

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List comprehension and FieldStorage

2005-04-27 Thread Derek Basch
bump

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List comprehension and FieldStorage

2005-04-27 Thread Derek Basch
Sorry Peter. I will refrain from nudging in the future. I did spend
time at the interactive prompt and got nothing. Maybe I will have
better luck next time.

-- 
http://mail.python.org/mailman/listinfo/python-list


Matplotlib logarithmic scatter plot

2006-02-27 Thread Derek Basch
Can anyone give any suggestions on how to make a logarithmic (base 10)
x and y axis (loglog) plot in matplotlib? The scatter function doesn't
seem to have any log functionality built into it.

Thanks,
Derek Basch

P.S. I suck at math so feel free to make me feel stupid if it is really
easy to do :).

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Matplotlib logarithmic scatter plot

2006-02-27 Thread Derek Basch
Thanks for the reply. I need a scatter plot though. Can that be done?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Matplotlib logarithmic scatter plot

2006-02-27 Thread Derek Basch
Great! That worked fine after I played with it for a bit. One last
question though. How do I label the ticks with the product of the
exponentiation? For instance:

100 

instead of 

10**2

Thanks for all the help,
Derek Basch

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Matplotlib logarithmic scatter plot

2006-02-28 Thread Derek Basch
Thanks again. Here is the finished product. Maybe it will help someone
in the future:

from pylab import *

def log_10_product(x, pos):
"""The two args are the value and tick position.
Label ticks with the product of the exponentiation"""
return '%1i' % (x)

ax = subplot(111)
# Axis scale must be set prior to declaring the Formatter
# If it is not the Formatter will use the default log labels for ticks.
ax.set_xscale('log')
ax.set_yscale('log')

formatter = FuncFormatter(log_10_product)
ax.xaxis.set_major_formatter(formatter)
ax.yaxis.set_major_formatter(formatter)

ax.scatter( [3, 5, 70, 700, 900], [4, 8, 120, 160, 200], s=8, c='b',
marker='s', faceted=False)
ax.scatter( [1000, 2000, 3000, 4000, 5000], [2000, 4000, 6000, 8000,
1000], s=8, c='r', marker='s', faceted=False)

ax.set_xlim(1e-1, 1e5)
ax.set_ylim(1e-1, 1e5)
grid(True)
xlabel(r"Result", fontsize = 12)
ylabel(r"Prediction", fontsize = 12)

show()

-- 
http://mail.python.org/mailman/listinfo/python-list


Rounding up to the nearest exact logarithmic decade

2006-02-28 Thread Derek Basch
Given a value (x) that is within the range (1e-1, 1e7) how do I round
(x) up to the closest exact logarithmic decade? For instance:

10**3 = 1000
x = 4978
10**4 = 1

x = 1

Thanks Everyone!
Derek Basch

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rounding up to the nearest exact logarithmic decade

2006-02-28 Thread Derek Basch
Thanks effbot. I knew their had to be something buried in the math
module that could help. ceil() it is!



-- 
http://mail.python.org/mailman/listinfo/python-list


Is it better to use class variables or pass parameters?

2006-03-01 Thread Derek Basch
This one has always bugged me. Is it better to just slap a "self" in
front of any variable that will be used by more than one class method
or should I pass around variable between the methods?

FlamewarNOW!

jk, I really do want other opinions.

Thanks,
Derek

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Matplotlib logarithmic scatter plot

2006-03-01 Thread Derek Basch
Good tip John. Hopefully it will help someone out. Thanks again.
Derek Basch

-- 
http://mail.python.org/mailman/listinfo/python-list


Multiple Inheritence and data attributes

2005-05-06 Thread Derek Basch
Hello Everyone,

Given:

class A:
def __init__(self):
super(A, self).__init__()
self.dog = "fluffy"
def changeDog(self):
self.dog = "spike"

class B:
def __init__(self):
super(B, self).__init__()

class C(object, A, B):
def __init__(self):
super(C, self).__init__()
def printDog(self, cls):
print cls.dog

c = C()
c.printDog(c)

How can I access data attributes of superclasses? I can see the
function attributes of the superclasses:

['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',
'__hash__', '__init__', '__module__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__',
'changeDog', 'printDog']

but not the data attributes. Shouldn't the derived class have that data
attributes of superclasses? I guess I am not understanding the python
implementation.

Thanks,
Derek

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it better to use class variables or pass parameters?

2006-03-13 Thread Derek Basch
Wow! Thanks everyone. Such coherent and philisophical answers. I will
read them all over on a lazy sunday as this type ethereal stuff hurts
my head after about 30 seconds. All the gurus on the python list are so
friggin' smart. This should improve my coding after I digest it all.
Thanks Again!

Derek Basch

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it better to use class variables or pass parameters?

2006-03-15 Thread Derek Basch
So, if I am understanding what everyone is saying here. I should do my
best to distinguish between values that are part of the "state" of an
object and values that are more disposable and can change for each
computation of a value. So if I create an instance of a "wallet" class
and the color of the wallet is "red". The "red" value would be ideal as
a class variable as it is tied to the state of that wallet instance.
However, if the wallet class contains a function to compute the tax on
a purchased item, the purchase price would be a good example of a
passed parameter value. Am I on the right track?

Thanks,
Derek Basch

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it better to use class variables or pass parameters?

2006-03-15 Thread Derek Basch
One more question everybody. Say you have a class that performs a
series of evaluations on several strings of peptides. Let's say for the
sake of argument:

DMCDIYLLY
FQPQNGQFI
RHPENPNLL

Heres the class:

class PeptideEvaluator:

def evaluate(self, peptide):
peptide_name = peptide + "Rules!"
result1 = self.test1(peptide, peptide_name)
result2 = self.test2(peptide, peptide_name)
result3 = self.test3(peptide, peptide_name)

def test1(self, peptide, peptide_name):
f = open(peptide_name + ".txt", "w")
f.write(peptide)
f.close()

def test2(self, peptide, peptide_name):
f = open(peptide_name + ".txt", "w")
f.write(peptide)
f.close()

def test3(self, peptide, peptide_name):
f = open(peptide_name + ".txt", "w")
f.write(peptide)
f.close()

So, you instantiate a class called "PeptideEvaluator" and pass in each
string to its "evaluate" method. Now you have to repeatedly pass the
peptide and peptide_name to each function. According to what everyone
has said declaring them as class variables is bad because they are not
related to the state of the "PeptideEvaluator". How can I avoid having
to pass the same parameters all over a class? I can';t quite seem to
wrap my head around this one.

Thanks again everyone,
Derek Basch

-- 
http://mail.python.org/mailman/listinfo/python-list


Counting nested loop iterations

2006-03-16 Thread Derek Basch
What is the best way to count nested loop iterations? I can only figure
to use an index but that seems kludgy.

index = 0
for animal in zoo:
for color in animal:
index += 1

Thanks,
Derek Basch

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Counting nested loop iterations

2006-03-16 Thread Derek Basch

Fredrik Lundh wrote:

> what's kludgy with using a counter to count things ?

Ohhh, nothing in particular. Just seeing if there is a better way to do
it.

> (the real question here is of course why you need the counter.  what's
> the loop doing?  if the code you posted is all you have, you can replace
> it with index = sum(len(animal) for animal in zoo), but I assume you want
> to do more stuff in there...)
>
> 

Yes, I am doing more. Your example assumes that all that animals have
the same amount of colors. Not a bad assumption considering I didn't
say anything about that. Looks like good old counters are they way to
go then.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Counting nested loop iterations

2006-03-16 Thread Derek Basch
> Depending on the types of the containers in question, you could use:
>
>   len(zoo) * len(animal)

I think this would give me the total iterations but I wouldn't be able
to get a running count. Correct?

Thanks for the reply,
Derek Basch

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Counting nested loop iterations

2006-03-16 Thread Derek Basch

Carl Banks wrote:
> But even the clear version isn't as nearly clear and straightforward as
> the nested fors with the counter.  I wouldn't forsake that clarity just
> so it isn't "kludgy".
>
>
> Carl Banks

Yeah, looks like using the counters is clearer. Thanks for the opinions
everyone!

Derek Basch

-- 
http://mail.python.org/mailman/listinfo/python-list


Remove integer from float number

2006-03-23 Thread Derek Basch
How can I return:

".666"

from float:

"0.666"

This is what I have so far:

>>> "%.6f" % x

Thanks Everyone,
Derek Basch

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Remove integer from float number

2006-03-23 Thread Derek Basch
Ahh yes you have to put parenthases around the string formatting to
remove the integer using indexes. Thanks, that's just what I needed!

Derek Basch

-- 
http://mail.python.org/mailman/listinfo/python-list