Using Windows Apache2triad with python. Need feedback form

2007-11-29 Thread kam
I need to process post data from a web feedback form and create an email which 
will be sent to me. (Something like cgiemail but 
with python code)

Does anyone have suggestions/samples? 

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


Re: do you fail at FizzBuzz? simple prog test

2008-05-12 Thread Kam-Hung Soh
On Tue, 13 May 2008 03:42:30 +1000, [EMAIL PROTECTED]  
<[EMAIL PROTECTED]> wrote:



I just can't believe someone applying for a programmer position cannot
provide a sensible anwser in 5 or less minutes.


You should join the recruitment and interview panel in your organization  
to test your faith.


--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman

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


Re: python vs. grep

2008-05-12 Thread Kam-Hung Soh
On Tue, 13 May 2008 00:03:08 +1000, Ricardo Aráoz <[EMAIL PROTECTED]>  
wrote:



Ville Vainio wrote:

On May 8, 8:11 pm, Ricardo Aráoz <[EMAIL PROTECTED]> wrote:

All these examples assume your regular expression will not span  
multiple

lines, but this can easily be the case. How would you process the file
with regular expressions that span multiple lines?

 re.findall/ finditer, as I said earlier.



Hi, sorry took so long to answer. Too much work.

findall/finditer do not address the issue, they merely find ALL the  
matches in a STRING. But if you keep reading the files a line at a time  
(as most examples given in this thread do) then you are STILL in trouble  
when a regular expression spans multiple lines.
The easy/simple (too easy/simple?) way I see out of it is to read THE  
WHOLE file into memory and don't worry. But what if the file is too  
heavy? So I was wondering if there is any other way out of it. Does grep  
read the whole file into memory? Does it ONLY process a line at a time?


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



Standard grep can only match a line at a time.  Are you thinking about  
"sed", which has a sliding window?


See http://www.gnu.org/software/sed/manual/sed.html, Section 4.13

--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman

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


Re: anonymous assignment

2008-05-12 Thread Kam-Hung Soh

On Tue, 13 May 2008 13:23:30 +1000, Yves Dorfsman <[EMAIL PROTECTED]> wrote:


Scott David Daniels wrote:

Yves Dorfsman wrote:

... Sorry this was a typo (again :-), I meant:
d = time.local()
  y = d[0]
  d = d[2]

Then:
y, d = list(time.localtime())[:4:2]



What is this ?
Could you point me to a document on this syntax ?

I've tried it, it works, but I don't understand how.


Thanks.

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



See:

"Built-in Functions", "slice()",  
http://docs.python.org/lib/built-in-funcs.html


l = range(10)
l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
l[:4]   # first four elements
[0, 1, 2, 3]
l[::2]  # every second element
[0, 2, 4, 6, 8]
l[:4:2] # every second element in the first four elements
[0, 2]

--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman

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


Re: Accepting text input

2008-05-13 Thread Kam-Hung Soh

On Wed, 14 May 2008 11:02:36 +1000, Collin <[EMAIL PROTECTED]> wrote:


Gabriel Genellina wrote:
En Mon, 12 May 2008 01:54:28 -0300, Collin <[EMAIL PROTECTED]>  
escribió:



Collin wrote:
I'm pretty new to Python, but this has really bugged me. I can't find  
a

way around it.


The problem is that, when I use raw_input("sajfasjdf") whatever, or
input("dsjfadsjfa"), you can only have numerical values as answers.

Any help would be appreciated. Thanks.


Oh, wow. I feel so stupid. Please disregard this message. <_<

 No need to apologize...


I read the error message just now a bit more carefully, and I tried
something. I tried defining "yes" as some random numerical value. Then
when I did:
(example code)

yes = 123123983 #some number
test = input("Test test test ")
if test == yes:
print "It worked."
else:
print "failed"

(example code off)

 The usual way for Python<3.0 is:
 answer = raw_input("Test test test ").lower()
if answer == "yes":
 ...
 The input() function evaluates user input as an expression: if he  
types 2+5 the input() function returns the integer 7. I would never use  
input() in a program - it's way too unsafe; use always raw_input  
instead.




If I use it like that, do I have to import anything to have the .lower()  
work? And if I do, what does the .lower() signify?

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



You don't need to import any module to use ".lower()"; it is a method of a  
string.  raw_input() returns a string, so you can use methods of a string.


Try the following statement to see what happens:
"ABCDE".lower()

--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman

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


Re: Accepting text input

2008-05-14 Thread Kam-Hung Soh

On Thu, 15 May 2008 12:36:29 +1000, Collin <[EMAIL PROTECTED]> wrote:


Kam-Hung Soh wrote:

On Wed, 14 May 2008 11:02:36 +1000, Collin <[EMAIL PROTECTED]> wrote:


Gabriel Genellina wrote:
En Mon, 12 May 2008 01:54:28 -0300, Collin <[EMAIL PROTECTED]>  
escribió:



Collin wrote:
I'm pretty new to Python, but this has really bugged me. I can't  
find a

way around it.


The problem is that, when I use raw_input("sajfasjdf") whatever, or
input("dsjfadsjfa"), you can only have numerical values as answers.

Any help would be appreciated. Thanks.


Oh, wow. I feel so stupid. Please disregard this message. <_<

 No need to apologize...


I read the error message just now a bit more carefully, and I tried
something. I tried defining "yes" as some random numerical value.  
Then

when I did:
(example code)

yes = 123123983 #some number
test = input("Test test test ")
if test == yes:
print "It worked."
else:
print "failed"

(example code off)

 The usual way for Python<3.0 is:
 answer = raw_input("Test test test ").lower()
if answer == "yes":
 ...
 The input() function evaluates user input as an expression: if he  
types 2+5 the input() function returns the integer 7. I would never  
use input() in a program - it's way too unsafe; use always raw_input  
instead.




If I use it like that, do I have to import anything to have the  
.lower() work? And if I do, what does the .lower() signify?

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

 You don't need to import any module to use ".lower()"; it is a method  
of a string.  raw_input() returns a string, so you can use methods of a  
string.

 Try the following statement to see what happens:
"ABCDE".lower()



So the .lower() string method is just to convert the string to lowercase  
letters so that you don't have to type a bunch of if - then statements  
in both cases, I'm assuming?

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



That's right.  If you normalize your input to all lower case or upper  
case, you make it easier to process user input.


Regards,

--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman

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


Re: set function

2008-05-16 Thread Kam-Hung Soh
On Sat, 17 May 2008 15:49:05 +1000, Beema shafreen  
<[EMAIL PROTECTED]> wrote:



Hi all,
I need to find the intersection of 10 different files with ids defined as
a_items, b_items and so on

common_items = a_items&b_items&c_items&\
   d_items&e_items&f_items\
   &g_items&h_items&i_items&j_items

i have included above line in the script
is this an right way will my program accept it or what are the other  
option

to compare 10 different such items


See "Set Types", http://docs.python.org/lib/types-set.html.  Example:

s1 = set([1,2,3])
s2 = set([3,4,5])
s1 & s2
set([3])

You can populate your sets using an iterable, such as the lines from a  
file.  Example:


s1 = set(file(r'blah.txt'))

--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman

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


Re: comparison of files using set function

2008-05-17 Thread Kam-Hung Soh
On Sun, 18 May 2008 00:47:55 +1000, Beema shafreen  
<[EMAIL PROTECTED]> wrote:



I have files with two column, column 1 is with id and column 2 is with
data(sequence)
My goal is to create a table in such a way, the column one of the table
should have all the id from the files and next column will be have the
respective seq of the file1 with correlation to the id and the third  
column

will be sequence information of the next file with respective to the id
original files look like this

45ytut
46erete
37   dfasf
45  dassdsd


and so on  for all the 10 files that is it has two column as mentioned
above.

The output should look like this:

Idfile1  file2 file3 file4   file5
43ytuhytuh ytuhytuhytuh
46   erteee   rty   ryyy  ertyu
47   yutiorrreeerr



The goal is if the pick all the common id in the files and with their
respective information in the adjacent rows.
the various conditons ca also prevails
1) common id present in all the files, which have same information
2)common id present in all the files, which donot have same information
3) common id may not be present in all the files

But the goal is exactly find the common id in all the files and add their
corresponding information in the file to the table as per the view
 my script :
def file1_search(*files1):
for file1 in files1:
gi1_lis = []
fh = open(file1,'r')
for line in fh.readlines():
data1 = line.strip().split('\t')
gi1 = data1[0].strip()
seq1 = data1[1].strip()
gi1_lis.append(gi1)
return gi1_lis
def file2_search(**files2):
for file2 in files2:
for file in files2[file2]:
gi2_lis = []
fh1 = open(file,'r')
for line1 in fh1.readlines():
data2 = line1.strip().split('\t')
gi2 = data2[0].strip()
seq2 = data2[1].strip()
gi2_lis.append(gi2)

return gi2_lis
def set_compare(data1,data2,*files1,**files2):
A = set(data1)
B = set(data2)
I = A&B # common between thesetwo sets

D = A-B #57 is the len of D
C = B-A #176 is  the len of c
#print len(C)
 #   print len(D)
for file1 in files1:
for gi in D:
fh = open(file1,'r')
for line in fh.readlines():
data1 = line.strip().split('\t')
gi1 = data1[0].strip()
seq1 = data1[1].strip()
if gi == gi1:
#print line.strip()
pass

for file2 in files2:
for file in files2[file2]:
for gi in C:
fh1 = open(file,'r')
for line1 in fh1.readlines():
data2 = line1.strip().split('\t')
gi2 = data2[0].strip()
seq2 = data2[1].strip()
if gi == gi2:
   # print line1.strip()
pass
if __name__ == "__main__":
files1 = ["Fr20.txt",\
  "Fr22.txt",\
  "Fr24.txt",\
  "Fr60.txt",\
  "Fr62.txt"]
files2 = {"data":["Fr64.txt",\
  "Fr66.txt",\
  "Fr68.txt",\
  "Fr70.txt",\
  "Fr72.txt"]}
data1 = file1_search(*files1)

"""113 is the total number of gi"""
data2 = file2_search(**files2)
#for j in data2:
 #   print j
"""232 is the total number of gi found"""
result = set_compare(data1,data2,*files1,**files2)

 It doesnot work fine... some body please suggest me the way i can  
proceed .

Thanks a lot



1. Test with a small number of short files with a clear idea of the  
expected result.
2. Use better variable names.  Names such as file1_search, file2_search,  
gi, gi2, A, B, C and D make it nearly impossible to understand your code.


--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman

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


Re: How do *you* use Python in non-GUI work?

2008-05-18 Thread Kam-Hung Soh
On Mon, 19 May 2008 08:20:22 +1000, John Salerno  
<[EMAIL PROTECTED]> wrote:


Hey all. Just thought I'd ask a general question for my own interest.  
Every time I think of something I might do in Python, it usually  
involves creating a GUI interface, so I was wondering what kind of work  
you all do with Python that does *not* involve any GUI work. This could  
be any little scripts you write for your own benefit, or what you do at  
work, if you feel like talking about that! :)


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



- Enhancing existing products by scripting new features.
- Interface between databases, Excel and text files.
- Convert data between flat files and XML.
- Manage files for build processes.
- Automating processes (e.g. checkout, builds, FTP).

Wish I had some reasons to make a GUI application in Python.

--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman

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


Re: Separate output for log file and stdout

2008-05-19 Thread Kam-Hung Soh

On Tue, 20 May 2008 06:58:28 +1000, <[EMAIL PROTECTED]> wrote:


On May 16, 6:37 pm, Ben Finney <[EMAIL PROTECTED]>
wrote:

[EMAIL PROTECTED] writes:
> I've recently jumped big time into python and I'm working on a
> software program for testing automation.

Welcome, to both fields :-)



Thanks! I am having a great time learning and coding in python. It's
an amazing programming language.


> I had a question about proper logging of output. What I would like
> is:

>  1. a function syslog (to log output to log file only)
>  2. a function stdout (to log output to stdout only)
>  3. a function sslog (to log output to both log and stdout)

> Right now I am using StandOut module

Have you investigated the 'logging' module in the Python standard
library http://www.python.org/doc/lib/module-logging>? It appears
to meet your listed requirements, without need of external
dependencies.


Hmm..Yeah I didn't realize python had its own standard logging
facility. I took a look at it and it seems to do the job. However, the
output seems to be syslog style output. In the program I am writing,
the log file stores all the output of the commands being run (e.g. tcl
scripts, etc). Will this be possible using the built in python logging
module?

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



You can define the format of the log output in basicConfig(), for example:

from logging import basicConfig, error, info, INFO
...
  basicConfig(
  datefmt='%Y%m%d_T%H%M%S',
  filemode='a',
  filename=LOG_PATH,
  format='%(asctime)s,%(levelname)s,%(message)s',
  level=INFO
  )

If you want to log the output of other commands in your log file, you can  
connect a pipe to that command.  Maybe look at "subprocess -- Subprocess  
management" in http://docs.python.org/lib/module-subprocess.html


--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman

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


Re: decorators when?

2008-05-27 Thread Kam-Hung Soh

David C. Ullrich wrote:

What version added decorators (using the
@decorator syntax)?

(Is there a general way I could have found out the answer myself?)

Is there a somthing such that "from __future__ import something"
will make decorators work in 2.5.2?


David C. Ullrich


See:

http://www.python.org/doc/2.4/whatsnew/whatsnew24.html

Dunno of a general way view a list of features versus releases, other 
than reading the "What's New in Python x" documents.  Maybe some 
enterprising developer can compile this list?  Hint, hint.


--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman

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


Re: convert string number to real number - ValueError: invalid literal for int() with base 10: '"2"'

2008-05-27 Thread Kam-Hung Soh

David Jackson wrote:

i used the csv module and saved its contents to a list.

['Date', 'No.', 'Description', 'Debit', 'Credit']
['3/17/2006', '5678', 'ELECTRONIC PAYMENT', '', '11.45']
['3/04/2007', '5678', 'THE HOME DEPOT 263 SomeCity FL', '', '25.40']


the credit/debit fields are strings.
what should i have done within the CSV module to make numbers appear as 
numbers?
how can i remove the quotes to make them numbers? i realize i posted a 
solution to this once before (same posting thread) but i am thinking 
there is a better method.


There doesn't seem to be a way to describe how specific columns should 
be processed in the csv module.  You could define a conversion function 
that "guesses" the best conversion, for example:


def str2num(datum):
try:
return int(datum)
except:
try:
return float(datum)
except:
return datum

for row in csv.reader(file(r'Transaction.csv')):
[str2num(cell) for cell in row]

['Date', 'No.', 'Description', 'Debit', 'Credit']
['3/17/2006', 5678, 'ELECTRONIC PAYMENT', '', 11.449]
['3/04/2007', 5678, 'THE HOME DEPOT 263 SomeCity FL', '', 
25.399]


--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman

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


Re: convert string number to real number - ValueError: invalid literal for int() with base 10: '"2"'

2008-05-28 Thread Kam-Hung Soh

Matthias Bläsing wrote:

Am Wed, 28 May 2008 10:41:51 -0700 schrieb davidj411:


I like the str2num function approach, but then i get left with a float
that has more than 2 decimal spaces , i.e. 11.50 becomes
11.449 and round will not fix that.


Welcome to the wonderful world of floating point numbers. For your usage 
you want 10-based numbers. Have a look at the decimal module:



from  decimal import Decimal
a = Decimal("11.45")
a

Decimal("11.45")

str(a)

'11.45'

a + 1

Decimal("12.45")

a + Decimal("1.55")

Decimal("13.00")

HTH

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



Thanks for the tip, Matthias.  I knew that there had to be a way to 
handle arbitrary precision numbers.


--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman

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


Re: Finding file details...

2008-05-29 Thread Kam-Hung Soh

Roger Upole wrote:

Kalibr wrote:

I've been trying to figure out how to find the details of files
(specifically music for now) for a little sorting script I'm making,
My aim is to get details on the artist, album, and genre for mp3 and
wma files (possibly more in the future). My closest match was when I
stumbled accross PyMedia, but it only supports up to 2.4 (I have 2.5).
Now I see a bit mentioned on GetFileVersionInfo, but that doesn't seem
to help (and most of it went over my head). Is there any module I can
use to find this sort of data? I'm trying to not make it specialised
in music, because I may want to extend this to picture, movie, text
etc. files in the future. Any ideas how I could go about this?


I think GetFileVersionInfo() only provides version information for DLL 
and EXE files.


See: http://msdn.microsoft.com/en-us/library/ms646981.aspx



You can use the shell COM objects to access media properties
as shown by Explorer.

import win32com.client
sh=win32com.client.Dispatch('Shell.Application')

folder= r'M:\Music\Bob Dylan\Highway 61 Revisited'
ns=sh.NameSpace(folder)

## the column index for Artist may vary from folder to folder
for c in range(0,255):
colname=ns.GetDetailsOf(None, c)
if colname=='Artists':  ## This shows up as just Artist on XP
for i in ns.Items():
artist=ns.GetDetailsOf(i, c)
if artist:
print ns.GetDetailsOf(i, 0), artist
break


Roger


Great tip, Roger!  This solution works for WMA files (I don't have any 
MP3 files handy), so I think it would work for any media files in Windows.


--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman

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


Re: Finding file details...

2008-05-29 Thread Kam-Hung Soh

Kalibr wrote:

On May 30, 1:41 am, "Roger Upole" <[EMAIL PROTECTED]> wrote:

You can use the shell COM objects to access media properties
as shown by Explorer.

import win32com.client
sh=win32com.client.Dispatch('Shell.Application')

folder= r'M:\Music\Bob Dylan\Highway 61 Revisited'
ns=sh.NameSpace(folder)

## the column index for Artist may vary from folder to folder
for c in range(0,255):
colname=ns.GetDetailsOf(None, c)
if colname=='Artists':  ## This shows up as just Artist on XP
for i in ns.Items():
artist=ns.GetDetailsOf(i, c)
if artist:
print ns.GetDetailsOf(i, 0), artist
break

Roger


I shall give that a go. (is the module you reference this one?
http://python.net/crew/mhammond/win32/Downloads.html )


If you installed ActiveState's Python, the win32com module should be 
installed.


--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman

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


Re: readline() & seek() ???

2008-06-05 Thread Kam-Hung Soh

Tim Roberts wrote:

DataSmash <[EMAIL PROTECTED]> wrote:

I have a text file that contains thousands of lines and each line is
256 characters long.

This is my task:
For each line in the file, move to the 25th character, if the
character is a "T",
move to the 35th character of the line and read 5 characters from
there.
Capture these 5 characters and write them to a new text file, each 5
characters separated by a comma.

I appreciate your help!


Did you even TRY this?  Your task reads like pseudocode that translates
virtually line-for-line to Python code.

  fout = open('outputfile.txt','w')
  for line in open('inputfile.txt'):
  if line[24] == 'T':
  fout.write( line[34:39] + ',' )


Should the last line be ...

fout.write(','.join(line[34:39])

--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman

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


Re: readline() & seek() ???

2008-06-06 Thread Kam-Hung Soh

Chris wrote:

On Jun 6, 5:13 am, Kam-Hung Soh <[EMAIL PROTECTED]> wrote:

Tim Roberts wrote:

DataSmash <[EMAIL PROTECTED]> wrote:

I have a text file that contains thousands of lines and each line is
256 characters long.
This is my task:
For each line in the file, move to the 25th character, if the
character is a "T",
move to the 35th character of the line and read 5 characters from
there.
Capture these 5 characters and write them to a new text file, each 5
characters separated by a comma.
I appreciate your help!

Did you even TRY this?  Your task reads like pseudocode that translates
virtually line-for-line to Python code.
  fout = open('outputfile.txt','w')
  for line in open('inputfile.txt'):
  if line[24] == 'T':
  fout.write( line[34:39] + ',' )

Should the last line be ...

fout.write(','.join(line[34:39])

--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman


each 5 characters need to be delimited by a comma, your statement
would have a comma between each of the 5 characters.


You're right; I see where I got confused.

--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman

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


Re: sendKey

2008-06-08 Thread Kam-Hung Soh

Gandalf wrote:

I found some script that send keys , But I couldn't  manage to send
CTRL+c with none of them

can any one tell me what i'm doing wrong:

import win32api
import win32com.client

shell = win32com.client.Dispatch("WScript.Shell")
shell.Run("Notepad")
win32api.Sleep(100)
shell.AppActivate("Notepad")
win32api.Sleep(100)
shell.SendKeys("112435435")
win32api.Sleep(100)

shell.SendKeys("^a") # that wouldn't select all
win32api.Sleep(100)
shell.SendKeys("^c")# that wouldn't copy


Works for me, using Vista and ActiveState Python 2.5.1.1.


import SendKeys
SendKeys.SendKeys("""^c""")


Thank you!


--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman

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


Re: Separators inside a var name

2008-06-09 Thread Kam-Hung Soh

Rainy wrote:

I have a stylistic question. In most languages words in var. name are
separated by underscores or cap letters, resulting in var names like
var_name, VarName and varName. I don't like that very much because all
3 ways of naming look bad and/or hard to type. From what I understand,
scheme can have variables like var-name. I'm curious about reasons
that python chose to disallow this. Another question I have is what
other languages allow this naming scheme? Were there any languages
that allowed space as a separator? What would be a practical way to
separate variables from keywords in that case? "some long variable
name", 'just a string', or maybe using 2 spaces: one var  +  other
var  +  third var ? I think being able to easy have very long names
for vars that are easy to type would be a fairly significant
advantage. I know I'm probably being too obsessive about this, but
that didn't stop me from posting. Comments?
--
http://mail.python.org/mailman/listinfo/python-list



Groovy allows spaces in method names.  See following request and thread:

http://jira.codehaus.org/browse/GROOVY-2857

--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman

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


Re: How is GUI programming in Python?

2008-04-09 Thread Kam-Hung Soh
On Apr 10, 12:35 pm, Benjamin <[EMAIL PROTECTED]> wrote:
> On Apr 9, 8:54 pm, Chris Stewart <[EMAIL PROTECTED]> wrote:> I've always had 
> an interest in Python and would like to dabble in it
> > further.  I've worked on a few very small command line programs but
> > nothing of any complexity.  I'd like to build a really simple GUI app
> > that will work across Mac, Windows, and Linux.  How painful is that
> > going to be?  I used to be really familiar with Java Swing a few years
> > ago.  I imagine it will be similar.
>
> Since it's Python, it will be a lot less painless than anything
> else. :)
>
> > Next, what would you say is the best framework I should look into?
> > I'm curious to hear opinions on that.
>
> Tkinter is the easiest for little apps, but when I'm doing anything
> for real, I use PyQt.
>
>
>
> > Chris Stewart
> > [EMAIL PROTECTED]

Since the OP has Swing programming experience, what about Jython
(http://www.jython.org/Project/index.html)?

"Jython is an implementation of the high-level, dynamic, object-
oriented language Python written in 100% Pure Java, and seamlessly
integrated with the Java platform. It thus allows you to run Python on
any Java platform."

--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to remove \n in the list

2008-04-13 Thread Kam-Hung Soh
On Apr 14, 2:58 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Mon, 14 Apr 2008 01:41:55 -0300, reetesh nigam
> <[EMAIL PROTECTED]> escribió:
>
> > hi,
> > l=['5\n', '2\n', '7\n', '3\n', '6\n']
>
> > how to remove \n from the given list
>
> l is is very poor name... I'll use lines instead:
>
> lines[:] = [line.rstrip('\n') for line in lines]
>
> --
> Gabriel Genellina

Also: map(str.rstrip, l)

--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finally had to plonk google gorups.

2008-04-16 Thread Kam-Hung Soh
On Apr 17, 1:14 am, Mike Kent <[EMAIL PROTECTED]> wrote:
> On Apr 16, 10:26 am, Mike Driscoll <[EMAIL PROTECTED]> wrote:
>
> > Yeah, I noticed that Google Groups has really sucked this week. I'm
> > using the Google Groups Killfile for Greasemonkey now and it helps a
> > lot. I like Google, but my loyalty only goes to far. This is a
> > complete lack of customer service.
>
> > Mike
>
> Bless you.  I just installed Greasemonkey and the Google Groups
> Killfile.  Works like a charm.

I manually edit the REs in the GGK's kill file variable (use Firefox
about:config and filter for "kill") and enable case-insensitive search
(open the script, search for "compile()" and add a second parameter
"i").

(Posted via GG, but I'm open to an alternative web-based Usenet
service.)

--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: index of list of lists

2008-04-18 Thread Kam-Hung Soh
On Thu, 17 Apr 2008 12:25:51 +1000, Daniel Fetchinson  
<[EMAIL PROTECTED]> wrote:

>> yes, there's a thread with the same title, but I believe mine is more
>> appropriate title.
>> so, as much as I search on the web, read manuals, tutorials, mail-lists
>> (including this one) I cannot figure it out how to search a string in a
>> list of lists.
>> like this one:
>>
>> someList = [['somestring', 1, 2], ['oneother', 2, 4]]
>>
>> I want to search "somestring" in someList which is in practice a list
>> of aprox. 200 lists. (hey, I'm a newbie python programmer, don't judge
>> me).
>> is the list.index the wrong approach?
>> should I use numpy, numarray, something else?
>> can anyone, be kind and help me with this?
>
> someList = [['somestring', 1, 2], ['oneother', 2, 4]]
> for alist in someList:
> if alist[0] == 'somestring':
> print "Found it at index %d" % someList.index( alist )
> # if you know it will only occur once you might say:
> break
>
> HTH,
> Daniel

See also Section 4.5. Filtering Lists.

List comprehension:

[x for x in someList if x[0] == 'somestring']

Use filter() function:

filter(lambda x: x[0] == 'somestring', someList)

-- 
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman

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


Re: Is massive spam coming from me on python lists?

2008-04-21 Thread Kam-Hung Soh
On Mon, 21 Apr 2008 16:01:42 +1000, Brian Vanderburg II  
<[EMAIL PROTECTED]> wrote:


I've recently gotten more than too many spam messages and all say  
Sender: [EMAIL PROTECTED]  I'm wondering  
if my mail list registration is now being used to spam myself and  
others.  If so, sorry, but I'm not the one sending messages if other are  
getting them even though Sender seems to include my address (I'm not  
sure about mail headers so I don't know how From: is different than  
Sender:)  Anyway, it seems to be a bunch of spam emails about cracks and  
stuff.


Brian Vanderburg II


No worries.  People should (I hope) just ignore the sender address when  
they receive spam.


--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman
--
http://mail.python.org/mailman/listinfo/python-list


Re: problem with listdir

2008-04-26 Thread Kam-Hung Soh
On Sat, 26 Apr 2008 19:07:45 +1000, Francesco Bochicchio  
<[EMAIL PROTECTED]> wrote:



On Sat, 26 Apr 2008 01:24:23 -0700, jimgardener wrote:


hi
i have a directory containing .pgm files of P5 type.i wanted to read
the pixel values of these files ,so as a firststep i wrote code to
make a  list  of filenames using listdir

pgmdir="f:\code\python\pgmgallery" # where i have pgm files
g2=listdir(pgmdir)

i get the following error
WindowsError: [Error 123] The filename, directory name, or volume
label syntax is incorrect: 'f:\\code\\python\pgmgallery/*.*'

i am running python on winXP ..can anyone tell me why i get this
error?


Did you try using a raw string as pathname
pgmdir=r"f:\code\python\pgmgallery"
?

AFAIK, the character '\' in interpreted in Python as the beginning of
an escape sequence (such as '\n') and it should be doubled ( as in the
error message) or a raw string should be used, telling Python that there
are no escape sequences inside.
However, from the message it looks like the path as been understood as
such, so this might not be the case.

Ciao
-
FB


Neither \c nor \p are escape characters in Section 2.4.1 "String literals".

Could there be some files in that directory whose name is not a valid  
Windows file name?  Windows file names cannot have the following symbols:


\ / : * ? " < > |

--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman
--
http://mail.python.org/mailman/listinfo/python-list


Re: computing with characters

2008-04-30 Thread Kam-Hung Soh

On Wed, 30 Apr 2008 16:13:17 +1000, SL <[EMAIL PROTECTED]> wrote:


How can I compute with the integer values of characters in python?
Like 'a' + 1 equals 'b' etc


Try: ord('a')

See also: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65117

--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman
--
http://mail.python.org/mailman/listinfo/python-list


Re: sed to python: replace Q

2008-04-30 Thread Kam-Hung Soh

On Wed, 30 Apr 2008 15:27:36 +1000, Raymond <[EMAIL PROTECTED]> wrote:


For some reason I'm unable to grok Python's string.replace() function.
Just trying to parse a simple IP address, wrapped in square brackets,
from Postfix logs. In sed this is straightforward given:

line = "date process text [ip] more text"

  sed -e 's/^.*\[//' -e 's/].*$//'

yet the following Python code does nothing:

  line = line.replace('^.*\[', '', 1)
  line = line.replace('].*$', '')


str.replace() doesn't support regular expressions.

Try:

import re
p = re.compile("^.*\[")
q = re.compile("].*$")
q.sub('',p.sub('', line))



Is there a decent description of string.replace() somewhere?

Raymond


Section 3.6.1 String Functions

--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman
--
http://mail.python.org/mailman/listinfo/python-list


Re: sed to python: replace Q

2008-04-30 Thread Kam-Hung Soh
On Wed, 30 Apr 2008 17:12:15 +1000, Kam-Hung Soh <[EMAIL PROTECTED]>  
wrote:


On Wed, 30 Apr 2008 15:27:36 +1000, Raymond <[EMAIL PROTECTED]>  
wrote:



For some reason I'm unable to grok Python's string.replace() function.
Just trying to parse a simple IP address, wrapped in square brackets,
from Postfix logs. In sed this is straightforward given:

line = "date process text [ip] more text"

  sed -e 's/^.*\[//' -e 's/].*$//'

yet the following Python code does nothing:

  line = line.replace('^.*\[', '', 1)
  line = line.replace('].*$', '')


str.replace() doesn't support regular expressions.

Try:

import re
p = re.compile("^.*\[")
q = re.compile("].*$")
q.sub('',p.sub('', line))



Another approach is to use the split() function in "re" module.

import re
re.split("[\[\]]", line)[1]

See http://docs.python.org/lib/node46.html

--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman
--
http://mail.python.org/mailman/listinfo/python-list


Re: creating a list from a inconsistent text file

2008-05-02 Thread Kam-Hung Soh

On Fri, 02 May 2008 23:47:11 +1000, Jetus <[EMAIL PROTECTED]> wrote:


On May 2, 7:19 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:

On Fri, 02 May 2008 04:14:47 -0700, Jetus wrote:
> I have a comma delimited file that is separated by comma's, and then
> sometimes by ","

> c:\temp\05-06-08\Sale1,659 CECIL,"659 CECIL,40211",
> 1,659,CECIL,AVENUE,LOUISVILLE,40211,"$65,276.78 "
> c:\temp\05-06-08\Sale2,637 SOUTH 27TH,"637 SOUTH 27TH,40211",
> 2,637,SOUTH 27TH,STREET,LOUISVILLE,40211,"$45,456.95 "
> c:\temp\05-06-08\Sale3,2709 ELLIOT,"2709 ELLIOT,40211",
> 3,2709,ELLIOT,AVENUE,LOUISVILLE,40211,"$49,349.66 "

The items are always delimited by commas but some items themselves  
contain

a comma and therefore are enclosed in double quotes.  So it's not
inconsistent.

> How do I convert that line into a list?

Use the `csv` module in the standard library.

Ciao,
Marc 'BlackJack' Rintsch


Hello Marc;
Thanks for the input! I am worried about the comma in the "" data
items, how do I tell Python to look for the "" data first, then use
the comma separator?


The reader in the csv package automatically handles double-quoted fields.

--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman
--
http://mail.python.org/mailman/listinfo/python-list


Re: open filename with spaces in path

2008-05-06 Thread Kam-Hung Soh
On Wed, 07 May 2008 08:36:35 +1000, Michael Robertson  
<[EMAIL PROTECTED]> wrote:



I'm having trouble opening a file in linux, whose path has spaces in it.

$ mkdir my\ test
$ echo test > my\ test/test.txt
$ python

 >>> open('./my test/test.txt')
Exception
 >>> open('./my\\ test/test.txt')
Exception



Try a string literal by prefixing your path string with "r":

open(r'./my test/test.txt')

See http://docs.python.org/ref/strings.html


but yet...

 >>> import os
 >>> os.chdir('./my test')
 >>> open('./test')

works just fine.


Couldn't test on Linux, but in Windows ...


os.chdir('C:\temp\my test')

Traceback (most recent call last):
  File "", line 1, in 
WindowsError: [Error 123] The filename, directory name, or volume label  
syntax is incorrect: 'C:\temp\\my test'


--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman
--
http://mail.python.org/mailman/listinfo/python-list


Re: open filename with spaces in path

2008-05-06 Thread Kam-Hung Soh
On Wed, 07 May 2008 09:09:08 +1000, Kam-Hung Soh <[EMAIL PROTECTED]>  
wrote:


On Wed, 07 May 2008 08:36:35 +1000, Michael Robertson  
<[EMAIL PROTECTED]> wrote:



I'm having trouble opening a file in linux, whose path has spaces in it.

$ mkdir my\ test
$ echo test > my\ test/test.txt
$ python

 >>> open('./my test/test.txt')
Exception
 >>> open('./my\\ test/test.txt')
Exception



Try a string literal by prefixing your path string with "r":

open(r'./my test/test.txt')

See http://docs.python.org/ref/strings.html


but yet...

 >>> import os
 >>> os.chdir('./my test')
 >>> open('./test')

works just fine.


Couldn't test on Linux, but in Windows ...


os.chdir('C:\temp\my test')

Traceback (most recent call last):
   File "", line 1, in 
WindowsError: [Error 123] The filename, directory name, or volume label  
syntax is incorrect: 'C:\temp\\my test'




Oops.  Should have been:


os.chdir(r'C:\temp\my test')
(no errors)


--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman
--
http://mail.python.org/mailman/listinfo/python-list


Re: anagram finder / dict mapping question

2008-05-07 Thread Kam-Hung Soh
On Thu, 08 May 2008 11:02:12 +1000, dave <[EMAIL PROTECTED]>  
wrote:



Hi All,

I wrote a program that takes a string sequence and finds all the words  
inside a text file (one word per line) and prints them:


def anagfind(letters):  #find anagrams of these letters
fin = open('text.txt')  #one word per line file
wordbox = [] #this is where the words will go
for line in fin:
word = line.strip()
count = 0
for char in letters:
if char not in word:
break
else:
count += 1
if count == len(word):
wordbox.append(word)
return wordbox

Now I'd like to modify the code to naturally find all anagrams inside a  
wordlist.  What would be the best way to do this?  Using Hints?  Is it  
possible to iterate over dict keys?  How can I make a dict that maps  
from a set of letters to a list of words that are spelled from those  
letters?  Wouldn't I need to make the set of letters a key in a dict?


As always - Thanks for helping someone trying to learn...

Dave



Suggestion: for each word, sort their characters and use them as the  
dictionary key.  If two words have the same combination of characters,  
then they are anagrams.  For example: "edam" and "made" are anagrams  
because they have the letters 'a', 'd', 'e' and 'm'.


Refer "Programming Pearls" by Jon Bentley.

--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman
--
http://mail.python.org/mailman/listinfo/python-list


Re: anagram finder / dict mapping question

2008-05-08 Thread Kam-Hung Soh
On Thu, 08 May 2008 15:42:07 +1000, dave <[EMAIL PROTECTED]>  
wrote:


This is what i've came up with.  My problem is that I can't get them to  
properly evaluate.. when  comparewords() runs it finds itself...  Should  
I have the keys of mapdict iterate over itself?  Is that possible?


def annafind():
fin = open('text.txt')  # file has one word per line
mapdic = {} # each word gets sorted & goes in here
for line in fin:
rawword = line.strip()
word = list(rawword)
word.sort()
mapdic[''.join(word)] = 0
return mapdic


def comparewords(): ***not working as intended
fin = open('text.txt')
for line in fin:
line = line.strip()
word = list(line)
word.sort()
sortedword = (''.join(word))
if sortedword in mapdic:
        print line




On 2008-05-07 19:25:53 -0600, "Kam-Hung Soh" <[EMAIL PROTECTED]>  
said:



On Thu, 08 May 2008 11:02:12 +1000, dave <[EMAIL PROTECTED]>
wrote:


Hi All,
 I wrote a program that takes a string sequence and finds all the words



inside a text file (one word per line) and prints them:
 def anagfind(letters): #find anagrams of these letters
fin = open('text.txt')  #one word per line file
wordbox = [] #this is where the words will go
for line in fin:
word = line.strip()
count = 0
for char in letters:
if char not in word:
break
else:
count += 1
if count == len(word):
wordbox.append(word)
return wordbox
 Now I'd like to modify the code to naturally find all anagrams inside

a

wordlist.  What would be the best way to do this?  Using Hints?  Is it



possible to iterate over dict keys?  How can I make a dict that maps



from a set of letters to a list of words that are spelled from those



letters?  Wouldn't I need to make the set of letters a key in a dict?
 As always - Thanks for helping someone trying to learn...
 Dave


 Suggestion: for each word, sort their characters and use them as the
dictionary key.  If two words have the same combination of characters,
then they are anagrams.  For example: "edam" and "made" are anagrams
because they have the letters 'a', 'd', 'e' and 'm'.
 Refer "Programming Pearls" by Jon Bentley.
 --
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salarimana>





Your code is always going to return the same list because every word is an  
anagram of itself.


Tip: Create a list for each dictionary key, then add a word to the list if  
that word is not in the list.  So:


mapdic('adem') --> ["edam", "made"]

P.S. When replying, the convention is to add your response to the bottom,  
not top of the message.


--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman
--
http://mail.python.org/mailman/listinfo/python-list


Re: anagram finder / dict mapping question

2008-05-08 Thread Kam-Hung Soh
On Fri, 09 May 2008 09:52:53 +1000, dave <[EMAIL PROTECTED]>  
wrote:



I got it!  Thanks for all your help!!!  Please tell me what you think:

def anafind():
fin = open('short.txt') #one word per line
mapdic = {} #this dic maps letters 
to anagrams
for line in fin:
line = line.strip()
templist = sorted(list(line))   #sort letters
newtlist = (''.join(templist))  #join letters
if newtlist not in mapdic:
mapdic[newtlist] = [line]
if line not in mapdic[newtlist]:
mapdic[newtlist].append(line)
for value in mapdic.values():
if len(value) <= 1:
pass
else:
print value




I avoid creating a temporary variable if it's only used once immediately,  
so I would have written:


newtlist = ''.join(sorted(list(line)))

Looks pretty good, and I found the other tips in parallel responses useful  
to me too!


--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman
--
http://mail.python.org/mailman/listinfo/python-list


Re: anagram finder / dict mapping question

2008-05-09 Thread Kam-Hung Soh

On Sat, 10 May 2008 07:19:38 +1000, <[EMAIL PROTECTED]> wrote:


> What would be the best method to print the top results, the one's that
> had the highest amount of anagrams??  Create a new histogram dict?

You can use the max() function to find the biggest list of anagrams:

top_results = max(anagrams.itervalues(), key=len)

--
Arnaud


That is the biggest list of anagrams, what if I wanted the 3 biggest
lists?  Is there a way to specific top three w/ a max command??



Built-in max() function only returns one result.

My solution is to make a sorted list and return last three items:

sorted((len(anagrams[key]), key) for key in anagrams.keys())[-3:]

--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman
--
http://mail.python.org/mailman/listinfo/python-list


Re: do you fail at FizzBuzz? simple prog test

2008-05-10 Thread Kam-Hung Soh

On Sun, 11 May 2008 11:12:37 +1000, globalrev <[EMAIL PROTECTED]> wrote:


http://reddit.com/r/programming/info/18td4/comments

claims people take a lot of time to write a simple program like this:


"Write a program that prints the numbers from 1 to 100. But for
multiples of three print "Fizz" instead of the number and for the
multiples of five print "Buzz". For numbers which are multiples of
both three and five print "FizzBuzz".

for i in range(1,101):
if i%3 == 0 and i%5 != 0:
print "Fizz"
elif i%5 == 0 and i%3 != 0:
print "Buzz"
elif i%5 == 0 and i%3 == 0:
print "FizzBuzz"
else:
print i


is there a better way than my solution? is mine ok?


Looks OK to me.

A different version, and I test for multiples of 3 and 5 first:

map(lambda x: (not x%3 and not x%5 and "FizzBuzz") or (not x%3 and "Fizz")  
or (not x%5 and "Buzz") or x, xrange(1,101))


--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman
--
http://mail.python.org/mailman/listinfo/python-list


Re: anagram finder / dict mapping question

2008-05-10 Thread Kam-Hung Soh
On Sat, 10 May 2008 18:06:17 +1000, Arnaud Delobelle  
<[EMAIL PROTECTED]> wrote:



"Kam-Hung Soh" <[EMAIL PROTECTED]> writes:


On Sat, 10 May 2008 07:19:38 +1000, <[EMAIL PROTECTED]> wrote:

> What would be the best method to print the top results, the one's  
that

> had the highest amount of anagrams??  Create a new histogram dict?

You can use the max() function to find the biggest list of anagrams:

top_results = max(anagrams.itervalues(), key=len)

--
Arnaud


That is the biggest list of anagrams, what if I wanted the 3 biggest
lists?  Is there a way to specific top three w/ a max command??



Built-in max() function only returns one result.

My solution is to make a sorted list and return last three items:

sorted((len(anagrams[key]), key) for key in anagrams.keys())[-3:]


Using the key= parameter of sorted() beats explicit DSU:

sorted(anagrams.itervalues(), key=len)[-3:]

Or even

sorted(anagrams.itervalues(), key=len, reverse=True)[:3]



Nice!

I just found out that DSU = Decorate-Sort-Undecorate idiom, from  
http://wiki.python.org/moin/HowTo/Sorting.


--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman
--
http://mail.python.org/mailman/listinfo/python-list


Re: firefox add-on to grab python code handily?

2008-05-10 Thread Kam-Hung Soh

On Sat, 10 May 2008 17:58:12 +1000, CM <[EMAIL PROTECTED]> wrote:


I encounter a fair number of small Python scripts online, and usually
try them out by copying them to the clipboard, pasting into Notepad,
saving them, and either running them directly or opening them in
IDLE.

And so I was wondering if anyone knew of an extension/add-on/script
for Firefox which would allow a way to do something like this:

user highlights Python code on a webpage
right clicks
selects a menu item, "Save as Python code"
FF pops up a filename dialog or popup for filename
(and, though I don't know if this is possible, runs Python code)

Not an important thing by any means, but it would be a nice
convenience.
I know there are similar add-ons in FF for grabbing highlighted text
and
saving, but they are not good, as they don't seem to preserve line
breaks
properly or append the .py extension, etc.  I've Googled for this and
so far
it seems it doesn't exist.  Anyone know?




Not a Firefox add-on, but I found GnuWin32's "getclip" and "putclip" tools  
useful.  If you are familiar with shell tools, you can use "sed" to remove  
leading indentation marks such as "> " before you paste sample code into  
your IDE:


getclip | sed "s/> //" | putclip

See http://kamhungsoh.com/blog/2008/05/more-uses-of-getclip-putclip.html

--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman
--
http://mail.python.org/mailman/listinfo/python-list