jlm699 320 Veteran Poster

It's hard to help you without the full traceback of the error but here's my two cents:

You're parsing the file contents incorrectly. What you should be doing is splitting each line at the tab character to get time stamp, port number, then the remaining string of floats. At this point you can sum the floats together and get a single float for your data list.

Here's how I would parse the data you provided:

>>> data_stor = []
>>> for line in file_hol:
...     data = line.split('\t')
...     if len(data) == 3:
...         tstamp = data[0].strip()
...         port = data[1].strip()
...         valu = sum([float(ea) for ea in data[2].strip().split()])
...         data_stor.append([tstamp, port, valu])
...     
>>> max(data_stor, key=lambda x:x[2])
['501', '6', 7.7770000000000001]
>>>

This returns that port 6 at timestamp 501 has the highest sum of numbers.

jlm699 320 Veteran Poster

but i just can't figure out how to make it work.
can anybody help me?

You were very close:

def one(s):
    if s == '':
        return [s]
    else:
        ans = []
        if s[1:] == '': return ans
        for o in one(s[1:]):
            ans.append(prevLetter(s[0])+o)
            ans.append(nextLetter(s[0])+o)
        return ans

You never made use of o in your function. You were for whatever reason trying to use ''.join(x) (NOTE: that is equivalent to string.join(x, '') ).

Your function can be further simplified as such:

def one4(s):
    if s == '': return [s]
    else:
        return [prevLetter(s[0]) + o for o in one(s[1:])] + \
               [nextLetter(s[0]) + o for o in one(s[1:])]
jlm699 320 Veteran Poster

Ive got that one too... what should i do next?

Open the archive, extract the files to your site-packages directory and use them as needed.

jlm699 320 Veteran Poster

Ive been searching on google but I cant find an .exe or a .zip file, for example Pmw.exe or Pmw.zip.
But I could find loads of tar.gz files, does this means that I cant have it, of course winzip cant open a file that is made for unix systems.
What can i do?

Do yourself a favor and uninstall winzip. Download 7zip, which can handle all the important compressed formats

jlm699 320 Veteran Poster

I guess I will have to do the .0 'trick'. Maybe some other folk will know a way.

Thanks wildgoose for your help.

You could do this:

float(4)/5

Or if you wanted to perform the from __future__ import division and still get integer returns you could simply turn the answer into an int like this:

>>> ans = 5 / 2
>>> ans
2.5
>>> int(ans)
2
>>>
jlm699 320 Veteran Poster

(a & b):
What happens with logical and? If a is false, does python evaluates b or not?

No. Here's the code I just used to check this:

>>> def a():
...     print 'a'
...     return False
...     
>>> def b():
...     print 'b'
...     return True
...     
>>> a() and b()
a
False
>>> b() and a()
b
a
False
>>>
vegaseat commented: good example +13
jlm699 320 Veteran Poster

Hi. Thanks a lot for your response. You gave me the tip I was looking for. os.getcwd() did the trick.

file_path = os.getcwd() + "\\some_file.xls"
exc.open(file_path)

Cheers.

As a tip: You don't need to use the + "\\ ... as you could use os.path.join(os.getcwd(), 'some_file.xls') . Although it's your preference... Just this way you don't need to worry about the escape/path characters.

jlm699 320 Veteran Poster

There are two ways I know to do this:
1) Use an absolute path, ie instead of simply some_file.xls specify "C:/Documents and Settings/UserName/My Documents/some_file.xls" 2) Change the current working directory using os.chdir(desired_path) . You can also check your current working directory using os.get_cwd()

jlm699 320 Veteran Poster

(The reason I have two "setup" methods is because in the first one I return a variable, and in the second one I have to bind an action to a key. As far as I know, these can't both be done within the same method.)

That is misinformation, what led you to believe that?

jlm699 320 Veteran Poster

Hi all,

I'm trying to mimic an html form that calls a script on the web. When I put the form together on a page, it works, and I was wondering if there was a way I could "scrape" this post request and see what I'm missing when I try to do it with Python?

If you've got Firefox you can load up Firebug and take a look at the POST contents under the Net panel. This is also a nice way to see what Headers are sent to authenticate with websites, which you can then spoof with your Python code.

jlm699 320 Veteran Poster

Thanks for reply

If i set the second index as END, then it will receive string data
from line#(index1) to the END..
but I need to read string line by line, not directly from certain line to the end.

If there is no method or attribute for this,
seems like string.split is the only option..

Did you follow that link I posted? There are special ways to work with indices such as "line.end", lineend, etc... Try reading up on that page that is linked and see if those don't answer your question.

jlm699 320 Veteran Poster

I believe you can specify the second index as END... refer to the text widget indices guide here.

These mostly seem to be tk constants, but let me know if that is a misconception.

jlm699 320 Veteran Poster

Because if I just replace T = Test() with T = Test(myapp), the argument it pass to "__init__", not "run". How would I go about doing this?

There might be a smarter way of doing this, but you could store those variables in a member at the __init__ function and then access those members as needed in run.

jlm699 320 Veteran Poster

2.2**2 resulting 4.840000000000001

which we all know that is incorrect.

Why is that incorrect? http://www.google.com/search?q=2.2^2

jlm699 320 Veteran Poster

Now what i wish to do is read a file, use a dictionary to search lines, and then get these lines and write to a new out put file. Is that possible?

That is how I interpret your question, so let me know if I read it wrong.

To read and/or write to a file you use the builtin open method, here's the documentation.

I'm not sure what you mean by use a dictionary to search lines.

jlm699 320 Veteran Poster

This shouldn't make a difference but the proper way to use the with statement is like so:

with open('C:/Python31/SKUs.txt', 'w') as txtfile:
    num = 817
    while num <= 820:
        x = "G" + str(num)
        txtfile.write(x)
        num += 1

Notice I omit closing the file. That's because the with syntax automatically closes the file handle. AFter that loop you can test with txtfile.closed , which should return True because it's closed.

jlm699 320 Veteran Poster

Okay, I changed it to the following, but when I run it and open the file, the document is still blank.

txtfile = open('C:/Python31/SKUs.txt', 'w')

with txtfile:
    num = 817
    while num <= 820:
        x = "G" + str(num)
        txtfile.write(x)
        num += 1

txtfile.close()

That code works fine for me. What platform are you on?

jlm699 320 Veteran Poster

You'll need to actually write to your file handle txtfile by using txtfile.write( text ) .

jlm699 320 Veteran Poster

Did this just start or has it happened always? It almost sounds like you may have inadvertently borked your Python install. I'd suggest a clean install.

jlm699 320 Veteran Poster

As little as I can remember 1 mile is about 1.6 km, so 1 km is 1/1.6 miles.

According to the Google:

1 kilometer = 0.621371192 miles

jlm699 320 Veteran Poster

As far as asking the user for input use either raw_input or input depending on your version of Python. Then the conversion is simple math. Just google "1 kilometer to miles" and it will give you the conversion rate.

jlm699 320 Veteran Poster

You can use in to figure out if a list (or string for that matter) contains a particular element:

>>> act_in = "I would love to take alice and punch her in the mouth"
>>> action = act_in.lower().split()
>>> if 'alice' in action:
...     print('This action will be performed on Alice')
... elif 'bob' in action:
...     print('This action will be performed on Bob')
... 
This action will be performed on Alice
>>> if 'punch' in action:
...     print('The target is getting punched')
... elif 'kick' in action:
...     print('The target is getting kicked')
...     
The target is getting punched
>>>

I believe that in simply makes use of the list method index (or analogously string.find ), which returns the index of the element you're looking for, and -1 if it does not exist in the list (string). So in would be the true/false version of using list.index (or string.find ).

So in the above code, splitting the string into a list is unnecessary if you're not using indexing to access individual words. Leave the action as a string and you can just ask if the word you're looking for is in the string.

>>> act_in = 'Sometimes, I like to kick people in the teeth.  One of the people that I frequently kick is named Bob.  That Bob is such an idiot.'
>>> action = act_in.lower()
>>> 'bob' in action
True
>>> 'alice' in action
False
>>> 'punch' in action
False
>>> 'kick' in action
True …
jlm699 320 Veteran Poster

If you were to split the users input into a list you can use list indexing to call out each word individually. Here's an example:

>>> act_in = "punch Alice in the face"
>>> act_in_parts = act_in.split()
>>> action = act_in_parts[0]
>>> target = act_in_parts[1]
>>> action
'punch'
>>> target
'Alice'
>>>
jlm699 320 Veteran Poster

I've been unable to get to it for the last hour or so.

This is a great site to keep in mind when you're posed with this question in the future...

www.downforeveryoneorjustme.com

lllllIllIlllI commented: Ah, i love that site! +4
jlm699 320 Veteran Poster

I'm thinking you should just be "adding" the lists together instead of appending a list onto a list... if you know what I mean.

Like this:

import re

def test():
    a = "<this is> <a> test"
    b = re.split("(<|>)", a)
    c = []
    for item in b:
        c += item.split()
    print(c)

if __name__ == '__main__':
    test()

""" My Output:
['<', 'this', 'is', '>', '<', 'a', '>', 'test']
"""

Is that what you're looking for?

jlm699 320 Veteran Poster
#open inventory and add contents to contents list
    newfile = open("inventory.txt", "rt")
    for item in newfile:
        ## Use strip here to remove the newlines that you're reading in
        contents.append(item.strip())
    newfile.close()

You're right... it's important to remember that when reading files, each line has a newline on the end of it. It's usually a good idea to always use strip() to strip the white space off of the end (as well as the beginning of the line - so if you've got tabs or spaces prepending your text use rstrip to only get the right side of the line clear of white space).

jlm699 320 Veteran Poster

For one thing, don't name your list "list", as that's a reserved word in Python (try list('12345') ), same thing with file... But that modification won't help you.

I'm assuming you've got a new version of Python installed, as the method you're using will only work in earlier versions of python.

pickle.dump(obj, file[, protocol, *, fix_imports=True])¶

Write a pickled representation of obj to the open file object file. This is equivalent to Pickler(file, protocol).dump(obj).

The optional protocol argument tells the pickler to use the given protocol; supported protocols are 0, 1, 2, 3. The default protocol is 3; a backward-incompatible protocol designed for Python 3.0.

Specifying a negative protocol version selects the highest protocol version supported. The higher the protocol used, the more recent the version of Python needed to read the pickle produced.

The file argument must have a write() method that accepts a single bytes argument. It can thus be a file object opened for binary writing, a io.BytesIO instance, or any other custom object that meets this interface.

If fix_imports is True and protocol is less than 3, pickle will try to map the new Python 3.x names to the old module names used in Python 2.x, so that the pickle data stream is readable with Python 2.x.

That's from the 3.1 docs; note that you must open your files in binary mode now. So for dumping use 'wb', and loading use 'rb'.

jlm699 320 Veteran Poster

don't know how to create a window installer

I've used NSIS to create Windows installers from my py2exe programs in the past.

jlm699 320 Veteran Poster

1. What is the "vs solution" ?
2. How are you performing your "build and clean" ?
3. What isn't creating the .exe ?

jlm699 320 Veteran Poster

sqlite3.OperationalError: near "?": syntax error

File "f:\Hosanna\CodeBase\PyCodeBase\sqlite_on_test.py", line 26, in <module>
test.CreateNewTable("testing")
File "f:\Hosanna\CodeBase\PyCodeBase\sqlite_on_test.py", line 12, in CreateNewTable
self.cur.execute("CREATE TABLE IF NOT EXISTS ?(id INTEGER, name TEXT)", (tablename, ))

Yup, that's a syntax error in the SQL command. Read up on SQL syntax here.

jlm699 320 Veteran Poster

I believe sys.stdout.flush() is what you're looking for. Those stdio handles are just like open file handles

jlm699 320 Veteran Poster

Use os.system("RD /s folderName") or subprocess.Popen depending on your python install

jlm699 320 Veteran Poster

Thank dears.So I have to chose one between wxpython and pygtk...your mean that pygtk is better to learn?
and another question.to use a database I learned sql language and there is not basic differences between mysql, sqlite and etc.

You don't need to choose one, you can learn them all and be your own judge for their pros/cons. None of them are "better" to learn, as all learning is beneficial and will bolster your skill set.

There are different implementations of SQL, and for each one there are different modules to take advantage of. This is another choice that depends on your necessity. I've used postgresql in the past with Python and had great success.

jlm699 320 Veteran Poster

sys.stdin is an "always open" file handle to the stdin and likewise sys.stdout. To use them, import sys.

jlm699 320 Veteran Poster

listen i want to make high professional program

You can add GUIs and pretty stuff later. When making a "high professional program" you must make sure it works well before it looks good.

Test the lines in the interpreter to figure out why it's taking so long.

The GUI frame does not respond because it's waiting for the function that you're calling to return. If you want the GUI updated while you're running a long/complex function you'll need to run it in a separate thread.

If you don't want to bother figuring out why your function is taking so long, you could use a Busy Cursor (hour glass) to indicate to the user that they should wait.

jlm699 320 Veteran Poster

computer is clushing.
and GUI programm's main frame become Not Responding.

Your computer is crashing?

Why don't you try to perform the urlretrieve section by itself in the interpreter. Maybe you've provided an invalid url or the wrong syntax.

jlm699 320 Veteran Poster

Also, when "Specify the number of threads" is asked, if I enter around 100,000, after a few seconds, it says thread could not be created? Any ideas why?

You're probably over-loading your cpu. There's no reason that you should ever be creating that many threads...

jlm699 320 Veteran Poster

#1 doubt:
Why do I have to specify 'self' while defining the function? I usually don't do it if the function isn't in a class, then why if it is in a class?

LOLWUT? myThread is a class, so naturally you should be specifying self... I don't really understand what you're asking though...

#2 doubt:
Why is variable 'a' first defined to be 1, and then globalized in the function specifically in the class? Why can't I do:

global a
a=1

class myThread(threading.Thread):    
    def run(self):
        print(a)
        a+=1

Because that's not how you use globals. You're supposed to identify a global variable as needed. So when your function gets "run", the command global a tells the program to pull in a reference of a from the global namespace.

And for your third doubt... I'm running the exact code with 100+ and not seeing repeats... so I'm not sure what you're talking about

jlm699 320 Veteran Poster

Explain what's wrong or else nobody can help you.

Here's the documentation on urlretrieve.

jlm699 320 Veteran Poster

In the top-most bar (with the <DANIWEB> logo) select Control Panel -> Edit Options. On that page look for Messaging & Notification section (should be second gray section)

Uncheck the boxes that read "Receive Occassional Email from DaniWeb" and "Receive Email from Other Members".

Finally, on the drop down for Default Thread Subscription Mode make sure "No email notification" is selected.

That should be all you need.

jlm699 320 Veteran Poster

The equivalent device in python is slicing:

>>> my_text = 'Rajesh Kumar'
>>> my_text[3:]
'esh Kumar'
>>> my_text[1:2]
'a'
>>>

This example is analogous to the example on this page, which gives example usage of Java substring.

jlm699 320 Veteran Poster

If the python program quits with an error the return code is 1. If it successfully runs the return code is 0.

You can alternately specify your own return codes using sys.exit(return_code_value) at specific exit points of your code.

jlm699 320 Veteran Poster

what is the best way to go? XML or Pickle? or Anything else?

Pickle. XML is way too much overhead for such a simple task.

jlm699 320 Veteran Poster

I'm not sure if tkinter has changed in py30 and above but shouldn't you be using awin.destroy ?

jlm699 320 Veteran Poster

I know I am linking to the right stuff as the first block of code works.

That's very peculiar. I wonder if there is some sort of timing issue happening when you're repeatedly opening and closing the database connection...

Why don't you just try to move the db = , cursor = and db.close statements outside of the for loop and see if that gives you any better results.

As far as I can tell everything looks okay.

jlm699 320 Veteran Poster

open the Sound Recorder, but how do I make it to start recording?

That's not the kind of thing that subprocess was intended for. That kind of behavior is more akin to win32 hooks.

Subprocess can manipulate std input but not buttons on a GUI. As sneekula said, if the windows sound recorder can be fully utilized through command line processes then you'll be good to go, otherwise you'll need to figure out if that program has any win32 handles to work with.

jlm699 320 Veteran Poster
print(command)
    cursor.execute(command)
    db.commit
    cursor.close()
    db.close()

Can you give us some example output from the print(command) trace code? It could be as simple as a missing quote or an improper tablename. Also, where is tablename even coming from? I don't see it in your code anywhere.

jlm699 320 Veteran Poster

but the list of tuples could be easily sorted.

Yeah, that link I provided actually demonstrates a sorting method as such: sorted(_, key=lambda x: -x[1]) EDIT: By the way, the '_' should be replaced by your variable name or the data itself if you were to implement this in a script. The usage of '_' is really only useful in the interpreter as a shortcut for the last return value.

jlm699 320 Veteran Poster

This isn't builtin, but my first hit on a google search for 'python list frequency' was this:

>>> alist = [ '1', '1', '2', '1', '3', '4', '1', '3']
>>> [(a, alist.count(a)) for a in set(alist)]
jlm699 320 Veteran Poster

Using your example string, we can separate at the whitespace using split(), and then locate the index of "welcome" using index(). Finally slicing the list by the result of index() + 1 will give us "to".

Here's some examples of using the above principals:

>>> example_msg = "Hello, welcome to DaniWeb"
>>> example_words = example_msg.split()
>>> index = example_words.index('welcome')
>>> example_words[index + 1]
'to'
>>>

Hope that's clear enough.