jice 53 Posting Whiz in Training

Sorry but i don't understand what you want...
Can you post your code ? part of your sql files ?
How do you execute the content of your sql files ?
What do you want to write in your logfile ?
Your question in far too open for me to answer.

jice 53 Posting Whiz in Training

Sorry, i've been too fast

import pprint # don't worry abour this it is only to print the result quickly at the end

rows=[[0 for i in range(9)] for i in range(9)]
cols=[[0 for i in range(9)] for i in range(9)]
# these are called list comprehensions and are the same as
rows=[]
for i in range(9):
    rows.append([])
    for j in range(9):
        rows[-1].append(0)
# so now rows=[[0, 0, 0, 0... ], [0,0,0,0...  ] ... ]
cols=[]
for i in range(9):
    cols.append([])
    for j in range(9):
        cols[-1].append(0)
# this is to create 2 lists skeltons
# now, let's fill them
for i in range(9):
    for j in range(9):
        # here, instead of 0 in each 'cell', I put a dictionary with 1 key : 'value'
        # note that you can put others datas in this dictionnary (like hidden, shown or whatever)
        rows[i][j]={"value":(i+j) % 9 + 1} # I put whatever value. Call another function... It's here you choose the values
        cols[j][i]=rows[i][j] # cols[j][i] and rows[i][j] are the SAME object
                              # altering one will alter the other

# Here is the print section.
# I use the pprint module and list comprehension to be quick on this part.
# This doesn't need to be understood ;-)
pprint.pprint([[elt["value"] for elt in row] for row in rows])
pprint.pprint([[elt["value"] for elt in col] for col in cols])

print 
# WHAT IS IMPORTANT TO SEE IS HERE
rows[3][4]["value"]=1515
# I change a rows value and in the result, you'll see that cols have changed too …
jice 53 Posting Whiz in Training

Something to think abour is also to use objects as cells (dict for example)
This way, you can use several lists to order the same cells different way.

For example

import pprint # don't worry abour this it is only to print the result quickly at the end

rows=[[0 for i in range(9)] for i in range(9)]
cols=[[0 for i in range(9)] for i in range(9)]
for i in range(9):
    for j in range(9):
        rows[i][j]={"value":(i+j) % 9 + 1}
        cols[j][i]=rows[i][j] # cols[j][i] and rows[i][j] are the SAME object
                              # altering one will alter the other

# Here is the print section.
# I use the pprint module and list comprehension to be quick on this part.
# This doesn't need to be understood ;-)
pprint.pprint([[elt["value"] for elt in row] for row in rows])
pprint.pprint([[elt["value"] for elt in col] for col in cols])

print 
rows[3][4]["value"]=1515

pprint.pprint([[elt["value"] for elt in row] for row in rows])
pprint.pprint([[elt["value"] for elt in col] for col in cols])

I didn't build the lists for the squares as it is a little more complicated and of no use for this example.
When you've done this, it is very quick and to verify all your groups...

jice 53 Posting Whiz in Training

edit: Admins/moderators, how do you put a code tag in a reply without creating a code box?

Hou can put spaces after the opening or before the closing [ ]

[/code ][code ]
[/code ]

jice 53 Posting Whiz in Training

You can do a list of lists...

rows=[[],[],[]...]
# you call a particular cell by doing
rows[3][4]
jice 53 Posting Whiz in Training

give me 40 mintues, i use this code ... ;]

This second code is only to help to find the good encoding (this is the hardest part)... Not to translate your whole file... It takes each encoding format and try to translate. If there is an exception, it writes "error".
The output shows you which encoding succeeds in encoding your file.

If the first programme raises an exception, you certainly have something wrong :
- the encoding line (# -*- coding: utf-8 -*-) MUST be consistant with the file encoding and the .decode() part of the commands.
- you've got some characters I hadn't in the string i used for my test and which isn't supported by "iso8859_13". If so, you can use the second part of my code to try to find another encoding format...

Hope this helps... Encoding is really tricky...

jice 53 Posting Whiz in Training

So I explored a little my solution (which may not be the simplest).
In your case, you have to use an encoding parameter which is using the same length to encode all the polish characters. It seems to be iso-8859-13 as mentionned here
standard-encodings
So, my example becomes :

# -*- coding: utf-8 -*-
import string
a='ąóęśłżźćńĄÓĘŚŁŻŹĆŃ' ## utf8 has variable number of bytes
b='aoeslzzcnAOESLZZCN'

t = string.maketrans(a.decode("utf8").encode('iso8859_13'),b.decode("utf8").encode('iso8859_13'))

print 'ąóęśłżźćńĄÓĘŚŁŻŹĆŃ'.decode("utf8").encode('iso8859_13').translate(t).encode("utf8")
# .decode("utf8").encode('iso8859_13') : decodes the preceeding string using the utf-8 encoding and encodes it in a fixed length encoding defining the letters you need
# .translate(t) translates the string using the rule you mentionned
# .encode("utf8") reencodes (if needed) the result (here encoded in iso8859_13) in utf8

When you're not sure of which encoding you should use, you can try this code :

# These are all the standards encodings
encs=['ascii', 'big5', 'big5hkscs', 'cp037', 'cp424', 'cp437', 'cp500', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp856', 'cp857', 'cp860', 'cp861', 'cp862', 'cp863', 'cp864', 'cp865', 'cp866', 'cp869', 'cp874', 'cp875', 'cp932', 'cp949', 'cp950', 'cp1006', 'cp1026', 'cp1140', 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255', 'cp1256', 'cp1257', 'cp1258', 'euc_jp', 'euc_jis_2004', 'euc_jisx0213', 'euc_kr', 'gb2312', 'gbk', 'gb18030', 'hz', 'iso2022_jp', 'iso2022_jp_1', 'iso2022_jp_2', 'iso2022_jp_2004', 'iso2022_jp_3', 'iso2022_jp_ext', 'iso2022_kr', 'latin_1', 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6', 'iso8859_7', 'iso8859_8', 'iso8859_9', 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15', 'iso8859_16', 'johab', 'koi8_r', 'koi8_u', 'mac_cyrillic', 'mac_greek', 'mac_iceland', 'mac_latin2', 'mac_roman', 'mac_turkish', 'ptcp154', 'shift_jis', 'shift_jis_2004', 'shift_jisx0213', 'utf_32', 'utf_32_be', 'utf_32_le', 'utf_16', 'utf_16_be', 'utf_16_le', 'utf_7', 'utf_8']
for e in encs:
    try:
        t = string.maketrans(a.decode("utf8").encode(e),b.decode("utf8").encode(e))
        print "%s : %s" % (e, 'ąóęśłżźćńĄÓĘŚŁŻŹĆŃ'.decode("utf8").encode(e).translate(t).encode("utf8")) …
Gribouillis commented: Nice. I didn't think it was possible with translate. +3
jice 53 Posting Whiz in Training

Sorry for not having been here for some days...
Gribouillis' solution is probably better.
I have used the one i told you some times but I always have problems to adjust encoding and decoding parameters...
To help you, i need your errors messages...

jice 53 Posting Whiz in Training

What's the error message ?
Probably a decoding encoding problem...
try things like

t = string.maketrans('ąóęśłżźćńĄÓĘŚŁŻŹĆŃ'.decode("utf8").encode("latin1"), 'aoeslzzcnAOESLZZCN').decode("utf8").encode("latin1"))
jice 53 Posting Whiz in Training

Problem 1 (done with python 2.4)

# -*- coding: latin-1 -*-
# The first line is important and must be consistant with your file encoding (maybe utf8)
import string
t=string.maketrans('àéèëêôöîïù', 'aeeeeooiiu') 
print "lévitèrent à l'ïstrùmen".translate(t)

for python 3.1

# -*- coding: latin-1 -*-
t=str.maketrans('àéèëêôöîïù', 'aeeeeooiiu')
print ("lévitèrent à l'ïstrùmen".translate(t))

problem 2

mylist=[]
for i in range(10):
    mylist.append([])
    for j in range(1,9,2):
        mylist[i].append(j)
print mylist

# same result with list comprehension
print [[i for i in range(1,9,2)] for i in range(10)]
jice 53 Posting Whiz in Training

You don't need to split and join...

datas = """US 9 15 13 37
GE 10 13 7 30
CA 14 7 5 26""".split("\n")
for l in datas:
    print l.split(None,1)[1] #  the 1 split argument will tell to split only once

# Faster
# you can also use lists comprehensions :
print [l.split(None,1)[1] for l in datas]
# or
print "\n".join([l.split(None,1)[1] for l in datas])
jice 53 Posting Whiz in Training

oups... indeed :-)

jice 53 Posting Whiz in Training

Here is some kind of skeleton to copy your files (you'll have to adapt it but the principle is here) :

import os, fnmatch, shutil
mydir="/path/to/my/dir/"
for filename in fnmatch.filter(os.listdir(mydir),'*.py'):
    shutil.copy(filename, "anotherDir/new-%s" % filename)

Note that if you want to explore the dir recursively, you can do:

for subdir, dirs, files in os.walk(mydir):
    for filename in files:
        shutil.copy(os.path.join(subdir, filename), "anotherDir/%s/new-%s" % (subdir.replace(mydir,""), filename)) # not tested but certainly close ;-)
jice 53 Posting Whiz in Training

Your way is so complicated :

def fileCount(filename):
    txt=open(filename).read()
    linecount=len(txt.split("\n"))
    wordcount=len(txt.split())
    charcount=len(txt.replace("\n","")) # if you don't want tou count the '\n'
    return (linecount, wordcount, charcount)
jice 53 Posting Whiz in Training

another alternative:

"-".join(DEVICE_IP.split("."))
jice 53 Posting Whiz in Training

Post your pseudo code, ask your question and we'll see...

jice 53 Posting Whiz in Training
score = score + scores(int)

don't you mean

score = score + int(scores)
jice 53 Posting Whiz in Training

2 more solutions using dict()

datas="""Avenue,Av
Road,Rd
South East,SE
Terrace,Tce""".split("\n")

# The shortest way :
print dict([(l.split(",")[0], l.split(",")[1]) for l in datas])

# a more understandable way
lst=[]
for l in datas:
    sl=l.split(",")
    lst.append((sl[0], sl[1]))
d=dict(lst)
print d
jice 53 Posting Whiz in Training

I can see 2 solutions :

list1 = ["20100122 http google.com 200", "20100124 http hushmail.com 200", "20100123 http microsoft.com 404" ]
list2 = ["google.com", "yahoo.com", "msn.com", "hotmail.com", "gmail.com"]
# 1
for i, e1 in enumerate(list1):
    for e2 in list2:
        if e2 in e1:
            print ("line %d : %s" % (i,e1))

# 2
for i,e in enumerate(list1):
    d=e.split()[2]
    if d in list2:
        print ("line %d : %s" % (i,e))

Note that I don't understand where your microsoft output line comes from.

jice 53 Posting Whiz in Training

Does this mean that it is no longer slower to concatenate a string than to build a list and join it at the end (or is it that i should hage say list = + list ) ?

jice 53 Posting Whiz in Training
def IntToNBytes(integer, n):
    while len(tmphex)<2*n:
        tmphex = '0'+tmphex

You should NOT do this. Adding characters to strings like this is very slow.
You should use a list instead (eventually, if you need a string a the end, you can join it (''.join(mylist)) :

def IntToNBytes(integer, n):
    tmphex = list(hex(integer)[2:])
    while len(tmphex)<2*n:
        tmphex.insert(0,'0')
    tmpbyte = []
    j = 0
    for i in range(n):
        tmpbyte.append(int(tmphex[j], 16)*16+int(tmphex[j+1], 16))
        j = j+2
    return tmpbyte
jice 53 Posting Whiz in Training

You problem is not clear to me :
Why is ('1101','4') the correct output ?
'1101' is in the second list...
Why not ('4472', '4') or ('5419', '2')
Are these tuples displayed if and only if the run id of the id in list 1 is greater than any run id of the same id in list 2 (or if the id isn't in list 2)

jice 53 Posting Whiz in Training

This is because we loaded the file in a list. This way, we can change whichever line we want (in the list). You can't do that directly in a file.
Then, when everything is ready, we overwrite the file 2 with the content of the list.

jice 53 Posting Whiz in Training

This should do the trick

keywords=[word1,word2,wor3,word4]
file1="/path/to/file1.txt"
file2="/path/to/file2.txt"
f2=open(file2).readlines() # I load the 2d file in a list to be able to change a line by another easily
for l in open(file1): # no need to open the file and read it before. This will read the file line by line
    for k in keywords:
        if k in l:
            for i, l2 in enumerate(f2): # enumerate will give you the number of the line and the line the same time
                if k in l2:
                    f2[i]=l # I change the line
of=open(file2,"w")
of.writelines(f2) # I rewrite the wole list
of.close()
deonis commented: very nice post! Well explained ! +1
jice 53 Posting Whiz in Training
if x != int(x):

This will tell you whether x is an int or not but should raise a ValueError if x is a non digit string ('a' for example) and will be false is x is a digit string ('6' != 6)

What you want to do is rather something like

if str(x).isdigit():

this will convert x in string (which will stay the same if x is already a string (no exception)) and will look if every character is a digit.

jice 53 Posting Whiz in Training

You should use modules like pickle or marshal to serialize and load your datas

import pickle
c=['Hondros', {'Equiped': [['none', [], 0], ['Rags', [0, 1, 0, 0], 1, 1], ['Mocassins', [0, 0, 1, 0], 1, 1], ['Gauntlets', [0, 0, 0, 1], 6, 5]], 'Equipment': [0, 1, 1, 1], 'Stats': {'AC': 14, 'Strength': 15, 'Constitution': 14, 'Level': 1, 'HP': 12, 'Experience': 0, 'Dexterity': 12, 'Intelligence': 12, 'Base AC': 8, 'Wisdom': 11, 'HP max': 12}, 'Inventory': [], 'Gold': 0}]
f=open('test.pkl','wb')
pickle.dump(c, f)
f.close()
f=open('test.pkl','rb')
d=pickle.load(f)
f.close()
print d[1]['Stats']

Eventually, you can use exec but this is not to be recomended

a = "['Hondros', {'Equiped': [['none', [], 0], ['Rags', [0, 1, 0, 0], 1, 1], ['Mocassins', [0, 0, 1, 0], 1, 1], ['Gauntlets', [0, 0, 0, 1], 6, 5]], 'Equipment': [0, 1, 1, 1], 'Stats': {'AC': 14, 'Strength': 15, 'Constitution': 14, 'Level': 1, 'HP': 12, 'Experience': 0, 'Dexterity': 12, 'Intelligence': 12, 'Base AC': 8, 'Wisdom': 11, 'HP max': 12}, 'Inventory': [], 'Gold': 0}]"
exec("b=" + a)
print b[1]['Stats']
jice 53 Posting Whiz in Training

Read the last post of masterofpuppets to your other thread (http://www.daniweb.com/forums/thread235765.html) and you'll nearly have the answer...
Put his code in a function (pascrow), change the for loop condition and the print statement and you've got it

jice 53 Posting Whiz in Training

Oh yes, you've got another choice. Use your brain.
This assignment is fairly doable and, if you search this forum or others, you'll find plenty of ways to do it.
I'm afraid that your post shows someone that doesn't want to bother with this assignment. I'd be interested in knowing why you think someone else would bother to solve it for you.
You say you would pay for that. How much would you do ?
Be serious. I can't imagine one here would ask for being paid for that as it would take less that 30 mn to do the whole stuff.

jice 53 Posting Whiz in Training

You can have a look at this to have an idea of web programming in python
http://webpython.codepoint.net/
and this
http://webpy.org/
I've never done web programming in python because norm in my job is php so i had to learn php. And i find it much less pleasant to write.
If I had choice, i'd certainly give a chance to python because it's very pleasant and fast to write.

jice 53 Posting Whiz in Training

doing
x=Stuff
make of x an alias to the Stuff class.
Try this :

class Test:
    def __init__(self):
        self.a="a"

x=Test
print x
y=x()
print y.a

This may be useful if you want to pass an object definition as an argument for a function. Never happened to me yet but it may be interesting in some case...
What "often" happens is to pass a function (without ()) as an argument of a function of another object. This is known as callback. Search the web for more information about callbacks...

jice 53 Posting Whiz in Training

you can use list comprehensions

g = "ThisIsATestt"
print [g[i:i+2] for i in range(0,len(g),2)]
jice 53 Posting Whiz in Training

I would add that exactly the same question was posted 2 days ago.
http://www.daniweb.com/forums/thread230626.html
It would be a good idea to search the forum before asking...

jice 53 Posting Whiz in Training

When I say end is excluded, i mean that :

for i in range(0, 10):
    print i,

> 0 1 2 3 4 5 6 7 8 9

No 10 in the list.
range(0,10) = [ 0, 10 [ in the mathematical writing way
This means that if you want to loop backward from end to start, you have to do

for i in range(len(s)-1, -1, -1):

jice 53 Posting Whiz in Training

Totally agree with Gribouillis. This is not a good way of doing things. Many problems may occur.
You may use a dictionnary instead:

def myfunc(arg1, arg2):
    d={'x':2, 'y':3, 'z':4}
    return d[arg1], d[arg2] 
 
print myfunc('x', 'y') # returns: 2, 3
print myfunc('y', 'z') # returns: 3, 4

But in this case, you should even imagine args are not what you are waiting for

def myfunc(arg1, arg2):
    d={'x':2, 'y':3, 'z':4}
    try:
        a=d[arg1]
    except KeyError:
        a="%s not handled" % arg1
    try:
        b=d[arg2]
    except KeyError:
        b="%s not handled" % arg2
    return a,b
 
print myfunc('x', 'y') # returns: 2, 3
print myfunc('y', 'z') # returns: 3, 4
print myfunc('g', 'z') # surprise

Of course what I do here in the try except blocks may be very different depending on your needs.
You also don't need to have 2 differents blocks

jice 53 Posting Whiz in Training

My 2 cents...
1 - I prefer for loop than while ones when I can (less code to write and no infinite loops).

start = int(raw_input("Start at: "))
end = int(raw_input("End at: "))
count = int(raw_input("Count by: "))

for i in range(start,end+1,count) : # end + 1 because range considers the end term excluded.
        print i,

2- First code
I put prints for you to understand what happens

s = raw_input("Enter a string: ")
print "len(s)=", len(s)
rev = ""
for i in range(len(s)):
    print "i=", i, "-i-1=", -i-1
#i only want to modify the "s[ ]" part, don't want to change any other part of the code
    rev = rev + s[-i-1] # counting negative way takes the string from the end (s[-1] = last character)
print "The reverse is: " + rev

second code

s = raw_input("Enter a string: ")
rev = ""
#for this code, I only want to modify the "range( )" part of the code, i don't want to change any other part of the code
for i in range(len(s)-1, -1, -1): # range(start, end, count) start included, end excluded, count negative. this will go backward from the end of the string
    rev = rev + s[i]
print "The reverse is: " + rev
jice 53 Posting Whiz in Training

As far as I know, this is some kind of standard behaviour.
Old languages [ troll] like C [ /troll] made difference between value and reference...
To have this behaviour in "non object" langage (in C), you passed pointers for "reference" assigment.
In object languages, especially when you don't have pointers (maybe vegaseat could lighten un about C++) reference is the standard way.

jice 53 Posting Whiz in Training

Sorry, I typed the wrong key... So...
Simply think that, when you assign a variable to another (say b=a), it is a reference assignment. If you change PART of b, you'll change a too. If you reassign b, just think it becomes another variable and does not reference a anymore so a and b will be different.

jice 53 Posting Whiz in Training

I typed the wrong key...
So... Simply think that, when you assign a variable to another, it is a reference assignment. If you change PART of b, you'll change a too. But, if you reassign b, just think b becomes another variable and does not reference a anymore.

jice 53 Posting Whiz in Training

I think he means everything but basic datatypes like int, floats and strings. However, you can do as if it was always true.

This is what i meant.
Try this and think of what it means :

a=13
b=a
b=14
print a
a=[1,2,3]
b=a
b[1]=4
print a
a=[1,2,3]
b=a
b=[4,5,6]
print a

Simply think that, when you assign a variable to another, it is a reference assignment. If you ch
just think b becomes another variable and does not reference a anymore.

jice 53 Posting Whiz in Training

Look at the buildin functions in the manual... you've got some parameters.
You just have to write :

print ('Enter quiz score %d: ' % i, end='')
jice 53 Posting Whiz in Training

Beware of the '\'. You should write

textfile = file('C:\\HourlyATC\\ATC101509\\10-15-09 to 10-21-09 ATC.txt','w') # \\ and 'w'
jice 53 Posting Whiz in Training

It points to the original variable.
This is true for all variables containing objects.
For a list, if you want to duplicate it, you have to do

mylist = [1,2,3,4]
    a = mylist[:]
    a[0] = 'hello'
    print mylist
jice 53 Posting Whiz in Training
numQuiz = input("Enter the number of quizzes:  ")
total = 0
for i in range(numQuiz):
    print ('Enter quiz score %d: ' % i) # 
    # OR
    print ('Enter quiz score ', str(i), ' : ')
    score= input()
    total = total + score
print "------------------------------------"
# Compute the average and print it.
average = total / numQuiz
print "The average is", average
jice 53 Posting Whiz in Training

You should run your program with pythonw.
This can be done in your command line or by renaming your .py file .pyw

jice 53 Posting Whiz in Training

__repr__ is not required as you are only sorting your objects.
I put it here just to introduce this way of printing objects.
If you have a complex object with some interesting fields to display, defining __repr__ will be an easy and clean way to do this.
Instead of doing

print "%s - %s" % (str(myobject.data1), str(myobject.data2))

each time i want to print the object useful datas, I just have to do

print myobject
# if __repr__ is defined and returns "%s - %s" % (str(self.data1), str(self.data2))
jice 53 Posting Whiz in Training

"Error connecting to MySQL..." is not the error you have, it is the error you defined, in your try - except block, hiding the mysql error message. So, to know what error you exactly have, you should remove this block or put a "raise" instead of "return".

jice 53 Posting Whiz in Training

If I knew how the 2nd line of Jiccess code I could make it work. But I forgot to mention that each POS variable is in a certain place. I won't work to only have 1 variable. I also forgot to mention that scru's code didn't work either, it said that POS1 wasn't defined.

Sorry but I don't understand what you mean.
What do you mean with "each POS variable is in a certain place" ?

If I use one variable, it contains the tenth values.
Instead of using POS1, you'll use pos[0], POS5 will become pos[4]...

jice 53 Posting Whiz in Training

The question is : what error do you have ?

jice 53 Posting Whiz in Training

Why do you want to have vars named POSn.
I wouldn't do that...
Very complicated. It's far easier to have one list variable where you assign pos[n]

pos=['  ' for i in range(10)] # defines a list inited with ['  ', '  ',... ten times]
pos[POS-1]='->'
jice 53 Posting Whiz in Training

Sorry, I answered too fast :

zipFile.write(filedir+'/'+pathname, zipFile, compress_type=None)

zip is not defined in your program, so it refers to the builtdin function which has nothing to do with zip archives...
The object you want to write in is the onr you defined here :

zipFile = zipfile.ZipFile(picSetup[0]+'/'+zipName, 'w')