Re: Addind imports to a class namespace

2009-07-13 Thread Ryan K
Thank you for your replies. I have factored out the dependency and
everything is solved.

Cheers,
Ryan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Addind imports to a class namespace

2009-07-11 Thread Ryan K
Thanks for your help Peter.

I'm thinking that perhaps this isn't a circular import and that I
don't understand importing. Here is a better explanation of my case (I
am using Django):

I have file x.py that declares classes A, B, C.

There is also a file y.py that contains two methods T, U and the class
that we are talking about above.

x.py uses a dispatcher system to connect a signal to methods T and U
in y.py so it does: from y import T, U.

y.py needs to use classes A, B, C which is basically Menu and Link
(and some other class) above so I am thinking that if in y.py I have
from x import A, B, C that will cause a circular import?

Is this not correct and if it isn't can you explain why? Does using
from ... import X, Y, Z, i.e. explicit imports avoid this problem or
does it exacerbate it?

Thanks,
Ryan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Addind imports to a class namespace

2009-07-11 Thread Ryan K
Okay so below is the acutal code. I am starting to think there is no
reason why I can't install the post_save signal in signals.py itself
and thereby avoid this issue entirely.

models.py:

class Link(CommonAbstractModel):
...

class Menu(CommonAbstractModel):


class StaticPage(CommonAbstractModel):
   ,,,

class CachedMenuXhtml(CommonAbstractModel):
   ...

post_save.connect(signals.build_menu, sender=Link)
post_save.connect(signals.build_menu, sender=Menu)



# Signlas for caching of menu XHTML

class GenerateMenuXhtml(threading.Thread):

def __init__(self, instance):
from asqcom.apps.staticpages.models import Menu, Link,
CachedMenuXhtml
self.Link = Link
self.Menu = Menu
self.CachedMenuXhtml = CachedMenuXhtml

# Function to run on post_save signal
def build_menu(sender, instance, **kwargs):
GenerateMenuXhtml(instance).start()

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


Addind imports to a class namespace

2009-07-10 Thread Ryan K
Greetings,

In order to avoid circular imports, I have a class that I want to
improve upon:

Class GenerateMenuXhtml(threading.Thread):

Subclasses a threading.Thread class to generate a menu's XHTML in
a separate
thread. All Link objects that have this menu associated with it
are gathered
and combined in an XHTML unordered list.

If the sender is of type Link, then all menus associated with that
link are
iterated through and rebuilt.

def __init__(self, instance):
from asqcom.apps.staticpages.models import Menu, Link
self.Link = Link
self.Menu = Menu

As you can see I just expose these imports by attaching them to
members of the class. There must be prettier option though where I
can just add these imoprts to the class's namespace so all methods of
any instance will have access to the imported modules.

How would I go about doing this? How can I access the namespace of any
class? Through Class.__dict__?

Thanks,
Ryan

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


Validating cElementTrees with lxml

2008-02-16 Thread Ryan K
If I have a cElementTree.ElementTree (or the one from the Standard
Library), can I use lxml's validation features on it since it
implements the same ElementTree API?

Thanks,
Ryan
-- 
http://mail.python.org/mailman/listinfo/python-list


Stripping whitespace

2008-01-23 Thread ryan k
Hello. I have a string like 'LNAME
PASTA   ZONE'. I want to create a list of those words and
basically replace all the whitespace between them with one space so i
could just do lala.split(). Thank you!

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


Re: Stripping whitespace

2008-01-23 Thread ryan k
On Jan 23, 2:04 pm, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote:
 On Wed, 23 Jan 2008 10:50:02 -0800, ryan k wrote:
  Hello. I have a string like 'LNAME
  PASTA   ZONE'. I want to create a list of those words and
  basically replace all the whitespace between them with one space so i
  could just do lala.split(). Thank you!

 You *can* just do ``lala.split()``:

Indeed you can thanks!


 In [97]: lala = 'LNAME   PASTA   ZONE'

 In [98]: lala.split()
 Out[98]: ['LNAME', 'PASTA', 'ZONE']

 Ciao,
 Marc 'BlackJack' Rintsch

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


Re: Stripping whitespace

2008-01-23 Thread ryan k
I am taking a database class so I'm not asking for specific answers.
Well I have this text tile:

http://www.cs.tufts.edu/comp/115/projects/proj0/customer.txt

And this code:

# Table and row classes used for queries

class Row(object):
def __init__(self, column_list, row_vals):
print len(column_list)
print len(row_vals)
for column, value in column_list, row_vals:
if column and value:
setattr(self, column.lower(), value)

class Table(object):
def __init__(self, table_name, table_fd):
self.name = table_name
self.table_fd = table_fd
self.rows = []
self._load_table()

def _load_table(self):
counter = 0
for line in self.table_fd:
# Skip the second line
if not '-' in line:
if counter == 0:
# This line contains the columns, parse it
column_list = line.split()
else:
# This is a row, parse it
row_vals = line.split()
# Create a new Row object and add it to the
table's
# row list
self.rows.append(Row(column_list, row_vals))
counter += 1

Because the addresses contain spaces, this won't work because there
are too many values being unpacked in row's __init__'s for loop. Any
suggestions for a better way to parse this file? I don't want to cheat
but just some general ideas would be nice. Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Stripping whitespace

2008-01-23 Thread ryan k
On Jan 23, 2:53 pm, John Machin [EMAIL PROTECTED] wrote:
 On Jan 24, 6:17 am, ryan k [EMAIL PROTECTED] wrote:

  I am taking a database class so I'm not asking for specific answers.
  Well I have this text tile:

 http://www.cs.tufts.edu/comp/115/projects/proj0/customer.txt

 Uh-huh, column-aligned output.



  And this code:

 [snip]



  Because the addresses contain spaces, this won't work because there
  are too many values being unpacked in row's __init__'s for loop. Any
  suggestions for a better way to parse this file?

 Tedious (and dumb) way:
 field0 = line[start0:end0+1].rstrip()
 field1 = line[start1:end1+1].rstrip()
 etc

 Why dumb: if the column sizes change, you have to suffer the tedium
 again. While your sample appears to pad out each field to some
 predetermined width, some reporting software (e.g. the Query Analyzer
 that comes with MS SQL Server) will tailor the widths to the maximum
 size actually observed in the data in each run of the report ... so
 you write your program based on some tiny test output and next day you
 run it for real and there's a customer whose name is Marmaduke
 Rubberduckovitch-Featherstonehaugh or somesuch and your name is mud.

 Smart way: note that the second line (the one with all the dashes)
 gives you all the information you need to build lists of start and end
 positions.

Thank you for your detailed response Mr. Machin. The teacher *said*
that the columns were supposed to be tab delimited but they aren't. So
yea i will just have to count dashes. Thank you!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Stripping whitespace

2008-01-23 Thread ryan k
On Jan 23, 3:02 pm, John Machin [EMAIL PROTECTED] wrote:
 On Jan 24, 6:57 am, ryan k [EMAIL PROTECTED] wrote:

  So yea i will just have to count dashes.

 Read my lips: *you* counting dashes is dumb. Writing your code so that
 *code* is counting dashes each time it opens the file is smart.

Okay it's almost working ...

new parser function:

def _load_table(self):
counter = 0
for line in self.table_fd:
# Skip the second line
if counter == 0:
# This line contains the columns, parse it
column_list = line.split()
elif counter == 1:
# These are the dashes
line_l = line.split()
column_width = [len(i) for i in line_l]
print column_width
else:
# This is a row, parse it
marker = 0
row_vals = []
for col in column_width:
start = sum(column_width[:marker])
finish = sum(column_width[:marker+1])
print line[start:finish].strip()
row_vals.append(line[start:finish].strip())
marker += 1
self.rows.append(Row(column_list, row_vals))
counter += 1

Something obvious you can see wrong with my start finish code?

['rimon', 'rimon', 'Barr', 'Rimon', '22 Greenside Cres., Thornhill, ON
L3T 6W9', '2', '', 'm', '102', '100
-', '22.13 1234567890', '[EMAIL PROTECTED]', '']
['UNAME', 'PASSWD', 'LNAME', 'FNAME', 'ADDR', 'ZONE', 'SEX', 'AGE',
'LIMIT', 'BALANCE', 'CREDITCARD', 'EMAIL',
 'ACTIVE']
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Stripping whitespace

2008-01-23 Thread ryan k
On Jan 23, 5:37 pm, Steven D'Aprano [EMAIL PROTECTED]
cybersource.com.au wrote:
 On Wed, 23 Jan 2008 11:05:01 -0800, Paul Rubin wrote:
  ryan k [EMAIL PROTECTED] writes:
  Hello. I have a string like 'LNAME
  PASTA   ZONE'. I want to create a list of those words and
  basically replace all the whitespace between them with one space so i
  could just do lala.split(). Thank you!

  import re
  s = 'LNAME  PASTAZONE'
  re.split('\s+', s)

 Please tell me you're making fun of the poor newbie and didn't mean to
 seriously suggest using a regex merely to split on whitespace?

  import timeit
  timeit.Timer(s.split(), s = 'one   two  three four').repeat()

 [1.4074358940124512, 1.3505148887634277, 1.3469438552856445] 
 timeit.Timer(re.split('\s+', s), import re;s = 'one   two

 three four').repeat()
 [7.9205508232116699, 7.8833441734313965, 7.9301259517669678]

 --
 Steven

The main topic is not an issue anymore.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Stripping whitespace

2008-01-23 Thread ryan k
On Jan 23, 5:37 pm, Steven D'Aprano [EMAIL PROTECTED]
cybersource.com.au wrote:
 On Wed, 23 Jan 2008 11:05:01 -0800, Paul Rubin wrote:
  ryan k [EMAIL PROTECTED] writes:
  Hello. I have a string like 'LNAME
  PASTA   ZONE'. I want to create a list of those words and
  basically replace all the whitespace between them with one space so i
  could just do lala.split(). Thank you!

  import re
  s = 'LNAME  PASTAZONE'
  re.split('\s+', s)

 Please tell me you're making fun of the poor newbie and didn't mean to
 seriously suggest using a regex merely to split on whitespace?

  import timeit
  timeit.Timer(s.split(), s = 'one   two  three four').repeat()

 [1.4074358940124512, 1.3505148887634277, 1.3469438552856445] 
 timeit.Timer(re.split('\s+', s), import re;s = 'one   two

 three four').repeat()
 [7.9205508232116699, 7.8833441734313965, 7.9301259517669678]

 --
 Steven

Much thanks to Machin for helping with the parsing job. Steven
D'Aprano, you are a prick.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Stripping whitespace

2008-01-23 Thread ryan k
On Jan 23, 6:30 pm, John Machin [EMAIL PROTECTED] wrote:
 On Jan 24, 9:50 am, ryan k [EMAIL PROTECTED] wrote:

  Steven D'Aprano, you are a prick.

 And your reasons for coming to that stridently expressed conclusion
 after reading a posting that was *not* addressed to you are .?

Because his tone is extremely condescending and quite frankly
annoying. From this post to others, his terse remarks scar this
community and fade its atmosphere of friendliness.
-- 
http://mail.python.org/mailman/listinfo/python-list


Displaying future times

2007-10-17 Thread ryan k
I have a schedule of times in the future that I want to display in a
timezone the user sets. There is a useful module
http://www.purecode.com/~tsatter/python/README.txt (at that URL) with
a function that takes seconds from the epoch and a time zone and
returns what is basically a datetime object.

My question is how to I display the seconds from the epoch for a
datetime object (which will be a datetime in the future) for the UTC
timezone?

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


Displaying future times

2007-10-17 Thread ryan k
I have a schedule of times in the future that I want to display in a
timezone the user sets. There is a useful module
http://www.purecode.com/~tsatter/python/README.txt (at that URL) with
a function that takes seconds from the epoch and a time zone and
returns what is basically a datetime object.

My question is how to I display the seconds from the epoch for a
datetime object (which will be a datetime in the future) for the UTC
timezone?

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


Re: Displaying future times

2007-10-17 Thread ryan k
On Oct 17, 1:52 pm, Steven D'Aprano [EMAIL PROTECTED]
cybersource.com.au wrote:
 On Wed, 17 Oct 2007 12:20:06 +, ryan k wrote:
  I have a schedule of times in the future that I want to display in a
  timezone the user sets. There is a useful module
 http://www.purecode.com/~tsatter/python/README.txt(at that URL) with a
  function that takes seconds from the epoch and a time zone and returns
  what is basically a datetime object.

  My question is how to I display the seconds from the epoch for a
  datetime object (which will be a datetime in the future) for the UTC
  timezone?

 Is this a trick question? Won't the answer be The same way you would for
 a datetime in the past?

 To get the number of seconds from the epoch, see the function timegm() in
 the calendar module.

 --
 Steven.

Not a trick question at all... Cheers.

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


Embedding interactive interpreter

2007-06-05 Thread Ryan K
Hi. I am trying to embed an interactive interpreter in a C++
application. I need to capture the output of int
PyRun_InteractiveOne(FILE *fp, const char *filename). Is redirecting
sys.stdout and sys.stderr after initializing the interpreter the best
way to do this?

Thanks,
Ryan

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


text wrapping help

2007-02-28 Thread Ryan K
I'm trying to text wrap a string but not using the textwrap module. I
have 24x9 matrix  and the string needs to be text wrapped according
to those dimensions. Is there a known algorithm for this? Maybe some
kind of regular expression? I'm having difficulty programming the
algorithm. Thanks,
Ryan

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


Re: text wrapping help

2007-02-28 Thread Ryan K
Okay, I was a little vague in my last post...the matrix is like a
Wheel of Fortune board and it knows nothing about newlines. After 24
characters it spills over onto the next line. Here is what I came up
with:

pre
## Wrap Text

def wrap_text(in_str, chars_line):
 wrap text 
spaces = 0
new_str = 
tmp_str = 
while True:
tmp_str = in_str[:chars_line]
if tmp_str[chars_line-1].isspace():
new_str += tmp_str
else:
spaces = 0
for ch in reversed(tmp_str):
if ch.isspace():
break
spaces += 1
tmp_str = tmp_str[:chars_line-spaces]
tmp_str +=   * spaces
new_str += tmp_str
in_str = in_str[chars_line-spaces:]
if len(in_str) = chars_line:
new_str +=   + in_str
break
return new_str


if __name__ == '__main__':

sample_text = 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.
print wrap_text(sample_text, 24)

/pre

It doesn't even run but when I go through it interactively it seems
okay. Once again, any help is appreciated.


On Feb 28, 7:06 pm, Ryan K [EMAIL PROTECTED] wrote:
 I'm trying to text wrap a string but not using the textwrap module. I
 have 24x9 matrix  and the string needs to be text wrapped according
 to those dimensions. Is there a known algorithm for this? Maybe some
 kind of regular expression? I'm having difficulty programming the
 algorithm. Thanks,
 Ryan

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


Re: text wrapping help

2007-02-28 Thread Ryan K
That works great but I need to replace the newlines with 24-(the index
of the \n) spaces.



On Feb 28, 8:27 pm, [EMAIL PROTECTED] wrote:
 On Feb 28, 4:06 pm, Ryan K [EMAIL PROTECTED] wrote:

  I'm trying to text wrap a string but not using the textwrap module. I
  have 24x9 matrix  and the string needs to be text wrapped according
  to those dimensions. Is there a known algorithm for this? Maybe some
  kind of regular expression? I'm having difficulty programming the
  algorithm.

 Try:

 import re
 sample_text = 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.

 # assume 24 is sufficiently wide:

 lines = map(lambda x: x.rstrip(),
 re.findall(r'.{1,24}(?:(?=\S)\s|$)', sample_text.replace(\n,  )))

 print \n.join(lines)

 --
 Hope this helps,
 Steven


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


Help with dbm TypeError

2006-01-09 Thread ryan k
I am writing a web application for mod_python that catalogs my home
(book) library. For now, I am using the Python dbm module to store
string representations of mod_python's req.form (using the
mod_python.publisher handler) using unique IDs as keys. In the .db
file, there is a key 'next' that holds the next key for the next form
submission. A TypeError exception is raised though when I attempt to
increment the 'next' key. This only occurs in mod_python.

This code...

self._db['next'] = str(int(self._db['next'])+1)

raises this exception

TypeError: string indices must be integers

 y = dbm.open(Test,c)
 next = 0
 y['next'] = str(next)
 y['next'] = str(int(y['next'])+1)
 y['next']
'1'
 y['next'] = str(int(y['next'])+1)
 y['next']

'2'

I do not understand the cause of this exception. I am using Python
2.3.5. Any help would be greatly appreciated.

Ryan Kaskel

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