Re: [Tutor] A Django Beginner View Question

2010-07-29 Thread Evert Rol
Consider using the django-users Google group for typical Django questions 
(unless you figure they're really about Python). Will likely get you better or 
more answers.
Anyway:

> Hi
> 
> I am building my first Django site which has a lot of effectively 'static' 
> pages where I just want to make the meta data and text editable.

Sounds like you actually want a generic view. Search for the link on the front 
page of the Django docs. Generic views point your straight from urls.py to the 
template, bypassing the views.py.
For the second part, you can use the keyword "editable" and set it to False in 
de model below, for fields you don't want to be edited in the admin (but you'll 
then have to figure out yourself how to enter the other fields).


> The model is
> 
> models.py
> 
> class About(models.Model):
>page_title = models.CharField(max_length=900, help_text='Text at top of 
> browser window')
>meta_keywords = models.CharField(max_length=900, help_text='Keywords (for 
> SEO)')
>meta_description = models.CharField(max_length=160, help_text='Description 
> (for SEO)')
>logo_header = models.CharField(max_length=900, help_text='H1 Header (for 
> SEO)')
>header = models.CharField(max_length=60)
>body = models.TextField()
>last_updated = models.DateTimeField(default=datetime.datetime.now, 
> primary_key=True)
> 
>class Meta:
>get_latest_by = "last_updated"
>verbose_name_plural = "About Page"
> #managed = False
> 
> def __unicode__(self):
>return self.title
> 
> 
> I'm trying to understand how to either write a model that only allows a 
> single entry or write a view that will take either a single entry or the most 
> recent entry.

Not clear what you want to do: "a model that allows a single entry"? Is that a 
model which has one, and only one, entry in the database? That doesn't really 
make much sense. Better do that through your view, as below (again, consider a 
generic view).


> views.py
> 
> def about(request):
>   return render_to_response('about.html',
>   { 'About' : 
> About.objects.latest() })
> urls.py
> 
>(r'^about/$', 'harkproject.cms.views.about'),
> 
> Much appreciated
> Al Macmillan

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Help - How to end program

2010-07-29 Thread Alan Gauld

"Jason MacFiggen"  wrote

Python keeps looping when it gets past the int 0, how do I end the 
program

when it the int 0 or > 0.

   while True:
   if mo_hp < 0:
   print "The Lich King has been slain!"
   elif my_hp < 0:


/etc...

When using a while True loop you need ttto have an explicit break
statement somewhere to get out. Personally I like to keep that 
statement

near the top of the loop if possible - just so that I can
find it easily!

So in your case I'd add a test like

if mo_hp >= 0:
   break

right at the top of the loop.

If there were other statements after the loop these would then
get executed but since you don't your program will naturally 
terminate.


Note that if you had an else clause in your while loop(quite unusual)
it does not get executed after a break - the only useful feature I've
found for a loop else condition!

ie

while True:
break
else:  print 'never executed'
print 'exited'

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Calculating and returning possible combinations of elements from a given set

2010-07-29 Thread ZUXOXUS
2010/7/28 Dave Angel 

> ZUXOXUS wrote:
>
>> 
>>
>> My doubt now is whether I can change the way python show the combinations.
>>
>> I mean, here's what python actually does:
>>
>>
>>
>>> for prod in itertools.product('abc', repeat=3):
>
>
 print(prod)
>>
>> ('a', 'a', 'a')
>> ('a', 'a', 'b')
>> ('a', 'a', 'c')
>> ('a', 'b', 'a')
>> ('a', 'b', 'b')
>> ('a', 'b', 'c')
>> [...] etc.
>>
>>
>> what if I want the combinations listed in a... well, in a list, kind of
>> like
>> this:
>>
>> ('aaa', 'aab', aac', 'aba', 'abb', 'abc' [...]etc.)
>>
>> can I do that?
>>
>> I have checked how the function works (see below), perhaps I have to just
>> change couple of lines of the code and voilá, the result displayed as I
>> want... But unfortunately I'm too newbie for this, or this is too
>> hardcore:
>>
>> def product(*args, **kwds):
>># product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
>># product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
>>pools = map(tuple, args) * kwds.get('repeat', 1)
>>result = [[]]
>>for pool in pools:
>>result = [x+[y] for x in result for y in pool]
>>for prod in result:
>>yield tuple(prod)
>>
>>
>> Any ideas will be very much appreciated.
>>
>> 
>>
> Well itertools.product() already returns an iterator that's equivalent to a
> list of tuples.   You can print that list simply by doing something like:
> print list(itertools.product('abc', repeat=3))
>
> So your question is how you can transform such a list into a list of
> strings instead.
>
> so try each of the following.
>
>
> for prod in itertools.product('abc', repeat=3):
>   print "".join(prod)
>
> print ["".join(prod) for prod in itertools.product('abc', repeat=3)]
>
> DaveA
>
>
***

Hi DaveA, the second option returns exactly the result I wanted:

>>> print(["".join(prod) for prod in itertools.product('abc', repeat=3)])
['aaa', 'aab', 'aac', 'aba', 'abb', 'abc', 'aca', 'acb', 'acc', 'baa',
'bab', 'bac', 'bba', 'bbb', 'bbc', 'bca', 'bcb', 'bcc', 'caa', 'cab', 'cac',
'cba', 'cbb', 'cbc', 'cca', 'ccb', 'ccc']

Thank you very much.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] finding duplicates within a tuple of tuples

2010-07-29 Thread Norman Khine
hello,

i have this tuple:

http://paste.lisp.org/+2F4X

i have this, which does what i want:

from collections import defaultdict

d = defaultdict(set)
for id, url in result:
d[url].add(id)
for url in sorted(d):
if len(d[url]) > 1:
print('%d -- %s' % (len(d[url]), url))

so here the code checks for duplicate urls and counts the number of occurences.

but i am sort of stuck in that i want to now update the id of the
related table and update the

basically i have two tables:

id, url
24715L, 'http://aqoon.local/muesli/2-muesli-tropical-500g.html'
24719L, 'http://aqoon.local/muesli/2-muesli-tropical-500g.html'

id, tid,
1, 24715L
2, 24719L

so i want to first update t(2)'s tid to t(1)'s id for each duplicate
and then delete the row id = 24719L

thanks

-- 
˙uʍop ǝpısdn p,uɹnʇ pןɹoʍ ǝɥʇ ǝǝs noʎ 'ʇuǝɯɐן sǝɯıʇ ǝɥʇ puɐ 'ʇuǝʇuoɔ
ǝq s,ʇǝן ʇǝʎ
%>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or
chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] )
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] FTP from mainframe

2010-07-29 Thread Steve Bricker
  BODY { font-family:Arial, Helvetica, sans-serif;font-size:12px;
}This is my first attempt to FTP a file from a mainframe.  The code:
 import ftplib
session = ftplib.FTP('company.lan.com','userid','passwd')
myfile = open('PC.filename','w')
session.retrlines("RETR 'mainframe.filename'", myfile)
myfile.close()
session.quit()
 The resulting error is:
 Traceback (most recent call last):
  File "ftp_from_mf.py", line 5, in 
session.retrlines("RETR 'mainframe.filename'", myfile)
  File "c:python26libftplib.py", line 428, in retrlines
callback(line)
TypeError: 'file' object is not callable

 Not sure what I'm missing.
 Steve Bricker  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] finding duplicates within a tuple of tuples

2010-07-29 Thread Peter Otten
Norman Khine wrote:

> hello,
> 
> i have this tuple:
> 
> http://paste.lisp.org/+2F4X
> 
> i have this, which does what i want:
> 
> from collections import defaultdict
> 
> d = defaultdict(set)
> for id, url in result:
> d[url].add(id)
> for url in sorted(d):
> if len(d[url]) > 1:
> print('%d -- %s' % (len(d[url]), url))
> 
> so here the code checks for duplicate urls and counts the number of
> occurences.
> 
> but i am sort of stuck in that i want to now update the id of the
> related table and update the
> 
> basically i have two tables:
> 
> id, url
> 24715L, 'http://aqoon.local/muesli/2-muesli-tropical-500g.html'
> 24719L, 'http://aqoon.local/muesli/2-muesli-tropical-500g.html'
> 
> id, tid,
> 1, 24715L
> 2, 24719L
> 
> so i want to first update t(2)'s tid to t(1)'s id for each duplicate
> and then delete the row id = 24719L

You can use another dictionary that maps ids associated with the same url to 
a canonical id.

from collections import defaultdict

url_table = [
(24715,"http://aqoon.local/muesli/2-muesli-tropical-500g.html";),
(24719,"http://aqoon.local/muesli/2-muesli-tropical-500g.html";),
(24720,"http://example.com/index.html";)
]

id_table = [
(1, 24715),
(2, 24719),
(3, 24720)
]

dupes = defaultdict(set)
for uid, url in url_table:
dupes[url].add(uid)

lookup = {}
for synonyms in dupes.itervalues():
if len(synonyms) > 1:
canonical = min(synonyms)
for alias in synonyms:
assert alias not in lookup
lookup[alias] = canonical

ids = [(id, lookup.get(uid, uid)) for id, uid in id_table]
print ids
urls = [(min(synonyms), url) for url, synonyms in dupes.iteritems()]
print urls

Note that if you use a database for these tables you can avoid creating 
duplicates in the first place.

Peter

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] finding duplicates within a tuple of tuples

2010-07-29 Thread Gregory, Matthew
Norman Khine wrote:
> basically i have two tables:
> 
> id, url
> 24715L, 'http://aqoon.local/muesli/2-muesli-tropical-500g.html'
> 24719L, 'http://aqoon.local/muesli/2-muesli-tropical-500g.html'
> 
> id, tid,
> 1, 24715L
> 2, 24719L
> 
> so i want to first update t(2)'s tid to t(1)'s id for each duplicate
> and then delete the row id = 24719L

Assuming your first table is 'd' and your second table is 't', could you do 
this?

for url in sorted(d):
# Get the ID of the first element for updating t's records
update_id = d[url][0]

# For all duplicate URLs, remove the dict item from d and
# update t's records
while len(d[url]) > 1:
pop_id = d[url].pop()
for (k, v) in t.iteritems():
if v == pop_id:
t[k] = update_id

There may be a more terse way of updating the values in t that I'm not seeing 
right now.

matt
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] FTP from mainframe

2010-07-29 Thread bob gailer

On 7/29/2010 12:34 PM, Steve Bricker wrote:

This is my first attempt to FTP a file from a mainframe.  The code:

import ftplib
session = ftplib.FTP('company.lan.com','userid','passwd')
myfile = open('PC.filename','w')
session.retrlines("RETR 'mainframe.filename'", myfile)
myfile.close()
session.quit()

The resulting error is:

Traceback (most recent call last):
  File "ftp_from_mf.py", line 5, in 
session.retrlines("RETR 'mainframe.filename'", myfile)
  File "c:\python26\lib\ftplib.py", line 428, in retrlines
callback(line)
TypeError: 'file' object is not callable


According to the ftplib module documentation:

retrlines(command[, callback])
Retrieve a file or directory listing in ASCII transfer mode. command 
should be an appropriate RETR command (see retrbinary()) or a command 
such as LIST, NLST or MLSD (usually just the string 'LIST'). The 
callback function is called for each line, with the trailing CRLF 
stripped. The default callback prints the line to sys.stdout.


IOW callback must be a function. You are passing a file object. I will 
guess that you want:


def writer(line):
  myfile.write(line + '\n')

session.retrlines("RETR 'mainframe.filename'", writer)

The documentation is in error in that it does not explicitly state that 
a line is passed to the callback function as an argument. I am assuming 
that is the case.


--
Bob Gailer
919-636-4239
Chapel Hill NC

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] FTP from mainframe

2010-07-29 Thread Alan Gauld


"Steve Bricker"  wrote 

}This is my first attempt to FTP a file from a mainframe.  


Thats one more than me!


The resulting error is:
   session.retrlines("RETR 'mainframe.filename'", myfile)
 File "c:python26libftplib.py", line 428, in retrlines
   callback(line)
TypeError: 'file' object is not callable



The error says that its expecting a callable and you are 
passing a file object. My guess is you need to create a 
function that writes to the file and pass that to ftp.
You could use myfile.write maybe - thats what the 
documentation does for a binary file...


HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] FTP from mainframe

2010-07-29 Thread Bill Campbell
On Thu, Jul 29, 2010, bob gailer wrote:
>
>   On 7/29/2010 12:34 PM, Steve Bricker wrote:
>
> This is my first attempt to FTP a file from a mainframe.  The code:
> import ftplib

The easiest way I've found to get a file via ftp in python is to
user urllib, not ftplib.  Something like this (add error checking).

import urllib, os
fname='something.pdf'
url = 'ftp://%...@%s:%s/%s' % ('john', 'secret', 'example.com', fname)
# f will have a temporary file name, and h the headers
(f, h) = urllib.urlretrieve(url)
os.rename(f, fname)

Of course this works for http by simply changing the url.

Bill
-- 
INTERNET:   b...@celestial.com  Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
Voice:  (206) 236-1676  Mercer Island, WA 98040-0820
Fax:(206) 232-9186  Skype: jwccsllc (206) 855-5792

If you want government to intervene domestically, you're a liberal.  If you
want government to intervene overseas, you're a conservative.  If you want
government to intervene everywhere, you're a moderate.  If you don't want
government to intervene anywhere, you're an extremist -- Joseph Sobran
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] problem with simple script

2010-07-29 Thread Richard D. Moores
On Wed, Jul 28, 2010 at 08:35, Richard D. Moores  wrote:

> Now I'll dig into all the help I received. I see an *args in Steven's
> detailed reply. That'll take some reviewing to understand.

Here's my slight revision of Steven's script (see my note, lines 9-14)
-- revised only because I wanted it to handle the case where the user
(me) entered the interval bounds in the wrong order, e.g., 10, 5
instead of 5, 10.  I've also added a way ('r') for the user to choose
to get another random number in the same interval without having to
reenter the bounds: . Then I
needed a way ('c') to choose to change the bounds after 'r' had been
used. I used a flag (lines 42, 53, 55) to accomplish these additions.
Was there a better way? Should I have written a couple of extra
functions instead of using the flag? Are flags unpythonic?

I've learned a lot from his script, and hope to learn more -- I'm
still grappling with the  *args  of line 46.

What I've learned so far:
1. To separate the front end (for the user) from the back end. See his
note on line 3.
2. The use of maxsplit with str.split(). Line 29.
3. Using the return of a function to call another function. Line 38.
4. In main(), he assigns the prompt to a variable _before_ the while
loop (line 41), so the assignment is done only once, rather than each
time through the loop. Not a biggie in this script, but a good thing
to learn, I think.

So thanks, Steven!

Now, on to *args!

Dick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] A better way for greatest common divisor

2010-07-29 Thread David Hutto
This is basically to get feedback, on a better way to show the
greatest common divisor in fraction, in order to reduce it fully, than
the one I've come up with. I'm sure there are better ways, so if you
have simpler method, or critique of what I've done, let me know.


'''Greatest Common Divisor Function'''
def gcd(num,den):
while True:
'''Find if numerator is less than denominator'''
if num < den:
'''Range backwards from larger number'''
for y in range.__reversed__(range(1,den+1)):
county = y
'''If den is evenly divisible by county'''
if den%county == 0:
'''And if num is divisible by county'''
if num%county == 0:
'''We have funneled the largest number\
divisible by both, by looping backwards\
from the larger number'''
print(county,'\n')
numdiv = num/county
dendiv = den/county
print('Reduced value is: %d/%d' % (numdiv,dendiv))
break
'''Below is about the same, except turns the fraction\
into it's wholenumber/fraction counterpart'''
if num > den:
for x in range.__reversed__(range(1,num+1)):
countx = x
if num%countx == 0:
if den%countx == 0:
print(countx)
numdiv = num/countx
dendiv = den/countx
print('Reduced value is: %d/%d' % (numdiv,dendiv))

print(int(numdiv/dendiv),'and',int(numdiv%dendiv),'/',int(dendiv))
break
break

'''Greatest Common Divisor Function Instance'''
num=int(float(input('Input numerator: ')))
den=int(float(input('Input denominator: ')))
gcd(num,den)


David
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A better way for greatest common divisor

2010-07-29 Thread James Mills
On Fri, Jul 30, 2010 at 11:47 AM, David Hutto  wrote:
> This is basically to get feedback, on a better way to show the
> greatest common divisor in fraction, in order to reduce it fully, than
> the one I've come up with. I'm sure there are better ways, so if you
> have simpler method, or critique of what I've done, let me know.

[snip]

I have a far simpler solution:

>>> from tools import gcd
>>> gcd(20, 5)
5
>>>

def gcd(a, b):
while b != 0:
(a, b) = (b, a%b)
return a

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A better way for greatest common divisor

2010-07-29 Thread James Mills
On Fri, Jul 30, 2010 at 12:10 PM, James Mills
 wrote:
> def gcd(a, b):
>    while b != 0:
>        (a, b) = (b, a%b)
>    return a

Here's another solution that uses a generator called factors to
generate a list of factors for any given value. The gcd function
then uses sets and intersection and the max function to find
the greatest common factor/divisor

http://codepad.org/VJIRyvI8

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A better way for greatest common divisor

2010-07-29 Thread Richard D. Moores
On Thu, Jul 29, 2010 at 19:10, James Mills  wrote:
> On Fri, Jul 30, 2010 at 11:47 AM, David Hutto  wrote:
>> This is basically to get feedback, on a better way to show the
>> greatest common divisor in fraction, in order to reduce it fully, than
>> the one I've come up with. I'm sure there are better ways, so if you
>> have simpler method, or critique of what I've done, let me know.
>
> [snip]
>
> I have a far simpler solution:
>
 from tools import gcd
 gcd(20, 5)
> 5

In Python 3.1 that would be
>>> from fractions import gcd
>>> gcd(20,5)
5

Dick Moores
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A better way for greatest common divisor

2010-07-29 Thread James Mills
On Fri, Jul 30, 2010 at 12:22 PM, Richard D. Moores  wrote:
> On Thu, Jul 29, 2010 at 19:10, James Mills  
> wrote:
>> On Fri, Jul 30, 2010 at 11:47 AM, David Hutto  wrote:
>>> This is basically to get feedback, on a better way to show the
>>> greatest common divisor in fraction, in order to reduce it fully, than
>>> the one I've come up with. I'm sure there are better ways, so if you
>>> have simpler method, or critique of what I've done, let me know.
>>
>> [snip]
>>
>> I have a far simpler solution:
>>
> from tools import gcd
> gcd(20, 5)
>> 5
>
> In Python 3.1 that would be
 from fractions import gcd
 gcd(20,5)
> 5

Yes. The code I provided above was code I wrote
for various Euler problems I had been working on
a whiel back. It was written for 2.x

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A better way for greatest common divisor

2010-07-29 Thread David Hutto
On Thu, Jul 29, 2010 at 10:36 PM, James Mills
 wrote:
> On Fri, Jul 30, 2010 at 12:22 PM, Richard D. Moores  
> wrote:
>> On Thu, Jul 29, 2010 at 19:10, James Mills  
>> wrote:
>>> On Fri, Jul 30, 2010 at 11:47 AM, David Hutto  wrote:
 This is basically to get feedback, on a better way to show the
 greatest common divisor in fraction, in order to reduce it fully, than
 the one I've come up with. I'm sure there are better ways, so if you
 have simpler method, or critique of what I've done, let me know.
>>>
>>> [snip]
>>>
>>> I have a far simpler solution:
>>>
>> from tools import gcd
>> gcd(20, 5)
>>> 5
>>
>> In Python 3.1 that would be
> from fractions import gcd
> gcd(20,5)
>> 5
>
> Yes. The code I provided above was code I wrote
> for various Euler problems I had been working on
> a whiel back. It was written for 2.x
>
> cheers
> James
>
> --
> -- James Mills
> --
> -- "Problems are solved by method"
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

Actually, I knew there was a function in one of the modules, this was
for an exercise in Building Skills in python. So it was more from
scratch than use a prebuilt function.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A better way for greatest common divisor

2010-07-29 Thread David Hutto
On Thu, Jul 29, 2010 at 10:16 PM, James Mills
 wrote:
> On Fri, Jul 30, 2010 at 12:10 PM, James Mills
>  wrote:
>> def gcd(a, b):
>>    while b != 0:
>>        (a, b) = (b, a%b)
>>    return a

That was pretty short, and sweet.

>
> Here's another solution that uses a generator called factors to
> generate a list of factors for any given value. The gcd function
> then uses sets and intersection and the max function to find
> the greatest common factor/divisor
>
> http://codepad.org/VJIRyvI8
>
> cheers
> James
>
> --
> -- James Mills
> --
> -- "Problems are solved by method"
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] finding duplicates within a tuple of tuples

2010-07-29 Thread Norman Khine
Hello,
Thanks for the replies.

On Thu, Jul 29, 2010 at 7:10 PM, Gregory, Matthew
 wrote:
> Norman Khine wrote:
>> basically i have two tables:
>>
>> id, url
>> 24715L, 'http://aqoon.local/muesli/2-muesli-tropical-500g.html'
>> 24719L, 'http://aqoon.local/muesli/2-muesli-tropical-500g.html'
>>
>> id, tid,
>> 1, 24715L
>> 2, 24719L
>>
>> so i want to first update t(2)'s tid to t(1)'s id for each duplicate
>> and then delete the row id = 24719L
>
> Assuming your first table is 'd' and your second table is 't', could you do 
> this?
>
> for url in sorted(d):
>    # Get the ID of the first element for updating t's records
>    update_id = d[url][0]
>
>    # For all duplicate URLs, remove the dict item from d and
>    # update t's records
>    while len(d[url]) > 1:
>        pop_id = d[url].pop()
>        for (k, v) in t.iteritems():
>            if v == pop_id:
>                t[k] = update_id
>
> There may be a more terse way of updating the values in t that I'm not seeing 
> right now.

Here is the latest version http://pastie.org/1066582 can this be
further improved?

>
> matt
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
˙uʍop ǝpısdn p,uɹnʇ pןɹoʍ ǝɥʇ ǝǝs noʎ 'ʇuǝɯɐן sǝɯıʇ ǝɥʇ puɐ 'ʇuǝʇuoɔ
ǝq s,ʇǝן ʇǝʎ
%>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or
chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] )
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] FTP from mainframe

2010-07-29 Thread Christian Witts

On 29/07/2010 18:34, Steve Bricker wrote:

This is my first attempt to FTP a file from a mainframe.  The code:

import ftplib
session = ftplib.FTP('company.lan.com','userid','passwd')
myfile = open('PC.filename','w')
session.retrlines("RETR 'mainframe.filename'", myfile)
myfile.close()
session.quit()

The resulting error is:

Traceback (most recent call last):
  File "ftp_from_mf.py", line 5, in 
session.retrlines("RETR 'mainframe.filename'", myfile)
  File "c:\python26\lib\ftplib.py", line 428, in retrlines
callback(line)
TypeError: 'file' object is not callable

Not sure what I'm missing.

Steve Bricker


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
   


When I'm retrieving items I use retrbinary for eg.

from ftplib import FTP

ftp = FTP(url, username, password)
for filename in ftp.nlst(''):
ftp.retrbinary('RETR %s' % filename, open(filename, 'wb').write)
ftp.delete(filename)

ftp.close()

I hope that helps.

--
Kind Regards,
Christian Witts
Business Intelligence

C o m p u s c a n | Confidence in Credit

Telephone: +27 21 888 6000
National Cell Centre: 0861 51 41 31
Fax: +27 21 413 2424
E-mail: cwi...@compuscan.co.za

NOTE:  This e-mail (including attachments )is subject to the disclaimer 
published at: http://www.compuscan.co.za/live/content.php?Item_ID=494.
If you cannot access the disclaimer, request it from 
email.disclai...@compuscan.co.za or 0861 514131.

National Credit Regulator Credit Bureau Registration No. NCRCB6


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] FTP from mainframe

2010-07-29 Thread Alan Gauld


"Christian Witts"  wrote


When I'm retrieving items I use retrbinary for eg.



The only issue with that is that if this is a real big-iron mainframe
then ftp can translate EBCDIC to ASCII during the transfer whereas
binary will, I think, bring the original file across untranslated.
So you would have the extra decoding step to do manually.
But binary transfer does simplify the transfer process.

But if its not an EBCDIC machine then I'd definitely consider
binary transfer for ftp.

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Newbie question - syntax - BeautifulSoup

2010-07-29 Thread Tommy Kaas
Thanks for the explanation. It's clearer now.
Tommy

"Tommy Kaas"  wrote

> > > for row in soup('table', {'class' : 'spad'})[0].tbody('tr'):
> >
> >Do you understand the syntax from a Python point of view?
>
> No. That's the problem.


OK, I'll assume you understand the basic for loop structure
and focus on the function call:

soup('table', {'class' : 'spad'})[0].tbody('tr')

Ignore the bit at the end for now:

soup('table', {'class' : 'spad'})

Thats a call to a function taking a string and a dictionary as 
arguments.
The string says we want to look for table tags. And the dictionary 
says
we want tables that have an attribute class with a value spad.
Is that bit clear?

Then we add an index [0] to get the first table.

Finally we call tbody("tr") to extract the tr tags from the table.
The for loop thus iterates over the rows of the first table with 
class=spad.

There might be slightly more to it than that, its a long time since I
played with BS...

>> Which help file?
>Well, maybe not a file, but the text produced by typing: 
>help(BeautifulSoup)

Ah, in that case you should definitely read the tutorial.

http://www.crummy.com/software/BeautifulSoup/documentation.html

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor