Re: [Tutor] Which is better in principle: to store (in file) calculated data or to re-calculate it upon restarting program?

2019-07-31 Thread Chris Roy-Smith

On 31/7/19 2:21 am, boB Stepp wrote:

I have been using various iterations of a solitaire scorekeeper
program to explore different programming thoughts.  In my latest
musings I am wondering about -- in general -- whether it is best to
store calculated data values in a file and reload these values, or
whether to recalculate such data upon each new run of a program.  In
terms of my solitaire scorekeeper program is it better to store "Hand
Number, Date, Time, Score, Total Score" or instead, "Hand Number,
Date, Time, Score"?  Of course I don't really need to store hand
number since it is easily determined by its row/record number in its
csv file.

In this trivial example I cannot imagine there is any realistic
difference between the two approaches, but I am trying to generalize
my thoughts for potentially much more expensive calculations, very
large data sets, and what is the likelihood of storage errors
occurring in files.  Any thoughts on this?

TIA!

From a scientific viewpoint, you want to keep the raw data, so you can 
perform other calculations that you may not have thought of yet. But 
that's not got much to do with programming ;)

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


Re: [Tutor] is there a graphics library for common tkinter Button functions?

2019-03-21 Thread Chris Roy-Smith

On 21/3/19 10:19 am, Alan Gauld via Tutor wrote:

On 20/03/19 22:43, Chris Roy-Smith wrote:
Is there a "graphics library" of common button uses? that is things 
like forward record, back record, 1st record, last record, printer, 
save and the likes.


The short answer is no. But you can assign any bitmap image
to a button. (You can use other formats too but bitmaps are
easiest in my experience!)

But putting an image on the button does not give it any
functionality. You need to program that yourself.

HTH,

Alan G.

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


Thanks Alan,

Yes I knew that buttons need a function to do anything.

I was hoping that the wheel didn't need re-inventing.

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


[Tutor] is there a graphics library for common tkinter Button functions?

2019-03-20 Thread Chris Roy-Smith

Hi,
Is there a "graphics library" of common button uses? that is things like 
forward record, back record, 1st record, last record, printer, save and 
the likes.
I don't have very artistic abilities, so would prefer to save making my 
own library.


Thank you
Chris Roy-Smith

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


Re: [Tutor] Tkinter: Can's figure out how to put a frame in a second window

2019-03-09 Thread Chris Roy-Smith

On 9/3/19 10:13 pm, Alan Gauld via Tutor wrote:

On 09/03/2019 02:53, Chris Roy-Smith wrote:


What is happening is that the contents of the frame appear in the master
window. I was expecting them to show in the second window. Also I
expected the frame to be sunken, but there is no obvious signs of the
frame, not even a colored background.

What am I doing wrong?

Its a very common mistake in Tkinter.
When you use one of the layout managers, in this case grid()
the return value is always None.


def NewWindow():
      sw=Toplevel(master)
      sw.title('New Window')
      Label(sw, text='new window').grid(row=0, column=0)
      sframe=Frame(sw, relief=SUNKEN, bg='red').grid(row=1, column=0)

So you are here assigning None to sframe.


      Label(sframe, text='Label in a frame').grid(row=2, column=0)
      Label(sframe, text='Second label in this frame').grid(row=3, column=0)

And when you pass None as the parent to a widget Tk
defaults to the root. So your widgets appear in your main window.

Change the sframe line to two lines:

sframe=Frame(sw, relief=SUNKEN, bg='red')
sframe.grid(row=1, column=0)


and all will be well

except the sunken relief wont work.
TYhats because the sunken form requires a border width of at least 2
pixels to be visible. So you need to add border=2 (or more) to make
it work.

So the final line should be:

sframe=Frame(sw, border=2, relief=SUNKEN, bg='red')
sframe.grid(row=1, column=0)

As I say its a very common mistake and so, any time weird things
happen, always check that anywhere you assign a widget to a variable
you call the layout manager on a separate line.

HTH


Thanks Alan,

Simple when you know. I remember having a similar issue with Entry widgets,

Regards, Chris Roy-Smith

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


[Tutor] Tkinter: Can's figure out how to put a frame in a second window

2019-03-09 Thread Chris Roy-Smith

Hi.

running Linux, with python3.6

I am trying to learn how to put a frame on a second window. I get no 
errors showing in the terminal, and I get no traceback.


What is happening is that the contents of the frame appear in the master 
window. I was expecting them to show in the second window. Also I 
expected the frame to be sunken, but there is no obvious signs of the 
frame, not even a colored background.


What am I doing wrong?

Thank you, Chris Roy-Smith

here is my code:

#! /usr/bin/python3
from tkinter import *

def NewWindow():
    sw=Toplevel(master)
    sw.title('New Window')
    Label(sw, text='new window').grid(row=0, column=0)
    sframe=Frame(sw, relief=SUNKEN, bg='red').grid(row=1, column=0)
    Label(sframe, text='Label in a frame').grid(row=2, column=0)
    Label(sframe, text='Second label in this frame').grid(row=3, column=0)
    Button(sw, text='close window', command=sw.destroy).grid(row=5, 
column=0)


master=Tk()
master.title('Master Window')
Button(master, text='open window', command=NewWindow).grid(row=1, column=1)
Button(master, text='quit', command=master.destroy).grid(row=2, column=1)
Label(master, text="learning").grid(row=0, column=0)

master.mainloop()


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


Re: [Tutor] Python installtion

2019-01-13 Thread Stephen Nelson-Smith
Hi,

On Mon, Jan 7, 2019 at 11:11 AM mousumi sahu
 wrote:
>
> Dear Sir,
> I am trying to install python 2.7.10 on HPC. Python 2.6 has already been
> install on root. I do not have root authority. Please suggest me how can I
> do this.

Sorry - I replied to you directly, by accident.  Take 2, with reply all:

You need to do a local installation of Python, and set up your system
to use that in preference to the one at the system level.  Although
it's possible to do this with various manual steps, there's a really
handy tool you can use which will make your life easier, and allow you
to manage multiple versions of Python, which might be useful, if you
wanted, say, to be able to run both Python 2 and Python 3.  The tool
is called `pyenv`, and as long as you have a bash/zsh shell, and your
system has a C compiler and associated tools already installed, you
can install and use it.

The simplest approach is to clone the tool it from git, modify your
shell to use it, and then use it to install Python.  Here's a sample
way to set it up.  This won't necessarily match your exact
requirements, but you can try it, and please come back if you have any
further questions:

1. Clone the git repo into your home directory

git clone https://github.com/pyenv/pyenv.git ~/.pyenv

Pyenv is very simple, conceptually.  It's just a set of shell scripts
to automate the process of fetching, compiling, and installing
versions of Python, and then massaging your shell to make sure the
versions you have installed are used in preference to anything else.
So now you have the tool, you need to configure your shell to use it.
I'm going to assume you're using Bash.

2. Make sure the contents of the pyenv tool is available on your path

echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile

Note - this might need to be .bashrc, or something else, depending on
your os/distro/setup.  However, in principle you're just making the
pyenv tool (which itself is just a set of shell scripts) available at
all times.

3. Set your shell to initialise the pyenv tool every time you start a new shell

echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n  eval "$(pyenv
init -)"\nfi' >> ~/.bash_profile

Again: this might need to be .bashrc

4. Now open a new shell, and check you have pyenv available:

$ pyenv
pyenv 1.2.9-2-g6309aaf2
Usage: pyenv  []

Some useful pyenv commands are:
   commandsList all available pyenv commands
   local   Set or show the local application-specific Python version
   global  Set or show the global Python version
   shell   Set or show the shell-specific Python version
   install Install a Python version using python-build
   uninstall   Uninstall a specific Python version
   rehash  Rehash pyenv shims (run this after installing executables)
   version Show the current Python version and its origin
   versionsList all Python versions available to pyenv
   which   Display the full path to an executable
   whence  List all Python versions that contain the given executable

See `pyenv help ' for information on a specific command.
For full documentation, see: https://github.com/pyenv/pyenv#readme

If you don't have pyenv working at this stage, come back and I'll help
you troubleshoot.  Assuming you do, continue:

5. Now you can install a version of Python, locally :

pyenv install --list

This shows you the various options of Pythons you can install.  You
want the latest 2.7:

pyenv install 2.7.15

This will fetch the source code of Python, and compile and install it
for you, and place it in your local shell environment, where you can
use it.

If this step doesn't work, it's probably because your system doesn't
have a compiler and associated tools.  I can help you troubleshoot
that, but ultimately you'll need support from your system
administrator at this point.

Assuming it's install Python, now you just need to tell your shell
that you want to use it:

pyenv local 2.7.15

This will make your shell find your 2.7.15 installation ahead of the
system python:

$ python --version
Python 2.7.15

Now you can run and use your Python.

Any further questions, sing out.

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


Re: [Tutor] Debugging a sort error.

2019-01-13 Thread Stephen Nelson-Smith
Hi,

On Sun, Jan 13, 2019 at 8:34 AM  wrote:

> description.sort()
> TypeError: unorderable types: float() < str()

So, fairly obviously, we can't test whether a float is less than a
string.  Any more than we can tell if a grapefruit is faster than a
cheetah.  So there must be items in description that are strings and
floats.

With 2000 lines, you're going to struggle to eyeball this, so try
something like this:

In [69]: irrational_numbers = [3.14159265, 1.606695, "pi", "Pythagoras
Constant"]
In [70]: from collections import Counter
In [71]: dict(Counter([type(e) for e in irrational_numbers]))
Out[71]: {float: 2, str: 2}

If with your data, this shows only strings, I'll eat my hat.

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


[Tutor] Performance Issue

2018-10-17 Thread Stephen Smith
I have written a screen scraping program that watches a clock (on the app's
server) and at 7:00:00 AM dashes to make a reservation on line. It works
fine. However, i have spent time trying to improve its performance. I am
using selenium, with chrome driver. 

Here is what i have learned. I have tried various methods to find (by
link_text, by_xpath, etc.) and click on the element in question (shown
below). When i find the element with no click, the find process takes about
.02 seconds. When i find it with a click (i need to select the element and
move to the next iframe) it takes over a second. I get these same results no
matter which find_element_by variation i use and i get the same times in
headless or normal mode.

Here is my theory - finding the element is relatively simple in the html
already loaded into my machine - hence .02 seconds. However, when i click on
the element, processing goes out to the server which does some stuff and i
get a new iframe displayed, all of which takes time. So i have sort of
concluded that perhaps I can't take a big chunk of that time out (literally
the same statement without the click option takes 2% of the time), but am
hoping perhaps someone has another thought. I had thought maybe i could jump
to the second ifame locally, but can't see a way to do this. I also have
considered something other than selenium, but since i think the problem lies
on the server side, not sure it is worth the time.

Thanks in advance for any ideas.

The program is quite large, but here is the relevant section:

#   Back from NAP - REALLY CLOSE to 7:00 AM select the date desired and
go to the next page (really iframe) - using prepared xpath

try: 

br.find_element_by_link_text(str(day_to_book)).click()

#sleep(refresh_factor)

except NoSuchElementException:

 self.queue.put("- (" + thread + ") Attempted date selection too
early? " + str(datetime.datetime.now()\

+ datetime.timedelta(seconds =
second_difference))[-11:-4])

 Return

 

Here is the relevant html (in this case I have copied the html for the 31st
of the month, but all dates look the same which is why
find_element_by_link_text [with day_to_book = 31) is easy to use. Again, my
code works fine - I am trying to see if there is a way to improve
performance with some trick I can't come up with.

 



 

 

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


Re: [Tutor] Help understanding base64 decoding

2018-09-13 Thread Ryan Smith
Hi Peter,

Thank you for the explanation! I have been banging my head around this
for almost two days. I'm still getting familiar with all of the
different encodings at play. For example the way I currently
understand things is that python supports unicode which ultimately
defaults to being encoded in UTF-8. Hence I'm guessing is  the reason
for converting strings to a bytes object in the first place. Again
thank you for the assistance!

Ryan

On Thu, Sep 13, 2018 at 2:57 AM, Peter Otten <__pete...@web.de> wrote:
> Ryan Smith wrote:
>
>> Hello All,
>>
>> I am currently working on a small utility that finds any base64
>> encoded strings in files and decodes them. I am having issue
>> understanding how the Base64 module actually works. The regular
>> expression that I am using correctly matches on the encoded strings. I
>> simply want to be able to convert the match of the encoded ascii
>> string to it's decoded ascii equivalent. For example the base64
>> encoded ascii string 'UwB5AHMAdABlAG0ALgBkAGwAbAA=' will decode to
>> 'System.dll' if I use an online base64 decoder. However I get a
>> completely different output when trying to codify this using python
>> 3.6.5:
>>
>>>>>import base64
>>>>>import binascii
>>
>>>>>test_str = 'UwB5AHMAdABlAG0ALgBkAGwAbAA='
>>>>> base64.b64decode(test_str)
>> b'S\x00y\x00s\x00t\x00e\x00m\x00.\x00d\x00l\x00l\x00'
>>
>>>>>temp = base64.b64decode(test_str)
>>>>>binascii.b2a_base64(temp)
>> b'UwB5AHMAdABlAG0ALgBkAGwAbAA=\n'
>>
>> I understand that when decoding and encoding you have to use bytes
>> objects but what I don't understand is why I can't get the proper
>> conversion of the original ascii string. Can someone please point me
>> in the right direction?
>
> Look closely at the odd bytes in
>
>> b'S\x00y\x00s\x00t\x00e\x00m\x00.\x00d\x00l\x00l\x00'
>
> or just do
>
>>>> b'S\x00y\x00s\x00t\x00e\x00m\x00.\x00d\x00l\x00l\x00'[::2]
> b'System.dll'
>
> The even bytes are all NUL:
>
>>>> b'S\x00y\x00s\x00t\x00e\x00m\x00.\x00d\x00l\x00l\x00'[1::2]
> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>
> This means that your byte string already *is* the original string, encoded
> as UTF-16. You can convert it into a string with
>
>>>> b'S\x00y\x00s\x00t\x00e\x00m\x00.\x00d\x00l\x00l\x00'.decode("utf-16")
> 'System.dll'
>
> which will handle non-ascii characters correctly, too.
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] why can use a widget assigned to a variable or just use it on it's own?

2018-07-02 Thread Chris Roy-Smith

Hi,

I'm trying to understand working with objects.

If I have grasped things correctly a widget is an object. So why can I 
assign the widget, or use it stand alone? See sample code below


=

#!/usr/bin/python3
from tkinter import *
main=Tk()

# as I understand it this will create an instance of the button widget 
called b1
b1=Button(main, text='instantce', command= lambda b='goodbye' : 
print(b)).grid(row=1, column=0)



# but here I haven't made an instance, but all seems well
Button(main, text='test1', command=lambda a='hello' 
:print(a)).grid(row=0, column=0)


main.mainloop()


===

any explanation gratefully recieved

Regards, Chris ROy-Smith

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


Re: [Tutor] how to change the command "string" on a tkinter Button?

2018-07-01 Thread Chris Roy-Smith

On 01/07/18 19:19, Steven D'Aprano wrote:

On Sun, Jul 01, 2018 at 03:32:59PM +1000, Chris Roy-Smith wrote:


Python is the first language I have
attempted since macro assembler for CP/M. Python seems to be another world.

Yes indeed, high-level languages like Python *are* a radically different
programming experience than low-level languages like assembler. The
fundamental execution and data models of the languages are *very*
different:

- assembler lives in a universe of bytes and words; there are few
   abstractions and you are dealing (very nearly) with the lowest
   level of flipping bits in hardware, or at least of moving bytes.

- Python lives in a world of big, complex abstractions like dicts
   and Unicode text and even objects as complex as "web server",
   and the fundamental operations are multiple layers away from
   moving bytes.

It's not surprising that this may require some re-adjustment of your
mental model of how to program.
those big complex bits cut down on the amount of code needed to achieve 
a given task. :-)




It appears that I broke the code I started experimenting with, to try
changing the command, and that may have added to my confusion.

"Save As..." before engaging in big changes is your friend :-)

yes, was supposed to be a quick experiment to test idea ;)


Even better would be to learn a form of VCS (version control system)
such as Mercurial (hg) or git. Depending on the text editor you are
using, it may have VCS integration available.
I don't know anything about these tools, I use Kate as my editor for my 
programming. I usually give a new number to separate versions, I'm sure 
there are better ways, I just haven't gone looking for them yet. Idle 
only looks useful for CLI stuff.


Off-topic:

I see you are a fellow Internode user, like me. Which part of Australia
are you in, and is your internet connection giving you as much grief as
mine is?
I have had little trouble with Internode over the last 13 years or so. 
The other day is the first time I had a really slow download, went to 
another mirror in Western Australia, and all went as fast as I'm 
supposed to get (I have the slowest option of NBN, ( bronze 100) which I 
have never NEEDED extra bandwidth, it might be nice, but I don't use the 
sort of service which depends on good bandwidth, downloads can go all 
night for all I care). I'm not greedy though it's all very fast compared 
to dial up, or packet radio


I'm pretty sure that Internode is *grossly* oversubscribed. E.g. when I
try doing a google search, I'll usually get "Waiting for
www.google.com..." which then times out about six or twelve times on
average before succeeding to connect, after which it is damn near
instantaneous.
I search with DuckDuckGo, and rarely have any response issue with my 
searches. I don't think they sell my search data.


I downloaded 2 GB of data in about ten minutes yesterday, not long
followed by a 2K email that took *three hours* to leave my computer
because the connection to Internode's mail server kept timing out.

Your connection is a bit faster than mine.
I've not experienced any speed issues with the email server.

Regards, Chris Roy-Smith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to change the command "string" on a tkinter Button?

2018-07-01 Thread Chris Roy-Smith

On 01/07/18 02:17, Alan Gauld via Tutor wrote:

On 30/06/18 03:55, Chris Roy-Smith wrote:


I am trying to change the command of a tkinter Button in my program.
Eventually I want to be able to do this to many buttons.

Since I'm not 100% sure if you mean the command or the label or both
here is a simple example that does both...


import tkinter as tk

def cmd1(): print('This is command 1')

def cmd2(): print('This is number 2')
I was hoping eventually to generate the command form the results of a 
database query, not knowing  the exact command until run time. Perhaps 
what I was trying to achieve is too close to self modifying code, I was 
warned off this when I used to dabble in assembler. Does the same advice 
hold for python?


def swapCmd():
 c = b1['command']
 # kluge to get the function name from Tcl id
 if str(c).endswith("cmd1"):
 b1['command'] = cmd2
 else:
 b1['command'] = cmd1
I never thought to try anything like this, I was thinking more along the 
lines for how to change the text of a Labe.l

def swapText():
 t = b1['text']
 if t == "Cool":
 b1['text'] = "Hot"
 else:
 b1['text'] = "Cool"

# make GUI
top = tk.Tk()
win = tk.Frame(top)
win.pack()
b1 = tk.Button(win,text="Cool", command=cmd1)
b1.pack()
b2 = tk.Button(win, text="Swap text", command=swapText)
b2.pack()
b3 = tk.Button(win, text="Swap cmd", command=swapCmd)
b3.pack()

top.mainloop()
###


Thank you again Alan,
While your solution works, it's not how I imagined in terms of approach. 
Eventually I wanted to change the command of a variable number of 
buttons with the actual command depending on the results of a database 
query. I am unable to see how I can manage this in your solution style ( 
predetermined commands) might be difficult to achieve ( with my limited 
programming skills ).  Your solution made me rethink what I was 
attempting to do, and found with a slightly modified database query, I 
didn't need to change the command at all. The rest of this bit of 
program I have already solved.

Now I just have to learn a lot more about classes, and objects.

again, thank you Alan.
Regards, Chris Roy-Smith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to change the command "string" on a tkinter Button?

2018-07-01 Thread Chris Roy-Smith

On 01/07/18 02:17, Alan Gauld via Tutor wrote:

On 30/06/18 03:55, Chris Roy-Smith wrote:


I am trying to change the command of a tkinter Button in my program.
Eventually I want to be able to do this to many buttons.

Since I'm not 100% sure if you mean the command or the label or both
here is a simple example that does both...


import tkinter as tk

def cmd1(): print('This is command 1')

def cmd2(): print('This is number 2')

def swapCmd():
 c = b1['command']
 # kluge to get the function name from Tcl id
 if str(c).endswith("cmd1"):
 b1['command'] = cmd2
 else:
 b1['command'] = cmd1

def swapText():
 t = b1['text']
 if t == "Cool":
 b1['text'] = "Hot"
 else:
 b1['text'] = "Cool"

# make GUI
top = tk.Tk()
win = tk.Frame(top)
win.pack()
b1 = tk.Button(win,text="Cool", command=cmd1)
b1.pack()
b2 = tk.Button(win, text="Swap text", command=swapText)
b2.pack()
b3 = tk.Button(win, text="Swap cmd", command=swapCmd)
b3.pack()

top.mainloop()
###


Thank you Alan, you have covered what I think I wanted to achieve. For 
me, programming is a continual learning experience, unfortunately I seem 
to forget nearly as much as I learn, Python is the first language I have 
attempted since macro assembler for CP/M. Python seems to be another world.


It appears that I broke the code I started experimenting with, to try  
changing the command, and that may have added to my confusion.


I'll play with your example to try an understand what is going on.

Regards, Chris Roy-Smith

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


[Tutor] how to change the command "string" on a tkinter Button?

2018-06-30 Thread Chris Roy-Smith

Hi,

OS is Linux,

Python version is 3.6.5

I am trying to change the command of a tkinter Button in my program. 
Eventually I want to be able to do this to many buttons.


My attempt at code brings up no error messages, but the button appears 
to do nothing.


I really have no idea how to do this, but this is what I wrote.



#!/usr/bin/python3
from tkinter import *

class form(object):
    def __init__(self, x, reply, master, z,bu):
    self.x=x
    self.reply=reply
    self.master=master
    self.z=z
    self.bu=bu

    def change(x, reply, z, b):
    #f contains the alternative command (as a string)
    f=["lambda x=vars, txt=reply,fu=0 bu=b1 :form.change(x, txt, 
fu, bu)", "lambda x=vars, txt=first, fu=1 bu=b1: form.change(x, txt, fu, 
bu)"]

    for i in range(4):
    x[i].set(reply[i])
    #attempt to change command clause
    set.button(f[z])

    def draw(master):
    vars = []
    label = []
    button = StringVar
    for i in range(4):
    var = StringVar()
    vars.append(var)
    label.append("")
    label[i] = Label( master, textvariable=var, relief=RAISED 
).grid(row=i, column=0)

    vars[i].set(first[i])
    b1=Button(master, text="change", command=button).grid(row=i+1, 
column=0)



reply=["now I don't know", "Happy birthday", "Many happy returns", "Next 
it's my turn",1]
first=["What's your name?", "My name is Fred", "I have just had my 
birthday", "your's is next!",2]

master=Tk()

form.draw(master)
master.mainloop()

=

How should I do this, I had worked around the problem by destroying  the 
window and building it again, but it was pointed out that I have an 
unusual coding style doing this.


All hints appreciated!

Regards, Chris Roy-Smith

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


Re: [Tutor] tkinter code executes before function returned

2018-04-16 Thread Chris Roy-Smith

On 15/04/18 18:10, Alan Gauld via Tutor wrote:

On 15/04/18 03:57, Chris Roy-Smith wrote:


I am trying to get tkinter to return a number from a window, which then
sets how many times to print a sign.

I don;t jhave time to look at this in detail just now, maybe later.

But first impressions is that you have a very unorthodox style of
Tkinter programming. Its more traditional to build the entire GUI
up front rather than creating and destroying widgets each time you
execute an event handler. Its less disturbing to the user than
having things appear/disappear etc, as you seem to be doing.

You can make widget hide/show/deactivate themselves without
destroying them just by withdrawing/unpacking them etc or
changing their status, if that's really what you want to do.


The code does not wait till the function returns a value, resulting in
the signcount variable in having a None value, giving an output like
below.

I'll look at this a bit more closely later if nobody else
answers by then...

This is where you call your function. Looking at it quickly
I think you would be as well using the standard Tkinter
simpledialogs/messagebox modules to get user input.
Have you looked at the simpledialogs?
Thank you Alan, I didn't know of simpledialogs. That was all I needed to 
search documentation for these. I have


now achieved what I was trying to do, with user interface as I was planning.



Or better still having a static entry field on your GUI
and just reading that?


I'll have to figure out how to achieve that!

Perhaps my intended design is not in line with modern styles?


Regards, Chris Roy-Smith

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


Re: [Tutor] tkinter code executes before function returned

2018-04-15 Thread Chris Roy-Smith

On 15/04/18 23:36, Alan Gauld via Tutor wrote:

On 15/04/18 14:24, Alan Gauld via Tutor wrote:


OK, I've had a closet look now and can confirm the

A closer look! Not a closet look. Ooops! :-/


Thank you Alan, I have even more to learn than I thought. I have been 
bashing away at several OOP tutorials, but the penny still hasn't 
dropped on making that work yet, I get the concept, but don't seem to 
understand how to make it work for methods. Events just add to my lack 
of understanding. I'll have to try your tutorial. Hopefully I won't have 
too many questions after that.


Regards, Chris Roy-Smith

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


[Tutor] tkinter code executes before function returned

2018-04-15 Thread Chris Roy-Smith

Hi,

System: Python 3.6, Ubuntu Linux 17.10

I am trying to get tkinter to return a number from a window, which then 
sets how many times to print a sign.


The code does not wait till the function returns a value, resulting in 
the signcount variable in having a None value, giving an output like 
below. Note that the output "line 64 ###   The required number of signs 
is 5   ###" only occurs after a number is input.


I can use an input statement to get the desired output, but that's not 
good having to go to the terminal to enter the response. How can I get 
the printSign code to wait till getcount() returns it's value?


Any help greatly appreciated.

Regards, Chris Roy-Smith

chris@chris-X451MA:~/Scripts/python3/dvms$ ./debug1.py
line 27 ###   required sign count for D is None   ###
Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.6/tkinter/__init__.py", line 1702, in __call__
    return self.func(*args)
  File "./debug1.py", line 28, in printSign
    for x in range(signcount):
TypeError: 'NoneType' object cannot be interpreted as an integer
line 64 ###   The required number of signs is 5   ###


Code:

#!/usr/bin/python3
from tkinter import *
import os
from reportlab.lib.units import cm
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas
from reportlab.lib.utils import ImageReader

def printSign():
    global gc, packages, rows
    myCanvas = canvas.Canvas("Signs.pdf", pagesize=A4)
    width, height = A4 #keep for
    myCanvas.rotate(90)
    myCanvas.setFillColorRGB(0,0,0)
    myCanvas.setFont("Helvetica-Bold", 400)
    TopMargin=-20
    LeftMargin=1
    Width=14
    Height=19
    VertPos=-15
    Bottom=-1
    a=[" " for i in range(rows)]
    i=0
    sign=0
    for line in packages:
    signcount=getcount(line[1])
    print('line 27 ###   required sign count for {} is {} 
###'.format(line[1], str(signcount)))

    for x in range(signcount):
    #draw rectangle
    myCanvas.rect(LeftMargin*cm+Width*sign*cm, TopMargin*cm, 
Width*cm, Height*cm, stroke=0, fill=1)
myCanvas.drawCentredString((LeftMargin+(0.5*Width))*cm+(Width*sign)*cm, 
VertPos*cm, line[0])

    if sign==1:
    myCanvas.showPage()
    sign=0
    myCanvas.rotate(90)
    i+=1
    else:
    sign+=1
    i+=1

    myCanvas.showPage()
    myCanvas.save()
    if os.name == "posix":
    os.popen("evince %s" % ("Signs.pdf"))
    if os.name == "nt":
    os.startfile('Signs.pdf')

def getcount(SignText):
    global gc,e
    gc=Toplevel(master)
    MsgText='How many copies of {} do you want to print?'.format(SignText)
    Label(gc, text=MsgText).grid(row=0, column=0, sticky=(W,E))
    e = Entry(gc)
    e.grid(row=0, column=1)
    Button(gc, text='Okay', command=ReturnCount).grid(row=1, column=0, 
sticky=(W,E))
    Button(gc, text='Cancel', command=gc.destroy).grid(row=1, column=1, 
sticky=(W,E))


def ReturnCount():
    global gc,e
    b0=e.get()
    if b0 == None:
    b0=0
    gc.destroy()
    print('line 64 ###   The required number of signs is {} 
###'.format(b0))

    return b0

master = Tk()
master.title("Testing")
packages = [[0,'D','drill'],[1,'J','Jointer'],[2,'B','Bandsaw']]
rows = 3
b2 = Button(master, text="Print Signs", command=printSign).grid(row=4, 
column=0, sticky=(W,E), padx=5, pady=5)
b3 = Button(master, text="Quit", command=master.destroy).grid(row=4, 
column=3, sticky=(W,E))


master.mainloop()

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


[Tutor] thinter: can't figure out how to update a window instead of creating a new on

2018-01-28 Thread Chris Roy-Smith

Hi,

system: Python 3.6, LInux

I have been playing around with the following code which I want to 
update the window, but I creates a new window (with the correct 
display), but I have not been able to find the solution. Perhaps I'm 
using the wrong key words in my searches.


Thank you for any assistance, I'm hoping to learn something from this 
experience


Regards, Chris Roy-Smith

#!/usr/bin/python3

import mysql.connector
from tkinter import *
import pickle
master = Tk()

def getCfg():
    fobj = open('members.pkl', 'rb')
    cfg = pickle.load(fobj)
    fobj.close()
    return cfg


def editmember(page=1):
    form=Toplevel(master)
    form.title('test form')
    cfg=getCfg()
    QrySelectMembers='select ident, concat_ws(" " ,`given`, `surname`) 
as `fullname` from `details` where 1 order by `surname` asc, `given` asc 
limit '+str(page)+', 10'
    db=mysql.connector.connect(user = cfg['user'], password = 
cfg['password'], database = cfg['database'])

    cursor=db.cursor()
    cursor.execute(QrySelectMembers) #,(page))
    MemberList=list(cursor)
    cursor.close()
    db.close
    ro=0
    for Member in MemberList:
    ident=Member[0]
    msg='edit '+Member[1]
    Button(form, text=msg, command= lambda tmp=ident : 
EdForm(tmp)).grid(sticky=(W, E), row=ro, column=0)

    ro+=1
    Button(form, text='exit', command=form.destroy).grid(row=ro+1, 
column=2)
    Button(form, text='next 10', command= lambda p=page+10 : 
editmember(p)).grid(row=ro, column=1)
    Button(form, text="previous 10", command= lambda p=page-10 : 
editmember(p)).grid(row=ro, column=0)



Button(master, text='click to test', command=editmember).grid(row=0, 
column=0)

Button(master, text='quit', command=master.destroy).grid(row=1, column=0)
master.mainloop()

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


[Tutor] Fwd: print a for loop system call

2018-01-20 Thread Derek Smith


Sent from my iPhone

Begin forwarded message:

From: Derek Smith 
<dereksm...@racksquared.com<mailto:dereksm...@racksquared.com>>
Date: January 19, 2018 at 4:01:58 PM EST
To: "tutor-requ...@python.org<mailto:tutor-requ...@python.org>" 
<tutor-requ...@python.org<mailto:tutor-requ...@python.org>>
Subject: print a for loop system call

Why does A work but B does not?


#!/usr/bin/env python3

import os
import sys
from subprocess import Popen, PIPE

pipe = Popen('lsdev -c tape', shell=True, stdout=PIPE)

for dev in pipe.stdout :
print ( dev.strip().split()[0].decode() )## A ##
# print ( dev.strip().split().decode()[0] ) ## B ##


And if I try to store in an array using

rmts = [ dev.strip().split()[0].decode() ]

it only stores the last line when there are over 100 lines.

Sample line looks like

rmt144 Available 04-T1-01 LTO Ultrium Tape Drive (FCP)

thank you!

Derek Smith  |  Unix/TSM Administrator  | Racksquared Data Centers
':  614-437-4983 * 325 East Spring Street, Columbus, OH 43215
::  dereksm...@racksquared.com<mailto:dereksm...@racksquared.com>  *: 
www.racksquared.com<http://www.racksquared.com/> |  
www.racksquared.jobs<http://www.racksquared.jobs/>

[cid:image003.png@01D2E9AA.1B9CF8F0]

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


Re: [Tutor] trouble using tkinter CheckButton

2018-01-16 Thread Chris Roy-Smith

On 16/01/18 22:35, Alan Gauld via Tutor wrote:

On 16/01/18 04:37, Chris Roy-Smith wrote:


    File "./debugString.py", line 7, in SetFin
      SetStatus[x] = var.get(x)
AttributeError: 'list' object has no attribute 'get'
var=[IntVar() for x in range(8)]

Here you create a list of IntVar objects.
The list has no get() method - just as the error message says.
You need to access the individual IntVar for your widget.

I suspect you want

   SetStatus[x] = var[x].get()

Yes, Thank you, that was the problem. other problems in my code, after 
correcting the get() were easy to sort out.


Regards, Chris Roy-Smith

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


[Tutor] trouble using tkinter CheckButton

2018-01-16 Thread Chris Roy-Smith

Hi,

I'm a relative newcomer to object oriented programming.

Operating system Linux (ubuntu 17.10)

Python version 3.6

With the code below, when I click on the "list set & unset" button I get 
the following error. This code is my attempt at debugging a bigger 
program. I have broken things down to what I think is as simple as I can 
get.


Thank you for looking at this,

Regards, Chris Roy-Smith


Error message:

=

chris@chris-X451MA:~/Scripts/python3/dvms$ ./debugString.py
Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.6/tkinter/__init__.py", line 1702, in __call__
    return self.func(*args)
  File "./debugString.py", line 26, in 
    Button(cmember, text='list set & unset',command= lambda lines = x : 
SetFin(lines) ).grid(row=x, column=2)

  File "./debugString.py", line 7, in SetFin
    SetStatus[x] = var.get(x)
AttributeError: 'list' object has no attribute 'get'



#!/usr/bin/python3
from tkinter import *

def SetFin(lines):
    SetStatus=[" " for i in range(lines)]
    for x in range(lines):
    SetStatus[x] = var.get(x)
    print (SetStatus(x))

master = Tk()


NameList=[(1, 'Vivian', 'Blackwell'), (2, 'Peter ', 'Bromell'), (3, 
'Nev', 'Casey'), (4, 'Claude', 'Chatwin'), (5, 'John ', 'Dennison'), (6, 
'Nicolene', 'Fairbrass'), (7, 'Paul', 'Fairbrass')] #in real situation 
this comes from a database and is of variable length

cmember=Toplevel(master)
x=0
y=0
var=[IntVar() for x in range(8)]
for line in NameList:
    for field in line:
    Label(cmember, text=field).grid(row=x, column=y)
    y+=1
    #make checkbox
    cb=Checkbutton(cmember, text='set', variable=var[x]).grid(row=x, 
column=y)

    y=0
    x+=1
Button(cmember, text='list set & unset',command= lambda lines = x : 
SetFin(lines) ).grid(row=x, column=2)

Button(cmember, text='exit', command=cmember.destroy).grid(row=x, column=4)

mainloop()

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


[Tutor] get javascript output data from ssi file

2017-11-27 Thread Derek Smith







 
Destination


Element
Volume Serial
  


  


   Element
  Volume Serial
  
  
  

   
  
  
  



 Drive 4 (1)
   
  
  

I/O Station 1
  
 


I/O Station 2
  
 
  

I/O Station 3
  
 


Slot 9 (1)
  
 
  

Slot 20 (1)
  
 


Slot 23 (1)
  
 
  

Slot 30 (1)
  
 


Slot 31 (1)
  
 
  

Slot 32 (1)
  
 


Slot 35 (1)
  
 
  

Slot 36 (1)
  
 


Slot 37 (1)
  
 
  

Slot 40 (1)
  
 


Slot 41 (1)
  
 
  

Slot 44 (1)
  
 
  
  
  
  




Derek Smith  |  Unix/TSM Administrator  | Racksquared Data Centers
':  614-437-4983 * 325 East Spring Street, Columbus, OH 43215
::  dereksm...@racksquared.com  *: 
www.racksquared.com<http://www.racksquared.com/> |  
www.racksquared.jobs<http://www.racksquared.jobs/>

[cid:image003.png@01D2E9AA.1B9CF8F0]

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


Re: [Tutor] problems using a listbox

2017-10-17 Thread Chris Roy-Smith

On 17/10/17 20:13, Peter Otten wrote:

#!/usr/bin/python3
#test listbox
from tkinter import *

class Dialog(Frame):

  def __init__(self, master):
  Frame.__init__(self, master)
  self.list = Listbox(self, selectmode=EXTENDED)
  self.list.pack(fill=BOTH, expand=1)
  self.current = None
  self.poll() # start polling the list

  def poll(self):
  now = self.list.curselection()
  if now != self.current:
  self.list_has_changed(now)
  self.current = now
  self.after(250, self.poll)

  def list_has_changed(self, selection):
  print ("selection is", selection)


snames=('fred', 'george', 'manuel', 'john', 'eric', 'terry')
master = Tk()

dialog = Dialog(master)
dialog.pack()

for item in snames:
  dialog.list.insert(END, item)

mainloop()


Thank you, that works, I have difficulties with object oriented coding. 
Never used a language where I needed it.


Regards, Chris Roy-Smith

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


[Tutor] problems using a listbox

2017-10-17 Thread Chris Roy-Smith

Hi,

OS: Linux Chris-X451MA 4.4.0-97-generic #120-Ubuntu SMP Tue Sep 19 
17:28:18 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux


Python 3.5.2 (default, Sep 14 2017, 22:51:06)

I am trying to learn how to use a tkinter listbox. When I execute my 
experimental code, an odd index is printed immediately (output below 
code), index looks wrong (shouldn’t it be an integer). Also it doesn't 
print new values when I select an entry.


---

#!/usr/bin/python3
#test listbox
from tkinter import *

class Dialog(Frame):

    def __init__(self, master):
    Frame.__init__(self, master)
    self.list = Listbox(self, selectmode=EXTENDED)
    self.list.pack(fill=BOTH, expand=1)
    self.current = None
    self.poll() # start polling the list

    def poll(self):
    now = self.list.curselection()
    if now != self.current:
    self.list_has_changed(now)
    self.current = now
    self.after(250, self.poll)

    def list_has_changed(self, selection):
    print ("selection is", selection)


snames=('fred', 'george', 'manuel', 'john', 'eric', 'terry')
master = Tk()

listbox = Listbox(master)
listbox.grid(row=0)

for item in snames:
    listbox.insert(END, item)

myindicator=Dialog.list_has_changed(master, listbox)

mainloop()

-

output:

---

./listbox.py

selection is .140537834621024

Thank you for any help

Regards, Chris Roy-Smith


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


[Tutor] subprocess check_output

2017-09-20 Thread Derek Smith
Why does python output this b and newline characters and how can I may it 
return just what I need, the number 8 w/no special characters? See below. I 
tried str(scratch), but no go, still prints that garbage.


#!/bin/env python3

cmdstr= "/usr/bin/dsmadmc"
id  = "-id=dereksmith"
pw   = "-password="
do= "-dataonly=yes"


from subprocess import check_output
scratch = check_output( [ cmdstr, id, pw, do, "select", "count(*)", "from", 
"libvolumes", "where", "status='Scratch'", "and", "library_name='TS3200'" ] )
print (scratch)

__OUTPUT__
# ./ts3200_scratchcount_check.py
email sent successfully
b'   8\n'


Thx!!
Derek Smith  |  Unix/TSM Administrator  | Racksquared Data Centers
::  dereksm...@racksquared.com  *: 
www.racksquared.com<http://www.racksquared.com/> |  
www.racksquared.jobs<http://www.racksquared.jobs/>

[cid:image003.png@01D2E9AA.1B9CF8F0]

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


[Tutor] pip install of subprocess module

2017-09-18 Thread Derek Smith
Hi All,

Thank for the recent replies.  I want to use the subprocess.run module b/c per 
the docs os.system is antiquated and cannot use  more than 1 arg in 3.6.
Why am I doing wrong below?  Also couldn't I just copy and paste the subprocess 
code from github and create a file, but then how do I tell python this is a new 
module called os.system since this py file requires os.system and os.spawn*
I am on AIX 7.1, python 3.6.2, pip 9.0.1

Thx agn!

# pip install git+https://github.com/python/cpython/blob/3.6/Lib/subprocess.py 
-vvv
Collecting git+https://github.com/python/cpython/blob/3.6/Lib/subprocess.py
  Cloning https://github.com/python/cpython/blob/3.6/Lib/subprocess.py to 
/tmp/pip-bw8rryo9-build
  Running command git clone -q 
https://github.com/python/cpython/blob/3.6/Lib/subprocess.py 
/tmp/pip-bw8rryo9-build
remote: Not Found
fatal: repository 
'https://github.com/python/cpython/blob/3.6/Lib/subprocess.py/' not found
Cleaning up...
Command "git clone -q 
https://github.com/python/cpython/blob/3.6/Lib/subprocess.py 
/tmp/pip-bw8rryo9-build" failed with error code 128 in None
Exception information:
Traceback (most recent call last):
  File "/opt/freeware/lib/python3.6/site-packages/pip/basecommand.py", line 
215, in main
status = self.run(options, args)
  File "/opt/freeware/lib/python3.6/site-packages/pip/commands/install.py", 
line 335, in run
wb.build(autobuilding=True)
  File "/opt/freeware/lib/python3.6/site-packages/pip/wheel.py", line 749, in 
build
self.requirement_set.prepare_files(self.finder)
  File "/opt/freeware/lib/python3.6/site-packages/pip/req/req_set.py", line 
380, in prepare_files
ignore_dependencies=self.ignore_dependencies))
  File "/opt/freeware/lib/python3.6/site-packages/pip/req/req_set.py", line 
620, in _prepare_file
session=self.session, hashes=hashes)
  File "/opt/freeware/lib/python3.6/site-packages/pip/download.py", line 805, 
in unpack_url
unpack_vcs_link(link, location)
  File "/opt/freeware/lib/python3.6/site-packages/pip/download.py", line 479, 
in unpack_vcs_link
vcs_backend.unpack(location)
  File "/opt/freeware/lib/python3.6/site-packages/pip/vcs/__init__.py", line 
286, in unpack
self.obtain(location)
  File "/opt/freeware/lib/python3.6/site-packages/pip/vcs/git.py", line 142, in 
obtain
self.run_command(['clone', '-q', url, dest])
  File "/opt/freeware/lib/python3.6/site-packages/pip/vcs/__init__.py", line 
325, in run_command
spinner)
  File "/opt/freeware/lib/python3.6/site-packages/pip/utils/__init__.py", line 
707, in call_subprocess
% (command_desc, proc.returncode, cwd))
pip.exceptions.InstallationError: Command "git clone -q 
https://github.com/python/cpython/blob/3.6/Lib/subprocess.py 
/tmp/pip-bw8rryo9-build" failed with error code 128 in None



Derek Smith  |  Unix/TSM Administrator  | Racksquared Data Centers
::  dereksm...@racksquared.com  *: 
www.racksquared.com<http://www.racksquared.com/> |  
www.racksquared.jobs<http://www.racksquared.jobs/>

[cid:image003.png@01D2E9AA.1B9CF8F0]

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


[Tutor] array input from keyboard

2017-09-15 Thread Derek Smith
I need to accept input from the user then store in an array/list.  This is my 
1st python script.

#!/usr/bin/env python
# Derek Smith
# 09/2017
# accept volumes for TSM for tape mgmt.

import os
import sys

nput1 = ""
nput2 = ""
nput1 = input("\nIs your input 'file' based or 'cli' based? ")

if nput1 == "file" :
nput2 = input("Please provide your input file? ")
nput2 = nput2.lower()
print (nput2)
fh = open(nput2,"r")

for ln in fh:
ln = ln.rstrip()
os.system("/usr/bin/dsmadmc -id=dereksmith -password=x -dataonly=yes 
move drm %s" %ln, "tost=onsiter")
os.system("/usr/bin/dsmadmc -id=dereksmith -password=x -dataonly=yes 
move drm %s" %ln, "wherest=vaultr tost=onsiter")

elif nput1 == "cli" :
vols = []
vols = input("Please enter your volume ids, comma delimited? ")
vols = vols.upper()
for vols in vols :
vols = vols.rstrip()
print("/usr/bin/dsmadmc -id=dereksmith -password=dereksmith 
-dataonly=yes move drm %s" %vols, "tost=onsiter")
elif
print ("Incorrect input, exiting.")
sys.exit(99)


__OUTPUT__

# python tsm_moveVR_tonsiter.py

Is your input 'file' based or 'cli' based? cli
Please enter your volume ids, comma delimited? r20344l5,r20355l5
/usr/bin/dsmadmc -id=dereksmith -password=x -dataonly=yes move drm R 
tost=onsiter
/usr/bin/dsmadmc -id=dereksmith -password=x -dataonly=yes move drm 2 
tost=onsiter
/usr/bin/dsmadmc -id=dereksmith -password=x -dataonly=yes move drm 0 
tost=onsiter
/usr/bin/dsmadmc -id=dereksmith -password=x -dataonly=yes move drm 3 
tost=onsiter
/usr/bin/dsmadmc -id=dereksmith -password=x -dataonly=yes move drm 4 tost=onsite
...
...
...

Its printing each element per line.  I have tried various changes, read online 
help but gave up looking.
I need it to print as below:


/usr/bin/dsmadmc -id=dereksmith -password=x -dataonly=yes move drm R20344L5 
tost=onsiter
/usr/bin/dsmadmc -id=dereksmith -password=x -dataonly=yes move drm R20355L5 
tost=onsiter

Thank you!!
Derek Smith  |  Unix/TSM Administrator  | Racksquared Data Centers
::  dereksm...@racksquared.com  *: 
www.racksquared.com<http://www.racksquared.com/> |  
www.racksquared.jobs<http://www.racksquared.jobs/>

[cid:image003.png@01D2E9AA.1B9CF8F0]

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


[Tutor] intro book for python

2017-09-01 Thread Derek Smith

Hello!

I am new to python coming from a Perl and Unix Admin background.  I reviewed 
the site https://wiki.python.org/moin/IntroductoryBooks and would like to know 
which book(s) you all recommended for a newbie?

Thank you!

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


[Tutor] Python Questions

2017-07-18 Thread Max Smith
I have some questions about python.



What's the easiest way to learn python currently I'm using google's excersise 
program, I'm just reading and making notes then testing out what I have learnt. 
Since I' need to understand python fully as I've got a exam in Python for my 
GCSE's if you could give me some tips. I'd be excited to hear.



Thanks very Much,

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


Re: [Tutor] Coming from R, what's a good IDE editor? I've tried PyCharm and Spyder

2017-06-05 Thread Ryan Smith
+1 for Wing IDE. I have been using it for about 6-7 months now and
absolutely love it.

Ryan
On Sun, Jun 4, 2017 at 11:37 AM Ryan Smith <r...@allwegot.net> wrote:

>
> On Sun, Jun 4, 2017 at 8:13 AM wolfrage8...@gmail.com <
> wolfrage8...@gmail.com> wrote:
>
>> Atom.io Editor is my current favorite after having swapped around a lot.
>>
>> http://www.marinamele.com/install-and-configure-atom-editor-for-python
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] feedback on simple python code

2017-03-02 Thread Ryan Smith
On 2/28/17, 3:32 AM, "Tutor on behalf of Peter Otten"
<tutor-bounces+ryan=allwegot@python.org on behalf of __pete...@web.de>
wrote:

>Ryan Smith wrote:
>
>> Hi all,
>> 
>> New python student here. I have been using O¹reilly¹s "Python Beyond the
>> Basics: Object Oriented Programming video series". In one of the
>> assignments we are to write a simple inheritance hierarchy of three
>> classes that write to text files. I have actually written the code for
>>the
>> assignment and it runs as well as meets the requirements of the
>> assignment. I am posting to get feedback on how I can improve this and
>> making it more pythonic and concise.
>> 
>> Please keep in mind that I am simply ³simulating" writing to a log file
>> and a tabbed delimited file, so I¹m not necessarily looking for which
>> modules I could have to create actual log files or writing to actual csv
>> files. The output of the code should be two text files with text written
>> to them that have been passed to the instance of each respective object.
>> 
>> #!/usr/bin/env python
>> 
>> import abc
>> import datetime
>> 
>> class WriteFile(object):
>> __metaclass__ = abc.ABCMeta
>> 
>> 
>> @abc.abstractmethod
>> def write(self,text):
>
>You might run a tool like https://pypi.python.org/pypi/pycodestyle over
>your 
>code to ensure it follows common standards.
>
>> """Write to file"""
>> return
>> 
>> 
>> class LogFile(WriteFile):
>> def __init__(self,fh):
>> self.fh = fh
>> 
>> 
>> def write(self, text):
>> date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
>> entry = "{0} {1}{2}".format(date, text, '\n')
>> with open(self.fh, 'a') as f:
>> f.write(entry)
>> 
>> class DelimWrite(WriteFile):
>> def __init__(self, fh, delim):
>> self.fh = fh
>> self.delim = delim
>> 
>> 
>> def write(self, text):
>> with open(self.fh, 'a') as f:
>> entry = ""
>> for item in text:
>> if self.delim in item:
>> entry += ' "{0}"{1} '.format(item,self.delim)
>
>What will happen if text contains double quotes?
>
>> else:
>> entry += item+self.delim
>
>Have a look at the str.join() method. Example:
>
>>>> ",".join(["foo", "bar", "baz"])
>'foo,bar,baz'
>
>> f.write(entry.strip(self.delim) + '\n')
>
>I will mention another "principle", DRY (don't repeat yourself), i. e. do
>not write the same code twice.
>
>When I look at your code I see that both DelimWrite and LogFile open a
>file. 
>If you want modify your code to accept file objects like sys.stdout you
>have 
>to make changes in both subclasses. To avoid that you might put the file-
>writing part into a separate method:
>
>class WriteFile(object):
>def __init__(self, file):
>self.file = file
>
>def write_record(self, record):
>with open(self.file, "a") as f:
>f.write(self.format_record(record))
>
>def format_record(self, record):
>return record
>
>
>class LogFile(WriteFile):
>def format_record(self, record):
>date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
>return "{0} {1}\n".format(date, record)
>
>
>class DelimWrite(WriteFile):
>quote = '"'
>def __init__(self, file, delimiter):
>super(DelimWrite, self).__init__(file)
>self.delimiter = delimiter
>
>def escaped(self, value):
>value = str(value)
>if self.delimiter in value:
>quote = self.quote
>value = '"{}"'.format(value.replace(quote, quote + quote))
>return value
>
>def format_record(self, record):
>escaped_rows = (self.escaped(value) for value in record)
>return self.delimiter.join(escaped_rows) + "\n"
>
>
>___
>Tutor maillist  -  Tutor@python.org
>To unsubscribe or change subscription options:
>https://mail.python.org/mailman/listinfo/tutor
>

Danny/Peter,

Thank you to both of you for your feedback.

Peter,

I will definitely be adding pycodestyle to my toolkit. You made a good
point about creating a separate method for file writing so that both the
DelimWrite and the LogFile classes can use them. Also looking at my code I
see where my code does repeat with the write() method. I guess I’m still
trying to understand polymorphism because that’s what I was aiming for
when I wrote the code.

Danny,

Thank you for the link you provided on Liskov’s principals. To be honest I
started reading what you shared and realize it’s gonna take a little time
to digest it so that I can apply the principals in future code. I’m sure I
will have more questions, but I will just start a separate thread.

Again thank you both,

Ryan

 


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


[Tutor] feedback on simple python code

2017-02-27 Thread Ryan Smith
Hi all,

New python student here. I have been using O¹reilly¹s "Python Beyond the
Basics: Object Oriented Programming video series". In one of the
assignments we are to write a simple inheritance hierarchy of three
classes that write to text files. I have actually written the code for the
assignment and it runs as well as meets the requirements of the
assignment. I am posting to get feedback on how I can improve this and
making it more pythonic and concise.

Please keep in mind that I am simply ³simulating" writing to a log file
and a tabbed delimited file, so I¹m not necessarily looking for which
modules I could have to create actual log files or writing to actual csv
files. The output of the code should be two text files with text written
to them that have been passed to the instance of each respective object.

#!/usr/bin/env python

import abc
import datetime

class WriteFile(object):
__metaclass__ = abc.ABCMeta


@abc.abstractmethod
def write(self,text):
"""Write to file"""
return 


class LogFile(WriteFile):
def __init__(self,fh):
self.fh = fh


def write(self, text):
date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
entry = "{0} {1}{2}".format(date, text, '\n')
with open(self.fh, 'a') as f:
f.write(entry)

class DelimWrite(WriteFile):
def __init__(self, fh, delim):
self.fh = fh
self.delim = delim


def write(self, text):
with open(self.fh, 'a') as f:
entry = ""
for item in text:
if self.delim in item:
entry += ' "{0}"{1} '.format(item,self.delim)
else:
entry += item+self.delim
f.write(entry.strip(self.delim) + '\n')




if __name__ == "__main__":


log = LogFile('log.txt')
log.write('This is a log message')
log.write('This is another log message')


d = DelimWrite('test.csv',',')
d.write([Œ1¹,¹2¹,¹3¹])
d.write(['a','this, that','c¹])#Double quote item if delimiter
included as list item
d.write([Œbasketball¹,'football¹,'golfball'])




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


Re: [Tutor] Need help

2016-10-13 Thread Ryan Smith
On Wednesday, October 12, 2016, Alan Gauld via Tutor 
wrote:

> On 12/10/16 09:03, niraj pandey wrote:
>
> > Can you pls guide how to print this screen (Attached here) content in
> > printer ?
>
> As we already pointed out this is a text list so attachments
> are usually stripped off...
>
> However, printing from Tkinter is not easy. The simplest way is usually
> to create an HTML file and use the OS to print that via a browser (many
> browsers have a print command line option). It is possible to convert
> your screen into a graphics file and print that, but the results can be
> a bit unpredictable.
>
> Alan G.
>
> ___
> Tutor maillist  -  Tutor@python.org 
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] is there a better way to do this?

2016-05-10 Thread Chris Roy-Smith

On 10/05/16 07:03, Ondřej Rusek wrote:

Dne 9.5.2016 v 10:13 Chris Roy-Smith napsal(a):

Hi
Python 3.4 Linux (ubuntu)

This code does what I want.
curs is the result of a mysql query


data = [[" " for x in range(9)] for y in range(count)]
for (ddate, mood, walk, lag, sleep) in curs:
data[row][0]=ddate
data[row][1]=mood
data[row][2]=walk
data[row][3]=lag
data[row][4]=sleep
row +=1


if you want 'lists in list' (like your solution):

data = []
for ddate, mood, walk, lag, sleep in curs:
data += [ [ddate, mood, walk, lag, sleep] ]

or 'tuples in list':

data = []
for ddate, mood, walk, lag, sleep in curs:
  data += [ (ddate, mood, walk, lag, sleep) ]

but for 'tuples in list'... simple:

data = []
for record in curs:
  data += [record]



Thanks,
I hadn't considered having a second list of lists for my calculations,
Your solution is the sort of thing I was looking for.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] is there a better way to do this?

2016-05-10 Thread Chris Roy-Smith

On 10/05/16 12:01, Steven D'Aprano wrote:

On Mon, May 09, 2016 at 06:13:32PM +1000, Chris Roy-Smith wrote:


data = [[" " for x in range(9)] for y in range(count)]
for (ddate, mood, walk, lag, sleep) in curs:
 data[row][0]=ddate
 data[row][1]=mood
 data[row][2]=walk
 data[row][3]=lag
 data[row][4]=sleep
 row +=1

While I don't know a better way to do this, it seems a bit awkward, is
there a better way?

Hmmm, it's hard to be sure because we don't really know what count is.
Do you want a bunch of empty rows at the end? My guess is No.

In your code above, you initialise each row with ten spaces, and only
replace five of them. So assuming you need the extra five spaces:

data = [record + [" "]*5 for record in curs]

provided curs returns lists, rather than tuples. (If not, it's
easy to just convert using `list(record)`.

If you don't need the extra five columns, the code is even simpler:

data = list(curs)

Thank you,
that's much better
I thought I needed the extra columns, but I changed things to use 2 
lists of lists
(one generated with the above line and another to hold my calculated 
results)




What if you do want extra blank rows? Easiest to just add them at the
end:

# initialise data as above, then add blanks
for i in range(how_many_extra_rows):
 data.append([" "]*10)

which can be simplified to:

data.extend([[" "]*10 for i in range(how_many_extra_rows)])





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


[Tutor] is there a better way to do this?

2016-05-09 Thread Chris Roy-Smith

Hi
Python 3.4 Linux (ubuntu)

This code does what I want.
curs is the result of a mysql query


data = [[" " for x in range(9)] for y in range(count)]
for (ddate, mood, walk, lag, sleep) in curs:
data[row][0]=ddate
data[row][1]=mood
data[row][2]=walk
data[row][3]=lag
data[row][4]=sleep
row +=1


While I don't know a better way to do this, it seems a bit awkward, is 
there a better way?



Thank you
Chris Roy-Smith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Python "password" securely hashed in script

2016-04-27 Thread Paul Smith
So creating small programs that automate my day specifically logins, how
can one "hash" or hide the user and pass items in the python script itself?
I need to prevent someone from easily seeing or accessing these if they
happen to gain access to my python files. Thanks in advance.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why define a function inside a function?

2016-01-30 Thread Ryan Smith
Thank you to both you and Ben for taking the time and answering my
question! The detailed explanation of the example code I provided
really helped and made things clear. As did the explanations about
closures and a simplified example. I definitely have a lot to learn,
but this was very educational nonetheless.





On Fri, Jan 29, 2016 at 10:38 PM, Steven D'Aprano  wrote:
> Oops, I screwed up!
>
>
> On Sat, Jan 30, 2016 at 02:31:09PM +1100, Steven D'Aprano wrote:
>
>> Complicated? Well, a bit. Here's a simpler demonstration of a closure:
>>
>>
>> def factory(num):
>> """Factory function that returns a new function that adds
>> num to whatever it is given."""
>> def adder(x):
>> return x + num
>
>
> Of course that can't work, because I forgot to return the inner
> function.
>
> def factory(num):
> def adder(x):
> return x + num
> return adder
>
>
> will work better. Sorry for any confusion.
>
>
>
> --
> Steve
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Why define a function inside a function?

2016-01-29 Thread Ryan Smith
Hi all,

I am new to programming and python and had a question. I hope I
articulate this well enough so here it goes... I was following along
on a thread on this mailing list discussing how to test file I/O
operations. In one of the suggested solutions the following code was
used:


def _open_as_stringio(self, filename):
filelike = StringIO(self.filecontents[filename])
real_close = filelike.close
def wrapped_close():
self.filecontents[filename] = filelike.getvalue()
real_close()
filelike.close = wrapped_close
return filelike

In trying to understand the logic behind the code for my own
edification, I was wondering what is the reasoning of defining a
function in side another function (for lack of a better phrase)?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why does this function execute before being called?

2015-11-07 Thread Chris Roy-Smith

On 07/11/15 20:18, Alan Gauld wrote:

On 07/11/15 04:34, Chris Roy-Smith wrote:


def genF(ofield): ...
 for x in range(10):



def second():
 main=Toplevel(root)
 ofield=Text(main, height=15, width=15)
 ofield.pack()
 B3=Button(main, text='exit', command=main.destroy)
 B3.pack()
 B4=Button(main, text='fill text', command=genF(ofield))


You call a function by sup[plying the parens after its name.
So the function gets called here. The normal way to circumvent
that in Tkinter is to use a lambda expression to defer execution,
like so:

B4=Button(main, text='fill text', command=lambda wgt=ofield : genF(wgt))


This certainly wasn't obvious from what I could find on the internet. 
Now I see an application for Lambda



 B4.pack()
 main.mainloop()


I'm not sure you need the second mainloop. I think the
root level mainloop will work for your window too.


Just tried out leaving this second mainloop, and every works the same. I 
had assumed I needed to create a loop the same as the top window.


Thanks for clearing up this mystery

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


[Tutor] Why does this function execute before being called?

2015-11-07 Thread Chris Roy-Smith

Hi,
Environment:
Python 2.7
Linux (Ubuntu 15.10)

I am experiencing a problem with the code below running the "genF" 
function on opening the second window. I expected that function to be 
executed on clicking the 'fill text' button. The text widget gets filled 
on opening the window. This is my first attempt at opening a second 
window, so I expect I have done something stupid.



#! /usr/bin/python
from Tkinter import *

root=Tk()


def genF(ofield):
for x in range(10):
ofield.insert(END, x)
ofield.insert(END, "\n")


def second():
main=Toplevel(root)
ofield=Text(main, height=15, width=15)
ofield.pack()
B3=Button(main, text='exit', command=main.destroy)
B3.pack()
B4=Button(main, text='fill text', command=genF(ofield))
B4.pack()
main.mainloop()

b1=Button(root, text='open second window', command=second)
b1.pack()
b2=Button(root, text='exit', command=root.destroy)
b2.pack()
root.mainloop()


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


Re: [Tutor] Mutable data type in python

2015-10-03 Thread C Smith
> Here is my modified version which I think works as you want:
>
> def findMinDepthPath(n):
> if n <= 0: raise ValueError
> elif n==1:
> return 0
> elif n==2 or n==3:
> return 1
> else:
> d1 = findMinDepthPath(n-1)+1
> d2 = d3 = (d1+1) # initialize to higher than d1
>
> if n%3 == 0:
> d3 = findMinDepthPath(n/3)+1
> if n%2 == 0:
> d2 = findMinDepthPath(n/2)+1
>
> return min(d1,d2,d3)
>
>
> n = int(raw_input('N? '))
> print "Minimum depth = ", findMinDepthPath(n),'\n'

Doesn't this only look one level deep? Is the poster asking for
something that would traverse all possible paths and then check for
the shortest?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Mutable data type in python

2015-10-03 Thread C Smith
On Sat, Oct 3, 2015 at 11:55 AM, Alan Gauld <alan.ga...@btinternet.com> wrote:
> On 03/10/15 19:10, C Smith wrote:
>>>
>>> Here is my modified version which I think works as you want:
>>>
>>> def findMinDepthPath(n):
>>>  if n <= 0: raise ValueError
>>>  elif n==1:
>>>  return 0
>>>  elif n==2 or n==3:
>>>  return 1
>>>  else:
>>>  d1 = findMinDepthPath(n-1)+1
>>>  d2 = d3 = (d1+1) # initialize to higher than d1
>>>
>>>  if n%3 == 0:
>>>  d3 = findMinDepthPath(n/3)+1
>>>  if n%2 == 0:
>>>  d2 = findMinDepthPath(n/2)+1
>>>
>>>  return min(d1,d2,d3)
>>>
>>>
What I meant was that the algorithm assumes that the lowest value from
one "action" (minus one, divide by 2, divide by 3) is the best
possible branch in the tree. That seems intuitively correct, but is it
necessarily so?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python type confusion?

2015-09-28 Thread C Smith
On Mon, Sep 28, 2015 at 1:27 PM, Ken Hammer  wrote:
> A simple "type" problem?
>
> The following code works as a py file with the XX'd lines replacing the two 
> later "raw_input" lines.
> Why do the "raw_input" lines yield a TypeError: 'str' object is not callable? 
>  Same result if I use/omit
> the parens around the poly tuple.
>
>  evaluate a polynomial as formula for a defined function
> ##poly = (0.0, 0.0, 5.0, 9.3, 7.0)# f(x) = 7x^4 + 9.3x^3 + 5x^2
> ##x = -13
> poly = raw_input("Type, 0.0-n ,")## these do not work in place of 
> above
> x = raw_input("Type your val of x, ")## 'str' object is not callable?
y = int(x) #see below

>
> total = 0.0
> for i in range(len(poly)):
> totalTerm = poly[i]* (x ** i)
Here you would get "unsupported operand type" since you are getting
the ith power of a string.


> total += totalTerm
> print "totalTerm ", i , totalTerm
> print "Equation Value", total
>
>  Good answer follows:
> totalTerm  0 0.0
> totalTerm  1 0.0
> totalTerm  2 845.0
> totalTerm  3 -20432.1
> totalTerm  4 199927.0
> Equation Value 180339.9

> thanks,  Ken Hammer
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python type confusion?

2015-09-28 Thread C Smith
On Mon, Sep 28, 2015 at 4:13 PM, C Smith <illusiontechniq...@gmail.com> wrote:
> On Mon, Sep 28, 2015 at 1:27 PM, Ken Hammer <kfh...@earthlink.net> wrote:
>> A simple "type" problem?
>>
>> The following code works as a py file with the XX'd lines replacing the two 
>> later "raw_input" lines.
>> Why do the "raw_input" lines yield a TypeError: 'str' object is not 
>> callable?  Same result if I use/omit
>> the parens around the poly tuple.
>>
>>  evaluate a polynomial as formula for a defined function
>> ##poly = (0.0, 0.0, 5.0, 9.3, 7.0)# f(x) = 7x^4 + 9.3x^3 + 5x^2
>> ##x = -13
>> poly = raw_input("Type, 0.0-n ,")## these do not work in place of 
>> above
>> x = raw_input("Type your val of x, ")## 'str' object is not callable?
> y = int(x) #see below
>
>>
>> total = 0.0
>> for i in range(len(poly)):
>> totalTerm = poly[i]* (x ** i)
> Here you would get "unsupported operand type" since you are getting
> the ith power of a string.
EDIT: change "x" to "y"
>
>
>> total += totalTerm
>> print "totalTerm ", i , totalTerm
>> print "Equation Value", total
>>
>>  Good answer follows:
>> totalTerm  0 0.0
>> totalTerm  1 0.0
>> totalTerm  2 845.0
>> totalTerm  3 -20432.1
>> totalTerm  4 199927.0
>> Equation Value 180339.9
>>>>>
>> thanks,  Ken Hammer
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] [Tkinter-discuss] tkinter file dialog pattern matching (fwd)

2015-08-24 Thread Chris Roy-Smith

On 23/08/15 23:52, Laura Creighton wrote:

oooh.  Seems that there is an undocumented feature we can use!

Laura

--- Forwarded Message

Return-Path: tkinter-discuss-bounces+lac=openend...@python.org
Date: Sun, 23 Aug 2015 12:40:02 +0200
From: Michael Lange klappn...@web.de
To: tkinter-disc...@python.org
Message-Id: 20150823124002.7391f37e21f9b5cfaa917...@web.de
In-Reply-To: 20150822210424.321b826f@lenny
References: 201508221103.t7mb3kdx010...@fido.openend.se

Hi,

On Sat, 22 Aug 2015 21:04:24 +0100
Pawel Mosakowski pa...@mosakowski.net wrote:


Hi,

I've found this little gem in the Tk docs
https://www.tcl.tk/man/tcl8.4/TkCmd/getOpenFile.htm#M13
 From what I see file patterns in the file dialog are not regex
patterns and do not support special characters. Only things that work
are:
1) * - any extension
2)  - files without extension
3) literal extension without wildcard chars
Unfortunately it looks like there is no simple way to filter out hidden
files.


actually the unix tk file dialog has an an (however undocumented) feature
to hide hidden elements and display even a button that allows to toggle
between hidden elements on/off, however we need to do a little tcl to get
to this. Since the feature is not documented anywhere it might also be a
good idea to wrap this into a try...except. See this little code snippet:

#
from Tkinter import *
import tkFileDialog as tkfd

root = Tk()

try:
 # call a dummy dialog with an impossible option to initialize the file
 # dialog without really getting a dialog window; this will throw a
 # TclError, so we need a try...except :
 try:
 root.tk.call('tk_getOpenFile', '-foobarbaz')
 except TclError:
 pass
 # now set the magic variables accordingly
 root.tk.call('set', '::tk::dialog::file::showHiddenBtn', '1')
 root.tk.call('set', '::tk::dialog::file::showHiddenVar', '0')
except:
 pass

# a simple callback for testing:
def openfile(event):
 fname = tkfd.askopenfilename()
 print(fname)
root.bind('Control-o', openfile)

root.mainloop()
#

Best regards

Michael

___
Tkinter-discuss mailing list
tkinter-disc...@python.org
https://mail.python.org/mailman/listinfo/tkinter-discuss

--- End of Forwarded Message
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Thanks Laura,
That does exactly what I wanted to do.

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


Re: [Tutor] filtering listed directories

2015-08-23 Thread Chris Roy-Smith

On 23/08/15 00:42, Laura Creighton wrote:

In a message of Sat, 22 Aug 2015 14:32:56 +0100, Alan Gauld writes:

But maybe some questions on a Tix (or Tk) forum might
get more help? Once you know how to do it in native
Tcl/Tk/Tix you can usually figure out how to do it
in Python.

--
Alan G


I asked the question on tkinter-discuss, but the question hasn't shown
up yet.

In the meantime, I have found this:
http://www.ccs.neu.edu/research/demeter/course/projects/demdraw/www/tickle/u3/tk3_dialogs.html

which looks like, if we converted it to tkinter, would do the job, since
all it wants is a list of files.

I have guests coming over for dinner, so it will be much later before
I can work on this.  (And I will be slow -- so if you are a wizard
at converting tk to tkinter, by all means feel free to step in here. :) )

Laura

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


Thanks Laura,
unfortunately I know next to nothing of tk, so I'll have wait. No 
worries, This in not an urgent thing, and is mostly a learning exercise, 
as I have a cli tool to do what what I'm aiming to write using Tkinter.


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


Re: [Tutor] filtering listed directories

2015-08-23 Thread Chris Roy-Smith

On 22/08/15 23:32, Alan Gauld wrote:

On 22/08/15 11:43, Laura Creighton wrote:


How can I filter out these hidden directories?
Help(tkFileDialog) doesn't help me as it just shows **options, but
doesn't show what these options might be.



tix (tkinter extensions) https://wiki.python.org/moin/Tix
have some more file dialogs, so maybe there is joy there.



There is a FileSelectDialog in Tix that has a dircmd option
according to the Tix documentation.

However, I've played about with it and can't figure out how
to make it work!

There is also allegedly a 'hidden' check-box subwidget
that controls whether hidden files are shown. Again I
couldn't find how to access this.

But maybe some questions on a Tix (or Tk) forum might
get more help? Once you know how to do it in native
Tcl/Tk/Tix you can usually figure out how to do it
in Python.

Thanks for the Tcl tk hint, so I searched for info for tcl tk. 
Unfortunately the options appear to be the same as offered by tkinter. I 
had hoped that the cause of my problem would be that I'm still to learn 
that bit ;)


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


Re: [Tutor] filtering listed directories

2015-08-23 Thread Chris Roy-Smith

On 23/08/15 18:13, Laura Creighton wrote:

In a message of Sun, 23 Aug 2015 13:09:41 +1000, Chris Roy-Smith writes:

On 22/08/15 23:32, Alan Gauld wrote:

On 22/08/15 11:43, Laura Creighton wrote:


How can I filter out these hidden directories?
Help(tkFileDialog) doesn't help me as it just shows **options, but
doesn't show what these options might be.



tix (tkinter extensions) https://wiki.python.org/moin/Tix
have some more file dialogs, so maybe there is joy there.



There is a FileSelectDialog in Tix that has a dircmd option
according to the Tix documentation.

However, I've played about with it and can't figure out how
to make it work!

There is also allegedly a 'hidden' check-box subwidget
that controls whether hidden files are shown. Again I
couldn't find how to access this.

But maybe some questions on a Tix (or Tk) forum might
get more help? Once you know how to do it in native
Tcl/Tk/Tix you can usually figure out how to do it
in Python.


Thanks for the Tcl tk hint, so I searched for info for tcl tk.
Unfortunately the options appear to be the same as offered by tkinter. I
had hoped that the cause of my problem would be that I'm still to learn
that bit ;)


No, the problem is that the tk widget is badly designed.  Not only is
there only minimal pattern support matching, but there is no way to
subclass the thing and feed it your own list of file and directory
names.  It really is a case of Do not open.  No user-servicable
parts to be found within. which is frustrating.

Laura



Thanks Laura,
I don't use idle but wondered how it handled hidden directories, and 
found that it also shows them. I guess I'll have to be inconsistent 
using the title bar to warn users and trap inappropriate selections 
sending the user back to try again. I can only assume that windows users 
don't get this problem.


Do any of the other graphical packages avoid this problem? I guess I 
should try the appropriate news groups.


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


[Tutor] filtering listed directories

2015-08-22 Thread Chris Roy-Smith

Hi,
environment: Python 2.7, Ubuntu 12.4 Linux

I am trying to get the list of directories shown by 
tkFileDialog.askdirectory to not show hidden files (starting with .)


this code results in lots of hidden directories listed in the interface 
making things harder than they need to be for the user.


#! /usr/bin/python
import Tkinter, tkFileDialog
root = Tkinter.Tk()
root.withdraw()

dirname = 
tkFileDialog.askdirectory(parent=root,initialdir=/home/chris/,title='Pick 
a directory')


How can I filter out these hidden directories?
Help(tkFileDialog) doesn't help me as it just shows **options, but 
doesn't show what these options might be.

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


Re: [Tutor] Abs

2015-07-27 Thread Chris Roy-Smith

On 27/07/15 11:06, Job wrote:

I want to be able to ask a user to input an integer and print out the root and 
power of the given integer.

Why do you use abs(x) for this program?

I don't understand or see the link between abs() and root and powers.

This reminds me of this:
By knowing that when x%2==1 x is an odd number and when x%2 ==0 x is even, I 
was able to create a program that asked the user to enter 10 integers and 
printed out the largest odd number .

So If I understand how and why abs() is used to find the cube root of a perfect 
cube or how to use abs() to make the computer print out the root and power of a 
given integer I may make this program.

Thank you and forgive for my fuzzy thoughts.

Job

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

You will fine that any attempt to find the root of a negative value will 
result in an error.

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


Re: [Tutor] tkinter window not showing max, min and close buttons

2015-07-21 Thread Chris Roy-Smith

On 21/07/15 21:52, Alan Gauld wrote:

On 21/07/15 08:15, Chris Roy-Smith wrote:

On 21/07/15 17:02, Alan Gauld wrote:

On 21/07/15 06:05, Chris Roy-Smith wrote:

I am working my way through Alan Gauld's tutorial and have just started
the section on GUI. The windows that are created look odd with no title
bar or maximise, minimise or close window button.



The simplest program that should show the icons is:

  import Tkinter
  top = Tkinter.Tk()
  top.mainloop()

What do you  see when you type just those lines at
the  prompt?


All I get is a white square, with no way to close without using kill

I have done a bit of tinkering and have found that it is only my user
account that behaves this way.


OK, No idea why that would be happening but it may be a Unity
setting - I use Mint/Cinnamon  because I hated Unity...

Can you try logging out and back in using a different desktop - say XFCE
and see if that
changes anything. That will hopefully narrow it down to a Unity v User
settings issue.

In either case it will probably be an issue for another forum since its
unlikely to be
a Python issue, but please keep me in the loop since it might affect
other tutorial
users.

Thanks Alan, other desktops allow correct operation. Only Unity 3D has 
the fault, Unity-2D works fine. I had not considered that the desktop 
could be the problem. I hope to find the offending file or setting in 
the Unity configuration, as I would prefer to know how to fix this if I 
need to in the future. A clean install and restore isn't an option 
because my backup also has the offending error :( I have narrowed it 
down to 1 machine, so a little detective work should identify the 
offending file.


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


Re: [Tutor] tkinter window not showing max, min and close buttons

2015-07-21 Thread Chris Roy-Smith

On 22/07/15 08:07, Chris Roy-Smith wrote:

On 21/07/15 21:52, Alan Gauld wrote:

On 21/07/15 08:15, Chris Roy-Smith wrote:

On 21/07/15 17:02, Alan Gauld wrote:

On 21/07/15 06:05, Chris Roy-Smith wrote:

I am working my way through Alan Gauld's tutorial and have just
started
the section on GUI. The windows that are created look odd with no
title
bar or maximise, minimise or close window button.



The simplest program that should show the icons is:

  import Tkinter
  top = Tkinter.Tk()
  top.mainloop()

What do you  see when you type just those lines at
the  prompt?


All I get is a white square, with no way to close without using kill

I have done a bit of tinkering and have found that it is only my user
account that behaves this way.


OK, No idea why that would be happening but it may be a Unity
setting - I use Mint/Cinnamon  because I hated Unity...

Can you try logging out and back in using a different desktop - say XFCE
and see if that
changes anything. That will hopefully narrow it down to a Unity v User
settings issue.

In either case it will probably be an issue for another forum since its
unlikely to be
a Python issue, but please keep me in the loop since it might affect
other tutorial
users.


Thanks Alan, other desktops allow correct operation. Only Unity 3D has
the fault, Unity-2D works fine. I had not considered that the desktop
could be the problem. I hope to find the offending file or setting in
the Unity configuration, as I would prefer to know how to fix this if I
need to in the future. A clean install and restore isn't an option
because my backup also has the offending error :( I have narrowed it
down to 1 machine, so a little detective work should identify the
offending file.


Problem solved.
Unity settings are stored using GConf.
Resetting Unity with the following:

dconf reset -f /org/compiz/

then log out and back in.
This fixed a few other mysteries at the same time (some windows could 
not be moved)

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




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


Re: [Tutor] tkinter window not showing max, min and close buttons

2015-07-21 Thread Chris Roy-Smith

On 21/07/15 17:02, Alan Gauld wrote:

On 21/07/15 06:05, Chris Roy-Smith wrote:

I am working my way through Alan Gauld's tutorial and have just started
the section on GUI. The windows that are created look odd with no title
bar or maximise, minimise or close window button.



The simplest program that should show the icons is:

  import Tkinter
  top = Tkinter.Tk()
  top.mainloop()

What do you  see when you type just those lines at
the  prompt?


All I get is a white square, with no way to close without using kill

I have done a bit of tinkering and have found that it is only my user 
account that behaves this way.


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


[Tutor] tkinter window not showing max, min and close buttons

2015-07-20 Thread Chris Roy-Smith
I am working my way through Alan Gauld's tutorial and have just started 
the section on GUI. The windows that are created look odd with no title 
bar or maximise, minimise or close window button.


system Python 2.7 (32 bit)
Ubuntu Linux (unity)

How might I get things to look like in the tutorial?

Thank you
Chris Roy-Smith

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


[Tutor] Sorting a list of list

2015-06-05 Thread Stephen Nelson-Smith
As part of my league secretary program (to which thread I shall reply again
shortly), I need to sort a list of lists.  I've worked out that I can use
sorted() and operator.itemgetter to sort by a value at a known position in
each list.  Is it possible to do this at a secondary level?  So if the
items are the same, we use the secondary key?

Current function:

 def sort_table(table, col=0):
... return sorted(table, key=operator.itemgetter(col), reverse=True)
...
 sort_table(results, 6)
[['spip', 2, 2, 0, 10, 0, 4], ['hpip', 2, 0, 2, 2, 8, 0]]

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


[Tutor] League Secretary Application

2015-05-30 Thread Stephen Nelson-Smith
Hello,

I'm the league secretary for a table tennis league.  I have to generate a
weekly results report, league table, and player averages, from results
cards which arrive by post or email.

The data is of the form:

Division: 1
Week: 7
Home: Some Team
Away: Different Team
Player A: Fred Bloggs
Player B: Nora Batty
Player X: Jim Smith
Player Y: Edna Jones
A vs X: 3-0
B vs Y: 3-2
A vs Y: 3-0
B vs X: 3-2
Doubles: 3-1

From this I can calculate the points allocated to teams and produce a table.

I've not done any real python for about 6 years, but figured it'd be fun to
design and write something that would take away the time and error issues
associated with generating this manually.  Sure I could build a
spreadsheet, but this seems more fun.

I'm currently thinking through possible approaches, from parsing results
written in, eg YAML, to a menu-driven system, to a web app.  I'm generally
in favour of the simplest thing that could possibly work, but I am
conscious that there's a lot of room for data entry error and thus
validation, if I just parse a file, or make a CLI.  OTOH I have never ever
written a web app, with forms etc.

There's no time constraint here - this is merely for fun, and to make my
life easier.

Any thoughts?

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


Re: [Tutor] League Secretary Application

2015-05-30 Thread Stephen Nelson-Smith
Hullo,

On Sat, May 30, 2015 at 3:49 PM, Laura Creighton l...@openend.se wrote:


 2.  How do you receive your data now?  Do you want to change this,
 perhaps extend the capabilities -- i.e. let people send an sms
 with results to your cell phone?  Or limit the capabilities (Stop
 phoning me with this stuff!  Use the webpage!)  How you get your
 data is very relevant to the design.


I get a physical card, or a photograph of the same.  It'd be possible in
the future to get people to use a website or a phone app, but for now, I
enter the data from the cards, manually.


 3.  After you have performed your calculation and made a table, what
 do you do with it?  Email it to members?  Publish it in a
 weekly dead-tree newspaper?  Post it to a website?  What you
 want to do with it once you have it is also very relevant to the
 design.


ATM I send an email out, and someone else takes that data and publishes it
on a website.

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


[Tutor] Umm.. I need help on changing Global Variables.

2015-01-29 Thread Tallen Grey Smith
So, I’m trying to make a very simple game that involves time management 
properly, but I’m having an issue.

level = 1
player_health = 100
enemy_health = 100
steps = 10
civilians = 20
charge = 0
name_2 = 'Bob'

def game():

global level
global player_health
global enemy_health
global steps
global civilians
global charge



print \n * 80
print Level  + str(level)
print  name_2 +:  + str(player_health) + HP
print Centurion:  + str(enemy_health) +  HP
print Distance:  + str(steps) +  feet
print Weapon Charge:  + str(charge)
print Civilians Remaining:  + str(civilians)
print A Centurion lands near the gate! Prepare the Laser!
action_1 = raw_input(Do you want to charge the laser or fire?)
action_2 = action_1.lower()

if action_2 == charge:
charge == charge+10
steps == steps-1
civilians == civilians -1
charge_1()


def charge_1():

level
player_health
enemy_health
steps
civilians
charge
print \n * 80
print Level  + str(level)
print  name_2 +:  + str(player_health) + HP
print Centurion:  + str(enemy_health) +  HP
print Distance:  + str(steps) +  feet
print Weapon Charge:  + str(charge)
print Civilians Remaining:  + str(civilians)
print The Centurion moves closer! Hurry!
action_1 = raw_input(Do you want to charge the laser or fire?)
action_2 = action_1.lower()

if action_2 == charge:
charge = charge+10
steps = steps-1
civilians = civilians -1
charge_1()

game()


thats my code, and I want it to where if I type charge it’ll make my charge go 
up 10, my steps go down 1, my divs going down 1, and it to go to my charge_1 
function, which should do the same thing but with a tweaked dialog box. But no 
matter how hard i try, once it gets to the charge_1, it always says that the 
variables that I changed where referenced in previous functions and it can’t 
pull them. How can I change this to get a variable that when changed in my If 
statement, would be useable in other functions?
Thanks.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Ideas for Child's Project

2015-01-07 Thread Stephen Nelson-Smith
Hi Danny,

On Tue, Jan 6, 2015 at 10:07 PM, Danny Yoo d...@hashcollision.org wrote:

 On Tue, Jan 6, 2015 at 1:46 PM, Stephen Nelson-Smith sanel...@gmail.com
 wrote:

 You might want to look at Bootstrapworld, a curriculum for
 middle-school/high-school math using programming and games:

 http://www.bootstrapworld.org/

 Students who go through the material learn how math can be used
 productively toward writing a video game.  Along the way, they learn
 the idea of function, of considering inputs and outputs, and how to
 test what they've designed.


Sounds ace.  I had a look.  It seems optimised for Racket, which is also
cool so I installed Racket on my son's computer and let him have a
play.  He immediately got into it, and got the hang of functions and
expressions etc.

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


[Tutor] Ideas for Child's Project

2015-01-06 Thread Stephen Nelson-Smith
Hello,

My son is interested in programming, and has dabbled in Scratch and done a
tiny bit of Python at school.  He's 11 and is going for an entrance exam
for a selective school in a couple of weeks.  They've asked him to bring
along something to demonstrate an interest, and present it to them.

In talking about it, we hit upon the idea that he might like to embark upon
a prorgamming challenge, or learning objective / project, spending say 30
mins a day for the next week or two, so he can show what he's done and talk
about what he learned.

Any suggestions for accessible yet challenging and stimulating projects?

Any recommendations for books / websites / tutorials that are worth a look?

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


Re: [Tutor] Tutor Digest, Vol 129, Issue 22

2014-11-11 Thread Ben Smith
Hi - I'm a teacher  sometimes when we're holding a two minute silence for an 
important occasion an
email comes through  makes my computer ping loudly. Is there a python script 
to stop these kind of things happening?

;)

-Original Message-
From: Tutor [mailto:tutor-bounces+ben.smith=arnoldkeqms@python.org] On 
Behalf Of tutor-requ...@python.org
Sent: 11 November 2014 11:00
To: tutor@python.org
Subject: Tutor Digest, Vol 129, Issue 22

Send Tutor mailing list submissions to
tutor@python.org

To subscribe or unsubscribe via the World Wide Web, visit
https://mail.python.org/mailman/listinfo/tutor
or, via email, send a message with subject or body 'help' to
tutor-requ...@python.org

You can reach the person managing the list at
tutor-ow...@python.org

When replying, please edit your Subject line so it is more specific than Re: 
Contents of Tutor digest...


Today's Topics:

   1. Re: http  question (Clayton Kirkwood)
   2. Re: ?has a value of True? versus ?evaluates true? (was: don't
  understand iteration) (wesley chun)
   3. Re: don't understand iteration (Alan Gauld)


--

Message: 1
Date: Mon, 10 Nov 2014 20:52:23 -0800
From: Clayton Kirkwood c...@godblessthe.us
To: tutor@python.org
Subject: Re: [Tutor] http  question
Message-ID: 01c801cffd6b$492408a0$db6c19e0$@us
Content-Type: text/plain;   charset=us-ascii



-Original Message-
From: Tutor [mailto:tutor-bounces+crk=godblessthe...@python.org] On
Behalf Of Steven D'Aprano
Sent: Sunday, November 09, 2014 3:04 AM
To: tutor@python.org
Subject: Re: [Tutor] http question

On Sat, Nov 08, 2014 at 09:53:33PM -0800, Clayton Kirkwood wrote:

  but I also am aware of httplib2, but it still seems to be in
  eternal alpha.
 
 What leads you to that conclusion? If you're talking about this:
 
 https://github.com/jcgregorio/httplib2
 
 I don't see any sign that it is alpha version software. According to
 the readme file, it is at version 0.8.
 
 I don't see any signs that the author publicly releases any alpha or
 beta versions, they all appear to be ready for production. But if
 you have seen something that suggests otherwise, please point it
 out, because I'm happy to be corrected.

 Well, I work from the premise that 0.anything is still a work in
 progress

All software is always a work in progress, until such time it is
abandoned.

And how do you determine the abandoned timestamp? If I remember correctly, this 
hasn't been updated for several years, and a job for a customer shouldn't be 
based on 0.*, years old hypothetical's. It sounds like a very usable product.


 and hasn't gotten to a point where the author is comfortable with
 general use. I am sure that you disagree.

In the FOSS (Free and Open Source Software) community, version 0.x does
not always carry connotations of being unready for use. It may, or it
may not. But normally alpha software will have an a in the version
number, e.g. 0.7a, 0.7b for beta, 0.7rc1 (release candidate 1), 0.7 is
ready for production.

What matters is not my opinion, or yours, but that of the author of the
software, and I don't know what that is.


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





--

Message: 2
Date: Mon, 10 Nov 2014 23:35:07 -0800
From: wesley chun wes...@gmail.com
To: c...@godblessthe.us
Cc: tutor tutor@python.org, Ben Finney ben+pyt...@benfinney.id.au
Subject: Re: [Tutor] ?has a value of True? versus ?evaluates true?
(was: don't understand iteration)
Message-ID:
CAB6eaA7dKS1JLzWAstXXLf5=hP=jmm9ucw8_j_qufrmo-nv...@mail.gmail.com
Content-Type: text/plain; charset=utf-8

good catch, and definitely a distinction beginners should be more cognizant of.

it's also good to recognize that a call to bool(match) would render that 
statement correct, as the built-in/factory function will return what an object 
evaluates to (True [re.match object] or/vs.False [None]).

On Mon, Nov 10, 2014 at 5:31 PM, Clayton Kirkwood c...@godblessthe.us
wrote:

 I reported it. I feel all grown up now. Kind of like one of the
 boys(girls...)

 Clayton:)


 -Original Message-
 From: Tutor [mailto:tutor-bounces+crk=godblessthe...@python.org] On
 Behalf Of Ben Finney
 Sent: Monday, November 10, 2014 3:24 PM
 To: tutor@python.org
 Subject: [Tutor] ?has a value of True? versus ?evaluates true? (was:
 don't understand iteration)
 
 Clayton Kirkwood c...@godblessthe.us writes:
 
  Also of confusion, the library reference says:
 
  Match objects always have a boolean value of True. Since match()
  and
  search() return None when there is no match, you can test whether
  there was a match with a simple if statement:
 
  match = re.search(pattern, string)
  if match:
  process(match)
 
 The documentation is incorrect, as you 

[Tutor] Whack-a-mole

2014-10-01 Thread Ben Smith
Hi, Can anyone help explain why you can keep hitting the Mole even when 
hittable should be False?

from tkinter import *

root = Tk()
#root.state('zoomed')
sec = 0
points=0
pic=PhotoImage(file='Dirt.gif')
pic2=PhotoImage(file='Mole.gif')
hittable=False

def HIT():
if hittable==True:
global points;points+=1
butty.configure(image=pic)
labby.configure(text=points)

def tick():
global sec, hittable
sec += 1
if sec == 3:
hittable=True
butty.configure(image=pic2)
if sec==6:
hittable=False
butty.configure(image=pic)
time['text'] = sec
time.after(1000, tick)

time = Label(root)
time.pack()
labby = Label(root, text=POINTS);labby.pack()
Button(root, text='Start', command=tick).pack()

butty=Button(root, image=pic, command=HIT);butty.pack()

root.mainloop()



This email and any attachments sent with it are intended only for the named 
recipient. If you are not that person please contact us immediately through our 
website and delete this message from your computer. You should not disclose the 
content nor take, retain or distribute any copies. No responsibility is 
accepted by AKS, United Learning or any associated entity for the contents of 
e-mails unconnected with their business. No responsibility is accepted for any 
loss or damage caused due to any virus attached to this email.

AKS is part of United Learning, comprising: UCST (Registered in England No: 
2780748. Charity No. 1016538) and ULT (Registered in England No. 4439859. An 
Exempt Charity).
Companies limited by guarantee.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Module? Error handling specific to SQLite3

2014-09-26 Thread Paul Smith
Ok Tutor help please...

Early stages messing with module sqlite3 in python3.4. I am successful in
creating sqlite tables of my own and interacting with other sqlite tables,
however in refining the code from a purely it can do it stage to a more
stable working piece of code I run into this problem.

I call the correct sqlite3 items and create table D to which I add or
'amend' specific information from tables A and Z.

However since the table is already created the line of code that created
the table subsequently kicks out this error when the program runs again.

Traceback (most recent call last):
  File C:\Users\Thechives\Desktop\pyweather\AlphaItems\
weathercodetrial1.2.py, line 206, in module
cur.execute('''CREATE TABLE D AS SELECT weather_current FROM
todays_weather WHERE weather_current IS NOT NULL''')
sqlite3.OperationalError: table D already exists

So how does one handle the error or ignore the creation portion of the
program once the table is created?

Python exception handling has not helped, Try - Except - although I am
mashing it I am sure. I believe since we are actually engaging sqlite via
python at this point in the code it should be a sqlite error handler or
some such. So simple and yet it eludes my noobile mind.

Thanks in advance,

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


Re: [Tutor] Help

2014-09-18 Thread C Smith
Check this guy's youtube channel. He has very basic examples. His
username is thenewboston

On Wed, Sep 17, 2014 at 4:36 PM, Art Pelletier artp...@gmail.com wrote:

 I am a beginner with pythons programming   I would like to see if their is a 
 site that has samples programs that I can practice on.
 Sent from my iPad
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using subprocess on a series of files with spaces

2014-08-01 Thread C Smith
However, the subprocess call above uses a list for the command, and that form 
DOES NOT pass anything to the shell. The command gets executed directly. And 
therefore no spaces need escaping at all.

That makes more sense to me now.

In terms of the code review, I found that stackexchange has a code
review site, in case anyone else is curious:
https://codereview.stackexchange.com
It would be hard to post a sscc example since the parts I am curious
about reference other class variables that would be unclear out of
context, I think.
Much appreciated...

On Fri, Aug 1, 2014 at 4:38 AM, Ben Finney ben+pyt...@benfinney.id.au wrote:
 Peter Otten __pete...@web.de writes:

 C Smith wrote:

  Nice, these are useful tools. I have been building something with
  just basic stuff and avoiding learning any libraries. If I wanted to
  get some insight on a larger program that is about 1000 lines, would
  that be doable here?

 In general we prefer concrete questions and smaller chunks of code.
 With 1000 lines you get fewer people to even take a look.

 Right. When attrmpting to learn, keep the examples simple. This will
 make it easier to focus on the essential points, and also minimise whole
 categories of error.

 To get feedback on some code, make it a Short, Self-Contained,
 Compilable Example URL:http://sscce.org/. This means we will be able
 to read the code quickly, run it ourselves, and better see what its
 purpose is.

 You might still try and post a link to the code together with a few
 questions here...

 Not really advised. If the code is too long to discuss in context here,
 much of the point is lost; we prefer discussions to have the code inline
 so the public archives contain the code too. That's an important reason
 to keep it short and self-contained.

 --
  \   “I bought some batteries, but they weren't included; so I had |
   `\to buy them again.” —Steven Wright |
 _o__)  |
 Ben Finney

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


Re: [Tutor] Using subprocess on a series of files with spaces

2014-08-01 Thread C Smith
Won't that write the mp3 to the current working dir? (Is that the dir where 
the .py lives? Or even the Python bin dir? Perhaps the cwd parameter of 
call() will be good?

Yeah, it just wrote the mp3's to my desktop, where I had the .py
script. But that was fine for my purposes. Just for curiosity's sake,
would you put cwd outside the list and inside the parens of the
subprocess.call()?

On Fri, Aug 1, 2014 at 4:23 PM, Albert-Jan Roskam
fo...@yahoo.com.dmarc.invalid wrote:



 --
 On Fri, Aug 1, 2014 12:35 AM CEST Steven D'Aprano wrote:

You may have already have solved your problem, unfortunately my
emails are coming in slowly and out of order, but I have a suggestion:

On Thu, Jul 31, 2014 at 03:53:48PM -0400, C Smith wrote:
 I am on OSX, which needs to escape spaces in filenames with a backslash.

Same as any other Unix, or Linux, or, indeed, Windows.

 There are multiple files within one directory that all have the same
 structure, one or more characters with zero or more spaces in the
 filename, like this:
 3 Song Title XYZ.flac.
 I want to use Python to call ffmpeg to convert each file to an .mp3.
 So far this is what I was trying to use:
 import os, subprocess
 track = 1
 for filename in os.listdir('myDir'):
 subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
 track += 1

I believe that your problem is *not* the spaces, but that you're passing
just the filename and not the directory. subprocess will escape the
spaces for you. Also, let Python count the track number for you. Try
this:


directory = '/path/to/the/directory'
for track, filename in enumerate(os.listdir(directory), 1):
pathname = os.path.join(directory, filename)
subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])

 Won't that write the mp3 to the current working dir? (Is that the dir where 
 the .py lives? Or even the Python bin dir? Perhaps the cwd parameter of 
 call() will be good?
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Using subprocess on a series of files with spaces

2014-07-31 Thread C Smith
I am on OSX, which needs to escape spaces in filenames with a backslash.
There are multiple files within one directory that all have the same
structure, one or more characters with zero or more spaces in the
filename, like this:
3 Song Title XYZ.flac.
I want to use Python to call ffmpeg to convert each file to an .mp3.
So far this is what I was trying to use:
import os, subprocess
track = 1
for filename in os.listdir('myDir'):
subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
track += 1


I am about to use re.sub to just replace all the '/s' with '\\/s', but
is there a simpler/more pythonic way to do this?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using subprocess on a series of files with spaces

2014-07-31 Thread C Smith
Change:


subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])

to:

subprocess.call(['ffmpeg', '-i', '%s' % filename, str(track)+'.mp3'])

I still get the same errors, the filenames are passed to the shell
without escaping the spaces.

Why not using ffmpeg without jumping into Python. It's well documented, check 
Google.

I guess you mean that the ability to change multiple files with ffmpeg
is possible. I hadn't considered that but I would rather do it with
Python, just for the practice.

On Thu, Jul 31, 2014 at 4:36 PM, Emile em...@salesinq.com wrote:
 On 7/31/2014 1:19 PM, C Smith wrote:

 I get
 TypeError: unsupported operand type(s) for %: 'int' and 'str
 I am not understanding the use of the list inside the subprocess.call().
 I tried all of the following
 subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3']) % filename
 --gives type error stated above
 subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3'] % filename)
 --same
 subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3' % filename])
 -- TypeError: not all arguments converted during string formatting
 and tried all three with the triple quotes, just to be sure.

 On Thu, Jul 31, 2014 at 4:04 PM, Emile van Sebille em...@fenx.com wrote:

 You might try using '%s' % filename so that the name is within quotes
 for the shell environment.


 Change:


 subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])

 to:

 subprocess.call(['ffmpeg', '-i', '%s' % filename, str(track)+'.mp3'])

 Emile



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


Re: [Tutor] Using subprocess on a series of files with spaces

2014-07-31 Thread C Smith
Even when I am using:
re.sub('/s', '\\/s', filename)
I am still getting the same output, even trying to assign the above to
a new variable doesn't work (as I wasn't sure if re.sub returned a new
value or changed filename in place, I tried both with)
Does the Python interpreter strip off backslashes or something with strings?

On Thu, Jul 31, 2014 at 5:53 PM, C Smith illusiontechniq...@gmail.com wrote:
Change:


subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])

to:

subprocess.call(['ffmpeg', '-i', '%s' % filename, str(track)+'.mp3'])

 I still get the same errors, the filenames are passed to the shell
 without escaping the spaces.

Why not using ffmpeg without jumping into Python. It's well documented, check 
Google.

 I guess you mean that the ability to change multiple files with ffmpeg
 is possible. I hadn't considered that but I would rather do it with
 Python, just for the practice.

 On Thu, Jul 31, 2014 at 4:36 PM, Emile em...@salesinq.com wrote:
 On 7/31/2014 1:19 PM, C Smith wrote:

 I get
 TypeError: unsupported operand type(s) for %: 'int' and 'str
 I am not understanding the use of the list inside the subprocess.call().
 I tried all of the following
 subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3']) % filename
 --gives type error stated above
 subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3'] % filename)
 --same
 subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3' % filename])
 -- TypeError: not all arguments converted during string formatting
 and tried all three with the triple quotes, just to be sure.

 On Thu, Jul 31, 2014 at 4:04 PM, Emile van Sebille em...@fenx.com wrote:

 You might try using '%s' % filename so that the name is within quotes
 for the shell environment.


 Change:


 subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])

 to:

 subprocess.call(['ffmpeg', '-i', '%s' % filename, str(track)+'.mp3'])

 Emile



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


Re: [Tutor] Using subprocess on a series of files with spaces

2014-07-31 Thread C Smith
Okay I messed up with slash instead of backslash, so the re.sub()
works, but I am still curious about the previous question.

On Thu, Jul 31, 2014 at 6:14 PM, C Smith illusiontechniq...@gmail.com wrote:
 Even when I am using:
 re.sub('/s', '\\/s', filename)
 I am still getting the same output, even trying to assign the above to
 a new variable doesn't work (as I wasn't sure if re.sub returned a new
 value or changed filename in place, I tried both with)
 Does the Python interpreter strip off backslashes or something with strings?

 On Thu, Jul 31, 2014 at 5:53 PM, C Smith illusiontechniq...@gmail.com wrote:
Change:


subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])

to:

subprocess.call(['ffmpeg', '-i', '%s' % filename, str(track)+'.mp3'])

 I still get the same errors, the filenames are passed to the shell
 without escaping the spaces.

Why not using ffmpeg without jumping into Python. It's well documented, 
check Google.

 I guess you mean that the ability to change multiple files with ffmpeg
 is possible. I hadn't considered that but I would rather do it with
 Python, just for the practice.

 On Thu, Jul 31, 2014 at 4:36 PM, Emile em...@salesinq.com wrote:
 On 7/31/2014 1:19 PM, C Smith wrote:

 I get
 TypeError: unsupported operand type(s) for %: 'int' and 'str
 I am not understanding the use of the list inside the subprocess.call().
 I tried all of the following
 subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3']) % filename
 --gives type error stated above
 subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3'] % filename)
 --same
 subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3' % filename])
 -- TypeError: not all arguments converted during string formatting
 and tried all three with the triple quotes, just to be sure.

 On Thu, Jul 31, 2014 at 4:04 PM, Emile van Sebille em...@fenx.com wrote:

 You might try using '%s' % filename so that the name is within quotes
 for the shell environment.


 Change:


 subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])

 to:

 subprocess.call(['ffmpeg', '-i', '%s' % filename, str(track)+'.mp3'])

 Emile



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


Re: [Tutor] Using subprocess on a series of files with spaces

2014-07-31 Thread C Smith
Actually, I can get re.sub() to print the filenames where they look
like they would be in the correct format for the shell, like this:
10\ track \number \ten.flac
but the shell still says that no such file exists, and I am sure I am
operating on them in the right place because I can modify them. So, I
am still wondering about that too.

On Thu, Jul 31, 2014 at 6:20 PM, C Smith illusiontechniq...@gmail.com wrote:
 Okay I messed up with slash instead of backslash, so the re.sub()
 works, but I am still curious about the previous question.

 On Thu, Jul 31, 2014 at 6:14 PM, C Smith illusiontechniq...@gmail.com wrote:
 Even when I am using:
 re.sub('/s', '\\/s', filename)
 I am still getting the same output, even trying to assign the above to
 a new variable doesn't work (as I wasn't sure if re.sub returned a new
 value or changed filename in place, I tried both with)
 Does the Python interpreter strip off backslashes or something with strings?

 On Thu, Jul 31, 2014 at 5:53 PM, C Smith illusiontechniq...@gmail.com 
 wrote:
Change:


subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])

to:

subprocess.call(['ffmpeg', '-i', '%s' % filename, str(track)+'.mp3'])

 I still get the same errors, the filenames are passed to the shell
 without escaping the spaces.

Why not using ffmpeg without jumping into Python. It's well documented, 
check Google.

 I guess you mean that the ability to change multiple files with ffmpeg
 is possible. I hadn't considered that but I would rather do it with
 Python, just for the practice.

 On Thu, Jul 31, 2014 at 4:36 PM, Emile em...@salesinq.com wrote:
 On 7/31/2014 1:19 PM, C Smith wrote:

 I get
 TypeError: unsupported operand type(s) for %: 'int' and 'str
 I am not understanding the use of the list inside the subprocess.call().
 I tried all of the following
 subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3']) % filename
 --gives type error stated above
 subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3'] % filename)
 --same
 subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3' % filename])
 -- TypeError: not all arguments converted during string formatting
 and tried all three with the triple quotes, just to be sure.

 On Thu, Jul 31, 2014 at 4:04 PM, Emile van Sebille em...@fenx.com wrote:

 You might try using '%s' % filename so that the name is within quotes
 for the shell environment.


 Change:


 subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])

 to:

 subprocess.call(['ffmpeg', '-i', '%s' % filename, str(track)+'.mp3'])

 Emile



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


Re: [Tutor] Using subprocess on a series of files with spaces

2014-07-31 Thread C Smith
for track, filename in enumerate(os.listdir(directory), 1):
It seems kinda counter-intuitive to have track then filename as
variables, but enumerate looks like it gets passed the filename then
track number. Is that correct and just the way enumerate works, a
typo, or am I missing something else here?

It is an ffmpeg error I am getting.
ffmpeg just gives its usual build information and the error is (for
each song title in the directory):
songTitleIsHere.flac: no such file or directory

So it looks like it is close to working because it finds the correct
file names, but doesn't recognize it for some reason.
Here is how I put in your code
import os, subprocess
directory = '/absolute/path/goes/here'
for track, filename in enumerate(os.listdir(directory), 1):
pathname = os.path.join(directory, filename)
subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])

So it goes to the right place, because every song title is listed out,
ffmpeg or the shell just don't recognize them correctly.

On Thu, Jul 31, 2014 at 6:35 PM, Steven D'Aprano st...@pearwood.info wrote:
 You may have already have solved your problem, unfortunately my
 emails are coming in slowly and out of order, but I have a suggestion:

 On Thu, Jul 31, 2014 at 03:53:48PM -0400, C Smith wrote:
 I am on OSX, which needs to escape spaces in filenames with a backslash.

 Same as any other Unix, or Linux, or, indeed, Windows.

 There are multiple files within one directory that all have the same
 structure, one or more characters with zero or more spaces in the
 filename, like this:
 3 Song Title XYZ.flac.
 I want to use Python to call ffmpeg to convert each file to an .mp3.
 So far this is what I was trying to use:
 import os, subprocess
 track = 1
 for filename in os.listdir('myDir'):
 subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
 track += 1

 I believe that your problem is *not* the spaces, but that you're passing
 just the filename and not the directory. subprocess will escape the
 spaces for you. Also, let Python count the track number for you. Try
 this:


 directory = '/path/to/the/directory'
 for track, filename in enumerate(os.listdir(directory), 1):
 pathname = os.path.join(directory, filename)
 subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])


 I expect something like that will work. You should be able to pass
 either an absolute path (beginning with /) or a relative path starting
 from the current working directory.

 If this doesn't work, please show the full error that you receive. If it
 is a Python traceback, copy and paste the whole thing, if it's an ffmpeg
 error, give as much information as you can.



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


Re: [Tutor] Using subprocess on a series of files with spaces

2014-07-31 Thread C Smith
woops, I see it pathname != filename

On Thu, Jul 31, 2014 at 6:55 PM, C Smith illusiontechniq...@gmail.com wrote:
for track, filename in enumerate(os.listdir(directory), 1):
 It seems kinda counter-intuitive to have track then filename as
 variables, but enumerate looks like it gets passed the filename then
 track number. Is that correct and just the way enumerate works, a
 typo, or am I missing something else here?

 It is an ffmpeg error I am getting.
 ffmpeg just gives its usual build information and the error is (for
 each song title in the directory):
 songTitleIsHere.flac: no such file or directory

 So it looks like it is close to working because it finds the correct
 file names, but doesn't recognize it for some reason.
 Here is how I put in your code
 import os, subprocess
 directory = '/absolute/path/goes/here'
 for track, filename in enumerate(os.listdir(directory), 1):
 pathname = os.path.join(directory, filename)
 subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])

 So it goes to the right place, because every song title is listed out,
 ffmpeg or the shell just don't recognize them correctly.

 On Thu, Jul 31, 2014 at 6:35 PM, Steven D'Aprano st...@pearwood.info wrote:
 You may have already have solved your problem, unfortunately my
 emails are coming in slowly and out of order, but I have a suggestion:

 On Thu, Jul 31, 2014 at 03:53:48PM -0400, C Smith wrote:
 I am on OSX, which needs to escape spaces in filenames with a backslash.

 Same as any other Unix, or Linux, or, indeed, Windows.

 There are multiple files within one directory that all have the same
 structure, one or more characters with zero or more spaces in the
 filename, like this:
 3 Song Title XYZ.flac.
 I want to use Python to call ffmpeg to convert each file to an .mp3.
 So far this is what I was trying to use:
 import os, subprocess
 track = 1
 for filename in os.listdir('myDir'):
 subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
 track += 1

 I believe that your problem is *not* the spaces, but that you're passing
 just the filename and not the directory. subprocess will escape the
 spaces for you. Also, let Python count the track number for you. Try
 this:


 directory = '/path/to/the/directory'
 for track, filename in enumerate(os.listdir(directory), 1):
 pathname = os.path.join(directory, filename)
 subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])


 I expect something like that will work. You should be able to pass
 either an absolute path (beginning with /) or a relative path starting
 from the current working directory.

 If this doesn't work, please show the full error that you receive. If it
 is a Python traceback, copy and paste the whole thing, if it's an ffmpeg
 error, give as much information as you can.



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


Re: [Tutor] Using subprocess on a series of files with spaces

2014-07-31 Thread C Smith
Works now, thanks!

On Thu, Jul 31, 2014 at 6:57 PM, C Smith illusiontechniq...@gmail.com wrote:
 woops, I see it pathname != filename

 On Thu, Jul 31, 2014 at 6:55 PM, C Smith illusiontechniq...@gmail.com wrote:
for track, filename in enumerate(os.listdir(directory), 1):
 It seems kinda counter-intuitive to have track then filename as
 variables, but enumerate looks like it gets passed the filename then
 track number. Is that correct and just the way enumerate works, a
 typo, or am I missing something else here?

 It is an ffmpeg error I am getting.
 ffmpeg just gives its usual build information and the error is (for
 each song title in the directory):
 songTitleIsHere.flac: no such file or directory

 So it looks like it is close to working because it finds the correct
 file names, but doesn't recognize it for some reason.
 Here is how I put in your code
 import os, subprocess
 directory = '/absolute/path/goes/here'
 for track, filename in enumerate(os.listdir(directory), 1):
 pathname = os.path.join(directory, filename)
 subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])

 So it goes to the right place, because every song title is listed out,
 ffmpeg or the shell just don't recognize them correctly.

 On Thu, Jul 31, 2014 at 6:35 PM, Steven D'Aprano st...@pearwood.info wrote:
 You may have already have solved your problem, unfortunately my
 emails are coming in slowly and out of order, but I have a suggestion:

 On Thu, Jul 31, 2014 at 03:53:48PM -0400, C Smith wrote:
 I am on OSX, which needs to escape spaces in filenames with a backslash.

 Same as any other Unix, or Linux, or, indeed, Windows.

 There are multiple files within one directory that all have the same
 structure, one or more characters with zero or more spaces in the
 filename, like this:
 3 Song Title XYZ.flac.
 I want to use Python to call ffmpeg to convert each file to an .mp3.
 So far this is what I was trying to use:
 import os, subprocess
 track = 1
 for filename in os.listdir('myDir'):
 subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
 track += 1

 I believe that your problem is *not* the spaces, but that you're passing
 just the filename and not the directory. subprocess will escape the
 spaces for you. Also, let Python count the track number for you. Try
 this:


 directory = '/path/to/the/directory'
 for track, filename in enumerate(os.listdir(directory), 1):
 pathname = os.path.join(directory, filename)
 subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])


 I expect something like that will work. You should be able to pass
 either an absolute path (beginning with /) or a relative path starting
 from the current working directory.

 If this doesn't work, please show the full error that you receive. If it
 is a Python traceback, copy and paste the whole thing, if it's an ffmpeg
 error, give as much information as you can.



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


Re: [Tutor] Using subprocess on a series of files with spaces

2014-07-31 Thread C Smith
Huh, that is quite an annoyance about changing the order though. Any
ideas about that? I will look into it further in the meantime...

On Thu, Jul 31, 2014 at 6:57 PM, C Smith illusiontechniq...@gmail.com wrote:
 Works now, thanks!

 On Thu, Jul 31, 2014 at 6:57 PM, C Smith illusiontechniq...@gmail.com wrote:
 woops, I see it pathname != filename

 On Thu, Jul 31, 2014 at 6:55 PM, C Smith illusiontechniq...@gmail.com 
 wrote:
for track, filename in enumerate(os.listdir(directory), 1):
 It seems kinda counter-intuitive to have track then filename as
 variables, but enumerate looks like it gets passed the filename then
 track number. Is that correct and just the way enumerate works, a
 typo, or am I missing something else here?

 It is an ffmpeg error I am getting.
 ffmpeg just gives its usual build information and the error is (for
 each song title in the directory):
 songTitleIsHere.flac: no such file or directory

 So it looks like it is close to working because it finds the correct
 file names, but doesn't recognize it for some reason.
 Here is how I put in your code
 import os, subprocess
 directory = '/absolute/path/goes/here'
 for track, filename in enumerate(os.listdir(directory), 1):
 pathname = os.path.join(directory, filename)
 subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])

 So it goes to the right place, because every song title is listed out,
 ffmpeg or the shell just don't recognize them correctly.

 On Thu, Jul 31, 2014 at 6:35 PM, Steven D'Aprano st...@pearwood.info 
 wrote:
 You may have already have solved your problem, unfortunately my
 emails are coming in slowly and out of order, but I have a suggestion:

 On Thu, Jul 31, 2014 at 03:53:48PM -0400, C Smith wrote:
 I am on OSX, which needs to escape spaces in filenames with a backslash.

 Same as any other Unix, or Linux, or, indeed, Windows.

 There are multiple files within one directory that all have the same
 structure, one or more characters with zero or more spaces in the
 filename, like this:
 3 Song Title XYZ.flac.
 I want to use Python to call ffmpeg to convert each file to an .mp3.
 So far this is what I was trying to use:
 import os, subprocess
 track = 1
 for filename in os.listdir('myDir'):
 subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
 track += 1

 I believe that your problem is *not* the spaces, but that you're passing
 just the filename and not the directory. subprocess will escape the
 spaces for you. Also, let Python count the track number for you. Try
 this:


 directory = '/path/to/the/directory'
 for track, filename in enumerate(os.listdir(directory), 1):
 pathname = os.path.join(directory, filename)
 subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])


 I expect something like that will work. You should be able to pass
 either an absolute path (beginning with /) or a relative path starting
 from the current working directory.

 If this doesn't work, please show the full error that you receive. If it
 is a Python traceback, copy and paste the whole thing, if it's an ffmpeg
 error, give as much information as you can.



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


Re: [Tutor] Using subprocess on a series of files with spaces

2014-07-31 Thread C Smith
thanks, got it
import os, subprocess, re
directory = 'abs/path'
for track, filename in enumerate(os.listdir(directory), 1):
pathname = os.path.join(directory, filename)
subprocess.call(['ffmpeg', '-i', pathname, filename+str(track)+'.mp3'])

On Thu, Jul 31, 2014 at 7:02 PM, C Smith illusiontechniq...@gmail.com wrote:
 Huh, that is quite an annoyance about changing the order though. Any
 ideas about that? I will look into it further in the meantime...

 On Thu, Jul 31, 2014 at 6:57 PM, C Smith illusiontechniq...@gmail.com wrote:
 Works now, thanks!

 On Thu, Jul 31, 2014 at 6:57 PM, C Smith illusiontechniq...@gmail.com 
 wrote:
 woops, I see it pathname != filename

 On Thu, Jul 31, 2014 at 6:55 PM, C Smith illusiontechniq...@gmail.com 
 wrote:
for track, filename in enumerate(os.listdir(directory), 1):
 It seems kinda counter-intuitive to have track then filename as
 variables, but enumerate looks like it gets passed the filename then
 track number. Is that correct and just the way enumerate works, a
 typo, or am I missing something else here?

 It is an ffmpeg error I am getting.
 ffmpeg just gives its usual build information and the error is (for
 each song title in the directory):
 songTitleIsHere.flac: no such file or directory

 So it looks like it is close to working because it finds the correct
 file names, but doesn't recognize it for some reason.
 Here is how I put in your code
 import os, subprocess
 directory = '/absolute/path/goes/here'
 for track, filename in enumerate(os.listdir(directory), 1):
 pathname = os.path.join(directory, filename)
 subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])

 So it goes to the right place, because every song title is listed out,
 ffmpeg or the shell just don't recognize them correctly.

 On Thu, Jul 31, 2014 at 6:35 PM, Steven D'Aprano st...@pearwood.info 
 wrote:
 You may have already have solved your problem, unfortunately my
 emails are coming in slowly and out of order, but I have a suggestion:

 On Thu, Jul 31, 2014 at 03:53:48PM -0400, C Smith wrote:
 I am on OSX, which needs to escape spaces in filenames with a backslash.

 Same as any other Unix, or Linux, or, indeed, Windows.

 There are multiple files within one directory that all have the same
 structure, one or more characters with zero or more spaces in the
 filename, like this:
 3 Song Title XYZ.flac.
 I want to use Python to call ffmpeg to convert each file to an .mp3.
 So far this is what I was trying to use:
 import os, subprocess
 track = 1
 for filename in os.listdir('myDir'):
 subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
 track += 1

 I believe that your problem is *not* the spaces, but that you're passing
 just the filename and not the directory. subprocess will escape the
 spaces for you. Also, let Python count the track number for you. Try
 this:


 directory = '/path/to/the/directory'
 for track, filename in enumerate(os.listdir(directory), 1):
 pathname = os.path.join(directory, filename)
 subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])


 I expect something like that will work. You should be able to pass
 either an absolute path (beginning with /) or a relative path starting
 from the current working directory.

 If this doesn't work, please show the full error that you receive. If it
 is a Python traceback, copy and paste the whole thing, if it's an ffmpeg
 error, give as much information as you can.



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


Re: [Tutor] Using subprocess on a series of files with spaces

2014-07-31 Thread C Smith
or more accurately
import os, subprocess, re
directory = '/abs/path'
for track, filename in enumerate(os.listdir(directory), 1):
pathname = os.path.join(directory, filename)
subprocess.call(['ffmpeg', '-i', pathname, filename[:-5]+'.mp3'])

On Thu, Jul 31, 2014 at 7:13 PM, C Smith illusiontechniq...@gmail.com wrote:
 thanks, got it
 import os, subprocess, re
 directory = 'abs/path'
 for track, filename in enumerate(os.listdir(directory), 1):
 pathname = os.path.join(directory, filename)
 subprocess.call(['ffmpeg', '-i', pathname, filename+str(track)+'.mp3'])

 On Thu, Jul 31, 2014 at 7:02 PM, C Smith illusiontechniq...@gmail.com wrote:
 Huh, that is quite an annoyance about changing the order though. Any
 ideas about that? I will look into it further in the meantime...

 On Thu, Jul 31, 2014 at 6:57 PM, C Smith illusiontechniq...@gmail.com 
 wrote:
 Works now, thanks!

 On Thu, Jul 31, 2014 at 6:57 PM, C Smith illusiontechniq...@gmail.com 
 wrote:
 woops, I see it pathname != filename

 On Thu, Jul 31, 2014 at 6:55 PM, C Smith illusiontechniq...@gmail.com 
 wrote:
for track, filename in enumerate(os.listdir(directory), 1):
 It seems kinda counter-intuitive to have track then filename as
 variables, but enumerate looks like it gets passed the filename then
 track number. Is that correct and just the way enumerate works, a
 typo, or am I missing something else here?

 It is an ffmpeg error I am getting.
 ffmpeg just gives its usual build information and the error is (for
 each song title in the directory):
 songTitleIsHere.flac: no such file or directory

 So it looks like it is close to working because it finds the correct
 file names, but doesn't recognize it for some reason.
 Here is how I put in your code
 import os, subprocess
 directory = '/absolute/path/goes/here'
 for track, filename in enumerate(os.listdir(directory), 1):
 pathname = os.path.join(directory, filename)
 subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])

 So it goes to the right place, because every song title is listed out,
 ffmpeg or the shell just don't recognize them correctly.

 On Thu, Jul 31, 2014 at 6:35 PM, Steven D'Aprano st...@pearwood.info 
 wrote:
 You may have already have solved your problem, unfortunately my
 emails are coming in slowly and out of order, but I have a suggestion:

 On Thu, Jul 31, 2014 at 03:53:48PM -0400, C Smith wrote:
 I am on OSX, which needs to escape spaces in filenames with a backslash.

 Same as any other Unix, or Linux, or, indeed, Windows.

 There are multiple files within one directory that all have the same
 structure, one or more characters with zero or more spaces in the
 filename, like this:
 3 Song Title XYZ.flac.
 I want to use Python to call ffmpeg to convert each file to an .mp3.
 So far this is what I was trying to use:
 import os, subprocess
 track = 1
 for filename in os.listdir('myDir'):
 subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
 track += 1

 I believe that your problem is *not* the spaces, but that you're passing
 just the filename and not the directory. subprocess will escape the
 spaces for you. Also, let Python count the track number for you. Try
 this:


 directory = '/path/to/the/directory'
 for track, filename in enumerate(os.listdir(directory), 1):
 pathname = os.path.join(directory, filename)
 subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])


 I expect something like that will work. You should be able to pass
 either an absolute path (beginning with /) or a relative path starting
 from the current working directory.

 If this doesn't work, please show the full error that you receive. If it
 is a Python traceback, copy and paste the whole thing, if it's an ffmpeg
 error, give as much information as you can.



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


Re: [Tutor] Using subprocess on a series of files with spaces

2014-07-31 Thread C Smith
Nice, these are useful tools. I have been building something with just
basic stuff and avoiding learning any libraries. If I wanted to get
some insight on a larger program that is about 1000 lines, would that
be doable here?

On Thu, Jul 31, 2014 at 7:37 PM, Peter Otten __pete...@web.de wrote:
 C Smith wrote:

 I'd throw in a check to verify that filename is indeed a flac:

 or more accurately
 import os, subprocess, re
 directory = '/abs/path'
 for track, filename in enumerate(os.listdir(directory), 1):
 pathname = os.path.join(directory, filename)
   if filename.endswith(.flac):
   subprocess.call(['ffmpeg', '-i', pathname, filename[:-5]+'.mp3'])


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


Re: [Tutor] Why is Quick Search at docs.Python.org so useless?

2014-07-05 Thread C Smith
I agree very much. I feel like I might have a learning disability when
I try to reference the official Python docs for something that seems
like it should be a very common task.

On Sat, Jul 5, 2014 at 1:31 PM, Deb Wyatt codemon...@inbox.com wrote:
 I am betting that a big reason newbies don't go straight to documentation for 
 answers is because of the useless quick search.  You should be able to type 
 'dictionary' and get links to the dictionary info.  You get a bunch of links 
 that are meaningless to someone who wants to learn about how to use 
 dictionaries.  It frustrates me to death when I want to look up a detail 
 about how a particular function works and I can't find it because quick 
 search doesn't provide the link to the BASIC information.

 Another example of what I am talking about, I just did a search of max(), a 
 BUILT-IN function.  This is what quick search gives me:

 Your search did not match any documents. Please make sure that all words are 
 spelled correctly and that you've selected enough categories.

 What is up with that???

 I realize that this list doesn't have control over python.org, but there are 
 enough of you who are experts about all this stuff that maybe some changes 
 can be made.  If I ever learn enough, I hope to be part of the solution 
 myself.  A working search engine would be most helpful.

 Yes, I use Google all that time. But quick search should be useful. Thanks in 
 advance for any insights and help.


 Deb in WA, USA

 
 Receive Notifications of Incoming Messages
 Easily monitor multiple email accounts  access them with a click.
 Visit http://www.inbox.com/notifier and check it out!


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


Re: [Tutor] What are your favourite unofficial resources

2014-06-30 Thread C Smith
Learning Python Design Patterns, by Gennadiy Zlobin
Let us know when your book is done!

On Mon, Jun 30, 2014 at 7:05 AM, Bob Williams
li...@barrowhillfarm.org.uk wrote:
 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1

 On 29/06/14 23:41, Alan Gauld wrote:
 I'm looking for tips for an appendix to a book that I'm working
 on.

 What are the best unofficial (ie not python.org) resources for
 people who have learned the basics but are not experts yet? ie
 Typical tutor list graduates...

 I'm thinking about web sites, blogs, books, videos etc. Anything
 that might be worth knowing about.

 I've got a few of my own - Activestate, O'Reilly, ByteOfPython,
 PythonChallenge, ShowMeDo etc.

 But I thought the tutor list readers might be an interesting source
 of alternatives that I hadn't thought of, or even heard of.

 All contributions considered :-)


 Python Module of the Week http://pymotw.com/2/

 Bob
 - --
 Bob Williams
 System:  Linux 3.11.10-17-desktop
 Distro:  openSUSE 13.1 (x86_64) with KDE Development Platform: 4.13.2
 Uptime:  06:00am up 1 day 20:14, 0 users, load average: 0.04, 0.05, 0.05
 -BEGIN PGP SIGNATURE-
 Version: GnuPG v2.0.22 (GNU/Linux)
 Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/

 iEYEARECAAYFAlOxRIsACgkQ0Sr7eZJrmU5kfQCgkE0dRzO1G+o/GX78s4U7oe3U
 mNQAoJ+ayTo+79Xj+9JaHoMrflxDHCzW
 =uWQJ
 -END PGP SIGNATURE-
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Doubts about installing python3.1 in squeeze

2014-05-22 Thread C Smith
Sorry, typing is hard.
*You will need to use virtualenv

On Thu, May 22, 2014 at 2:40 PM, C Smith illusiontechniq...@gmail.com wrote:
 You can't use apt-get or similar to install 3.1.
 You will need to virtualenv.

 On Thu, May 22, 2014 at 12:22 PM, Alex Kleider aklei...@sonic.net wrote:
 On 2014-05-22 06:17, Markos wrote:

 Hi,

 I'm learning Python and I'm using Debian 6.0 (squeeze)

 The installed version is 2.6.6. (python -V)

 I have seen some recommendations for beginners to invest in version 3.

 I found package of Python 3.1 in repository for squeeze.

 I am considering installing Python 3.1 with

 apt-get install python3.1

 But I found the site
 http://www.circuidipity.com/python2-and-python3.html information on
 how to keep the two versions using virtualenv.

 Also I found in the /usr/bin python2.5 and python2.6

 And in /usr/lib python2.4, python2.5 and python2.6

 Can I just run apt-get install python3.1 or should I do any other
 configuration?

 I'm confused.


 Are there any risk to install python3.1 and some programs stop working
 on my debian squeeze?

 Thanks for any tips?
 Markos


 On Ubuntu both v2 and v3 are installed by default.
 Have you tried typing
 python3
 on the command line?
 If you get the interpreter, it's installed.
 Then you just have to use a different shebang line in your code files:
 #!/usr/bin/env python3

 I don't have a debian system close at hand to test this myself.

 alex

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


Re: [Tutor] Doubts about installing python3.1 in squeeze

2014-05-22 Thread C Smith
You can't use apt-get or similar to install 3.1.
You will need to virtualenv.

On Thu, May 22, 2014 at 12:22 PM, Alex Kleider aklei...@sonic.net wrote:
 On 2014-05-22 06:17, Markos wrote:

 Hi,

 I'm learning Python and I'm using Debian 6.0 (squeeze)

 The installed version is 2.6.6. (python -V)

 I have seen some recommendations for beginners to invest in version 3.

 I found package of Python 3.1 in repository for squeeze.

 I am considering installing Python 3.1 with

 apt-get install python3.1

 But I found the site
 http://www.circuidipity.com/python2-and-python3.html information on
 how to keep the two versions using virtualenv.

 Also I found in the /usr/bin python2.5 and python2.6

 And in /usr/lib python2.4, python2.5 and python2.6

 Can I just run apt-get install python3.1 or should I do any other
 configuration?

 I'm confused.


 Are there any risk to install python3.1 and some programs stop working
 on my debian squeeze?

 Thanks for any tips?
 Markos


 On Ubuntu both v2 and v3 are installed by default.
 Have you tried typing
 python3
 on the command line?
 If you get the interpreter, it's installed.
 Then you just have to use a different shebang line in your code files:
 #!/usr/bin/env python3

 I don't have a debian system close at hand to test this myself.

 alex

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


Re: [Tutor] While truth

2014-05-20 Thread C Smith
You can test out a condition like this in IDLE like so:
while 6:
print yes its true
break


while 0:
print yes its true
break


while -1:
print yes its true
break


emptyList = []
while emtpyList:
print yes its true
break

This way you don't have to deal with an infinite loop.
It will print yes its true once, if it IS true and then break will
break you out of the loop.

On Tue, May 20, 2014 at 2:00 PM, Danny Yoo d...@hashcollision.org wrote:
 On Tue, May 20, 2014 at 1:25 AM, Ian D dux...@hotmail.com wrote:
 I was reading a tutorial that had these examples in it:


 while False:
   print(False is the new True.)


 while 6:
   print(Which numbers are True?)


 while -1:
   print(Which numbers are True?)


 while 0:
   print(Which numbers are True?)

 Unfortunately the author never explained these statements.


 The statements above are trying to talk about what Python considers to
 be true.  In some languages, there is a single distinguished true
 value.  Python chooses a broader definition that allows everything to
 be considered true, with the exception of the following values:

 False
 None
 Numeric zero
 Empty collection
 Empty string

 Reference: https://docs.python.org/3/reference/expressions.html#booleans

 We care about what values are true, because they are the switch that
 controls which way we're flowing through a conditional statement like
 if or while.

 As people are pointing out, the examples above are a bit
 disappointing.  They are demonstrating this with infinite while loops,
 and that's probably not a great idea because the output will be so
 overwhelming to be actively distracting.
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While truth

2014-05-20 Thread C Smith
Of course that isn't very useful code. I thought it might be a useful
quick test for someone learning how while loops treat different
values.

On Tue, May 20, 2014 at 2:46 PM, Danny Yoo d...@hashcollision.org wrote:
 On Tue, May 20, 2014 at 11:44 AM, C Smith illusiontechniq...@gmail.com 
 wrote:
 You can test out a condition like this in IDLE like so:
 while 6:
 print yes its true
 break


 while 0:
 print yes its true
 break


 while -1:
 print yes its true
 break


 emptyList = []
 while emtpyList:
 print yes its true
 break

 This way you don't have to deal with an infinite loop.
 It will print yes its true once, if it IS true and then break will
 break you out of the loop.


 That being said, if we're going to go through these contortions, we
 might as well use if, right?  :P


 The infinite loops in the examples above are a complete distraction
 from the main point, I think.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] for the error about 'import site' failed; use -v for traceback

2014-05-14 Thread C Smith
That looks pretty normal. I don't see any errors.

On Wed, May 14, 2014 at 5:42 AM, Tao Zhu zxl_...@126.com wrote:
 Hi everyone,
 when I use python, the problem occured. when I used the command python -v,
 the results are listed as follows. could you tell me what wrong?

 $ python -v
 # installing zipimport hook
 import zipimport # builtin
 # installed zipimport hook
 # /usr/local/lib/python2.4/site.pyc matches /usr/local/lib/python2.4/site.py
 import site # precompiled from /usr/local/lib/python2.4/site.pyc
 # /usr/local/lib/python2.4/os.pyc matches /usr/local/lib/python2.4/os.py
 import os # precompiled from /usr/local/lib/python2.4/os.pyc
 import posix # builtin
 # /usr/local/lib/python2.4/posixpath.pyc matches
 /usr/local/lib/python2.4/posixpath.py
 import posixpath # precompiled from /usr/local/lib/python2.4/posixpath.pyc
 # /usr/local/lib/python2.4/stat.pyc matches /usr/local/lib/python2.4/stat.py
 import stat # precompiled from /usr/local/lib/python2.4/stat.pyc
 # /usr/local/lib/python2.4/UserDict.pyc matches
 /usr/local/lib/python2.4/UserDict.py
 import UserDict # precompiled from /usr/local/lib/python2.4/UserDict.pyc
 # /usr/local/lib/python2.4/copy_reg.pyc matches
 /usr/local/lib/python2.4/copy_reg.py
 import copy_reg # precompiled from /usr/local/lib/python2.4/copy_reg.pyc
 # /usr/local/lib/python2.4/types.pyc matches
 /usr/local/lib/python2.4/types.py
 import types # precompiled from /usr/local/lib/python2.4/types.pyc
 # /usr/local/lib/python2.4/warnings.pyc matches
 /usr/local/lib/python2.4/warnings.py
 import warnings # precompiled from /usr/local/lib/python2.4/warnings.pyc
 # /usr/local/lib/python2.4/linecache.pyc matches
 /usr/local/lib/python2.4/linecache.py
 import linecache # precompiled from /usr/local/lib/python2.4/linecache.pyc
 import encodings # directory /usr/local/lib/python2.4/encodings
 # /usr/local/lib/python2.4/encodings/__init__.pyc matches
 /usr/local/lib/python2.4/encodings/__init__.py
 import encodings # precompiled from
 /usr/local/lib/python2.4/encodings/__init__.pyc
 # /usr/local/lib/python2.4/codecs.pyc matches
 /usr/local/lib/python2.4/codecs.py
 import codecs # precompiled from /usr/local/lib/python2.4/codecs.pyc
 import _codecs # builtin
 # /usr/local/lib/python2.4/encodings/aliases.pyc matches
 /usr/local/lib/python2.4/encodings/aliases.py
 import encodings.aliases # precompiled from
 /usr/local/lib/python2.4/encodings/aliases.pyc
 # /usr/local/lib/python2.4/encodings/utf_8.pyc matches
 /usr/local/lib/python2.4/encodings/utf_8.py
 import encodings.utf_8 # precompiled from
 /usr/local/lib/python2.4/encodings/utf_8.pyc
 Python 2.4.4 (#3, May 15 2014, 00:22:35)
 [GCC 3.4.4 20050721 (Red Hat 3.4.4-2)] on linux2
 Type help, copyright, credits or license for more information.
 dlopen(/usr/local/lib/python2.4/lib-dynload/readline.so, 2);
 import readline # dynamically loaded from
 /usr/local/lib/python2.4/lib-dynload/readline.so

 Tao



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

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


Re: [Tutor] for the error about 'import site' failed; use -v for traceback

2014-05-14 Thread C Smith
What are you trying to do?

On Wed, May 14, 2014 at 12:24 PM, C Smith illusiontechniq...@gmail.com wrote:
 That looks pretty normal. I don't see any errors.

 On Wed, May 14, 2014 at 5:42 AM, Tao Zhu zxl_...@126.com wrote:
 Hi everyone,
 when I use python, the problem occured. when I used the command python -v,
 the results are listed as follows. could you tell me what wrong?

 $ python -v
 # installing zipimport hook
 import zipimport # builtin
 # installed zipimport hook
 # /usr/local/lib/python2.4/site.pyc matches /usr/local/lib/python2.4/site.py
 import site # precompiled from /usr/local/lib/python2.4/site.pyc
 # /usr/local/lib/python2.4/os.pyc matches /usr/local/lib/python2.4/os.py
 import os # precompiled from /usr/local/lib/python2.4/os.pyc
 import posix # builtin
 # /usr/local/lib/python2.4/posixpath.pyc matches
 /usr/local/lib/python2.4/posixpath.py
 import posixpath # precompiled from /usr/local/lib/python2.4/posixpath.pyc
 # /usr/local/lib/python2.4/stat.pyc matches /usr/local/lib/python2.4/stat.py
 import stat # precompiled from /usr/local/lib/python2.4/stat.pyc
 # /usr/local/lib/python2.4/UserDict.pyc matches
 /usr/local/lib/python2.4/UserDict.py
 import UserDict # precompiled from /usr/local/lib/python2.4/UserDict.pyc
 # /usr/local/lib/python2.4/copy_reg.pyc matches
 /usr/local/lib/python2.4/copy_reg.py
 import copy_reg # precompiled from /usr/local/lib/python2.4/copy_reg.pyc
 # /usr/local/lib/python2.4/types.pyc matches
 /usr/local/lib/python2.4/types.py
 import types # precompiled from /usr/local/lib/python2.4/types.pyc
 # /usr/local/lib/python2.4/warnings.pyc matches
 /usr/local/lib/python2.4/warnings.py
 import warnings # precompiled from /usr/local/lib/python2.4/warnings.pyc
 # /usr/local/lib/python2.4/linecache.pyc matches
 /usr/local/lib/python2.4/linecache.py
 import linecache # precompiled from /usr/local/lib/python2.4/linecache.pyc
 import encodings # directory /usr/local/lib/python2.4/encodings
 # /usr/local/lib/python2.4/encodings/__init__.pyc matches
 /usr/local/lib/python2.4/encodings/__init__.py
 import encodings # precompiled from
 /usr/local/lib/python2.4/encodings/__init__.pyc
 # /usr/local/lib/python2.4/codecs.pyc matches
 /usr/local/lib/python2.4/codecs.py
 import codecs # precompiled from /usr/local/lib/python2.4/codecs.pyc
 import _codecs # builtin
 # /usr/local/lib/python2.4/encodings/aliases.pyc matches
 /usr/local/lib/python2.4/encodings/aliases.py
 import encodings.aliases # precompiled from
 /usr/local/lib/python2.4/encodings/aliases.pyc
 # /usr/local/lib/python2.4/encodings/utf_8.pyc matches
 /usr/local/lib/python2.4/encodings/utf_8.py
 import encodings.utf_8 # precompiled from
 /usr/local/lib/python2.4/encodings/utf_8.pyc
 Python 2.4.4 (#3, May 15 2014, 00:22:35)
 [GCC 3.4.4 20050721 (Red Hat 3.4.4-2)] on linux2
 Type help, copyright, credits or license for more information.
 dlopen(/usr/local/lib/python2.4/lib-dynload/readline.so, 2);
 import readline # dynamically loaded from
 /usr/local/lib/python2.4/lib-dynload/readline.so

 Tao



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

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


Re: [Tutor] Translator - multiple choice answer

2014-05-14 Thread C Smith
This might be useful for reading values from a text value into a dictionary:
https://stackoverflow.com/questions/17775273/how-to-read-and-store-values-from-a-text-file-into-a-dictionary-python

On Wed, May 14, 2014 at 7:00 PM, Danny Yoo d...@hashcollision.org wrote:
 Program read TXT file (c:\\slo3.txt)
 In this file there are two words per line separated by tab.
 First word is foreign language and second word is proper translation, like
 this:

 pivobeer
 kruhbread
 rdeca   red
 krompir potatoe
 hisahouse
 cesta   road
 autocar

 (not even trying to mess with special characters for now, lol)

 Do look at:

 http://www.joelonsoftware.com/articles/Unicode.html

 because the fact that you're dealing with foreign language means you
 want to get it right.


 If it were me, I'd just say that the input is UTF-8 encoded text, and
 always open up the file in utf-8 mode.

 myfile = open(slo3.txt, r, encoding=utf8)

 and just know that we're working with Unicode from that point forward.



 I was going to read content into dictionary, each pair as tuple but I gave
 up, couldn't figure it out. Looks like it is working with the list so no
 problem.

 Question 1: would be better to use dictionary, than list?

 It depends.

 If you're picking out a random entry, then having a dictionary in hand
 is not going to need the key lookup support that dictionaries give
 you.

 For the application you're describing right now, it doesn't sound like
 you need this yet.



 Question 2: slo3.txt is just small sample for now and before I type in all
 words, I would like to know is it better to use some other separator such as
 coma or empty space instead of TAB? I found on the internet example for TAB
 only, so this is what I'm using for now.

 TAB is a reasonable separator.  You might also consider comma, as in
 Comma-Separated Values (CSV).

 If your data starts having more structure, then check back with folks
 on the tutor mailing list.  There are richer formats you can use, but
 your program's description suggests that you probably don't need the
 complexity yet.





 I need help with two things. First one is simple, basic, but I couldn't
 figure it out. If I want to print out 'Wrong' part in the same line next
 to wrong answer, how do I do it?

 The print function puts a newline at the end.  You can change this
 default behavior by providing an end keyword to it.  The
 documentation mentions it here:

 https://docs.python.org/3/library/functions.html#print

 Small test program to demonstrate:

 
 print(Hello , end=)
 print(world )
 



 Now, big, huge help request.
 I would like to make it easy on my wife :-) instead of her needing to type
 in answer I would like that she could choose (click on) multiple choice. Say
 she get 4 or 5 possible answers and one of them is correct. Then she need to
 click on correct answer...

 What do I need to do? I understand there will be some graphic/windows things
 involved. I don't have any additional packages or libraries installed, nor
 do I know what/how do do it. Complete noob

 How about printing them with numbers, so that entry is just a number
 rather than the typed word?


 You can put a graphical user interface on the program, though it does
 take a bit more effort to get it to work.

 Look into Tkinter, which is a library for producing graphical user 
 interfaces:

 https://wiki.python.org/moin/TkInter



 Another option might be to turn your program into a web site, so that
 the interface is the web browser, which everyone is getting used to
 these days.  But this, too, is also... involved.  :P
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Real world experience

2014-05-12 Thread C Smith
Thanks to everyone.

 practice.  That programming doesn't have to be a solitary thing needs
 to be strongly emphasized, because the media likes to exaggerate,
Yes, This can't be stressed too much. Industrial coding is a team activity not 
a solo process.

This is particularly good advice for me. Although I realized that a
big project would involve many people, I was thinking of myself as
coding alone in dark room  without being able to go over ideas with
a team. I would probably get less frustrated that way.

One big step is program for someone else

This is something I need to practice.

Just as a side comment: there are probably several folks on this
mailing list whose job description would match working in industry.

I was thinking IRL. Thanks for the sense of community though.

I don't know where you're geographically located, but if you are close
to Hacker Dojo, they're good people.

That looks pretty amazing. I am in Atlanta, but I may take a bus out
there just to check it out. I lived in LA for a little while and
venice beach, santa monica, and the desert-y hills around mulholland
drive were beautiful.

or a significant contribution to the industry.

I will keep this in mind.

involve following standardized practices, using standard notations and naming 
conventions and so on.

This is another very relevant thing for me to keep in mind. My
variables are usually interesting animals or spells from final fantasy
1.

Thanks

On Mon, May 12, 2014 at 4:55 PM, Alan Gauld alan.ga...@btinternet.com wrote:
 On 12/05/14 18:47, Danny Yoo wrote:

 practice.  That programming doesn't have to be a solitary thing needs
 to be strongly emphasized, because the media likes to exaggerate,


 Yes, This can't be stressed too much. Industrial coding is a team activity
 not a solo process.

 In fact one well known and respected management book(*) had as a maxiom -
 Beware of the man in a darkened room. What it meant was be suspicious of
 the lone wolf coder who doesn't tell you what he'sd doing, where he's at
 etc.
 His code will likely not work with any one else's (and he'll blame
 them of course!) and it will be late because its always 95%
 complete...

 There are a few lone shark geniuses out there, I've met maybe 2 in
 my 40 years in IT. But 99.9% of coders work best in a team.


 (*)Software Project Survival Guide by Steve McConnell
 (also author of Code Complete etc)

 --
 Alan G
 Author of the Learn to Program web site
 http://www.alan-g.me.uk/
 http://www.flickr.com/photos/alangauldphotos

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


Re: [Tutor] Real world experience

2014-05-12 Thread C Smith
Freeside is more makers. I haven't gone but have known people that
have. You might find some arduino supposedly, but not much coding
otherwise and you have to pay membership fees. It is more social than
technical, I think. And your car will probably be broken into. I will
check out the python-atlanta group though, thanks.

On Mon, May 12, 2014 at 7:42 PM, Danny Yoo d...@hashcollision.org wrote:
I don't know where you're geographically located, but if you are close
to Hacker Dojo, they're good people.

 That looks pretty amazing. I am in Atlanta, but I may take a bus out
 there just to check it out. I lived in LA for a little while and
 venice beach, santa monica, and the desert-y hills around mulholland
 drive were beautiful.

 Scanning Atlanta

 ...
 ...

 I do not know what the status of this is in real life, since I don't
 live in Atlanta, but you might want to check on:

 https://wiki.freesideatlanta.org/fs/Info


 Alternatively, check your local meetups in the area.  For example:

 http://www.meetup.com/Geekspace-Gwinnett/

 http://www.meetup.com/python-atlanta/


 There are probably many others out there in your local area.  Start
 searching.  :P


 Good luck to you!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Real world experience

2014-05-12 Thread C Smith
I think that is going to be my new wallpaper.

On Mon, May 12, 2014 at 8:25 PM, Martin A. Brown mar...@linux-ip.net wrote:

 Hello,

   10 Pick one favorite specific topic, any topic (XML parsing; Unix
  process handling; databases).  The topic matters for you.
  Learn it deeply.  Keep learning it.  The topic matters less for
  others (unless it is specifically within the computer science
  discipline).  You have just begun. [0]

   20 Pick a toolkit (minidom, etree; os, multiprocessing, threading,
  subprocess; sqlite, psycopg, sqlalchemy, mysql).  Learn why
  people solved the problem differently each time.  Ask.

   30 Write a program that does something interesting with this.
  Try a different toolkit.  What was hard?  What was easy?
  What could you simply not accomplish?  Look at the source code
  for the tool you used?  Why couldn't you accomplish what you
  wanted?

   40 Read all of the documentation.  Read it again.  Read papers and
  books listed in the documentation footnotes.  Read the
  documentation again.  Realize that all of this is a (fallible)
  human endeavor.

   45 Find other, related mailing lists.  Subscribe.  Listen.  Post.

   46 Talk to somebody who has solved the problem.  How?  What tools
  did that person use [1]?

   48 If reference to something that was new or you did not
  understand, GOTO 40.

   50 Write a brand new program to solve the same problem.  Examine
  what you did differently.  Ask somebody to review your code.

   52 Read your old code.

   53 Talk to somebody who has solved the problem in his/her own
  way, potentially with different tools. [2]

   59 If MASTERY and BORED, GOTO 10.

   60 GOTO 20 [3]

 This discipline can be approached in depth-first or breadth-first
 traversal pattern.  Most people on more technical mailing lists
 appreciate the depth-first traversal.

 Time waits for nobody (Oh! I need to go eat!),

 -Martin

  [0] For these purposes, mine was IP networking.
  [1] What!?!  Not Python?!  Why?  There are reasons to choose
  something else.  Do not be blind to those resaons.
  [2] Find people who are motivated as you are and are working on
  similar problems.  Work for them.  Keep reading.  Hire them.
  Keep writing.  Keep reading.
  [3] Oops.  I learned on BASIC.  I hope I do not get banned from
  the list.

 --
 Martin A. Brown
 http://linux-ip.net/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with Python

2014-05-11 Thread C Smith
Hey Glen, include the error you are getting. It will make answering
your question easier. How are you running this program, in an IDE?

On Sat, May 10, 2014 at 11:16 PM, Glen Chan gchan...@msn.com wrote:
 Hello, I am a student trying to figure out Python. I am getting errors that
 I don't know how to fix. What do you do after you get the error message and
 something is highlighted? Does that have to be deleted? Anyway, here is what
 I mean...


 # The Dice Game
 #add libraries needed
 import random
 #the main function
 def main():
 print
 #initialize variables
 playerOne = 'No Name'
 playerTwo = 'No Name'

 #call to inputNames
 playerOne, playerTwo = inputNames(playerOne, playerTwo)
 #while loop to run program again
 while endProgram == 'no':
 #initialize variables
  winnersName = 'NO NAME'
  p1number = 0
  p2number = 0
 #call to rollDice
  winnerName = rollDice(p1number, p2number, playerOne, playerTwo,
 winnerName)

 #call to displayInfo
  winnerName
 endProgram = raw_input('Do you want to end program? (Enter yes or
 no): ')



 #this function gets the players names
 def inputNames(playerOne, playerTwo):
 playerOne = raw_input(Enter Name)
 playerTwo = raw_input(Enter Name)

 return playerOne, playerTwo
 #this function will get the random values
 def rollDice(p1numer, p2numer, playerOne, playerTwo, winnerName):
  p1number = random.randint(1, 6)
  p1number = random.randint(1, 6)

 #this function displays the winner

 if p1number == p2number:
 winnerName = TIE
 elif p1number  p2number:
 winnerName = playerOne
 else:
 winnerName = playerTwo
 return winnerName

 # calls main
 main()


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

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


[Tutor] Real world experience

2014-05-11 Thread C Smith
I have never known anyone that works in this industry. I got one job
transforming xml (should have used xslt, ended up using sed and python
regex scripts) where the guy asked me how much I wanted and I threw
200 bucks out there because I could get a room for two weeks at that
cost. He just laughed and handed me the money. That is the only
professional experience I have and no formal education whatsoever
(some high school). I have been doing online stuff and hit a wall in a
'design of computer programs' class on udacity. I made it about
halfway through but started back at square one to sharpen my skills
before trying to come at it again from a different angle. I started to
feel overwhelmed when trying to basically recode regex (functions for
'*' and '.' for instance) in python and make an api to interact easily
with the text parser.

I am still completely in the dark about what level of difficulty I
would be facing in the professional world.
If this is difficult at all for me, is there hope to think about
making money in this field?
I am pretty persistent and can keep up a level of work if I am not
even close yet, but I don't know if I am a year off or 10 years off.
Are basic scripting skills employable at even a very low rate (10
bucks an hour)?
What level of experience are the people at who make 100k a year?
Sorry if this is off-topic for the list, but I am trying to get past a
psychological hurdle or two before reapplying myself and hopefully it
would be valuable to others as well.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Real world experience

2014-05-11 Thread C Smith
What is a difficult problem that if I could solve it would indicate I
am ready to begin looking for a job? I realize that solving just ONE
problem isn't too meaningful, but I am looking for a level of
difficulty or some sort of gauge as to what a good programmer would
consider difficult. What would a junior programmer for a company be
expected to be able to do? This way I could have an idea of the range
between a beginner (still a paid employee) and someone with many years
of experience. I am in the south, USA.
thanks

On Sun, May 11, 2014 at 9:43 PM, Tim Krupinski tdkrupin...@gmail.com wrote:
 Probably off-topic for the list but i'll let some of the others weigh in on
 that.  This is more for help with the python language itself.

 But i'll weigh in.  Programming is difficult work.  It's definitely a
 profitable career.  Its hard to say how much you'll make since it varies
 depending on location, but in general a combination of experience and your
 ability to solve difficult problems and provide solutions consistently
 command higher salaries.  However, many companies wont even consider you
 without a degree, or a significant contribution to the industry.

 If you want to pursue a career in IT, you need to finish high school.  You
 would be wise to get a degree.

 My $0.02.

 Tim


 On Sun, May 11, 2014 at 7:12 PM, C Smith illusiontechniq...@gmail.com
 wrote:

 I have never known anyone that works in this industry. I got one job
 transforming xml (should have used xslt, ended up using sed and python
 regex scripts) where the guy asked me how much I wanted and I threw
 200 bucks out there because I could get a room for two weeks at that
 cost. He just laughed and handed me the money. That is the only
 professional experience I have and no formal education whatsoever
 (some high school). I have been doing online stuff and hit a wall in a
 'design of computer programs' class on udacity. I made it about
 halfway through but started back at square one to sharpen my skills
 before trying to come at it again from a different angle. I started to
 feel overwhelmed when trying to basically recode regex (functions for
 '*' and '.' for instance) in python and make an api to interact easily
 with the text parser.

 I am still completely in the dark about what level of difficulty I
 would be facing in the professional world.
 If this is difficult at all for me, is there hope to think about
 making money in this field?
 I am pretty persistent and can keep up a level of work if I am not
 even close yet, but I don't know if I am a year off or 10 years off.
 Are basic scripting skills employable at even a very low rate (10
 bucks an hour)?
 What level of experience are the people at who make 100k a year?
 Sorry if this is off-topic for the list, but I am trying to get past a
 psychological hurdle or two before reapplying myself and hopefully it
 would be valuable to others as well.
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 https://mail.python.org/mailman/listinfo/tutor


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


Re: [Tutor] How inefficient is this code?

2014-05-07 Thread C Smith
I see. Thanks that is exactly what I was looking for. Would your
example be an instance of an object-oriented approach,
compartmentalizing things into functions?

On Wed, May 7, 2014 at 7:55 PM, Joe Cortes escoz...@gmail.com wrote:
 Welcome to the wonderful world of generators!

 Looking at your code, you'll notice two things. First, you're
 iterating over all the numbers twice: once to calculate them, and then
 another time to actually do the sum. What's worse, at any given point
 in time, you're only really using fibs[-1] and fibs[-2], and yet
 you're still building this huge list with all the numbers. This is bad
 in terms of memory efficiency. Luckily, it's such a common problem
 that Python offers a really nice, really Pythonic solution. You can
 define the following function:

 def fib(top):
 first = 1 # As an aside, consider starting the sequence from 0, 1.
 next = 2
 yield first
 while next  top:
  yield next
  # For kicks, try rewriting the following three lines as a
 tuple assignment.
  new_next = next + first
  first = next
  next = new_next

 Now, how do you use this? This being Python, there is a super simple
 way to do this:

 sum = 0
 for num in fib(400):
  if num % 2 == 0:
 sum += num
 print sum


 So, what's going on here? fib is mostly straightforward, but that
 yield keyword might look new.
 Here's the deal: when you have a function that uses the yield keyword,
 that function becomes usable in the context of a for loop. Every time
 it hits a yield it will, well, yield that value out to the for loop.
 At the end of an iteration, control will be handed back to the
 function, which will do its magic, and yield another value. Again, the
 value will be sent out to the for loop, in this case as the num
 variable, for use in that iteration.
 When the function hits a return (or reaches the end of its body), the
 for loop ends.

 This is called a generator function, and is a really nice way to
 simplify and optimize your loops.

 You can read more about generators here: 
 https://wiki.python.org/moin/Generators


 On Wed, May 7, 2014 at 7:27 PM, C Smith illusiontechniq...@gmail.com wrote:
 A topic came up on slashdot concerning intermediate programming,
 where the poster expressed the feeling that the easy stuff is too easy
 and the hard stuff is too hard.

 Someone did point out that 'intermediate' programming would still
 involve actually selling code or at least some professional
 experience, so this would probably fall into the category of 'novice'.

 I feel similarly right now and the cs 101 classes from udacity or
 coursera or the opencourseware stuff are very easy and boring. I tried
 the class design of computer programs on udacity and made it about
 halfway before being overwhelmed. The class involved making an api for
 a regex-like function to parse text (if I am communicating that
 correctly, it was sort of rewriting regex functionality in Python
 terms), and it seemed to go over a very definite cliff in terms of
 difficulty. Could someone provide a concise example of decorator use?

 Someone suggested projecteuler.net and I started blazing through
 things I had done before, when I realized this would be a good time to
 start more efficient practices instead of code that just happens to
 work and may be very inefficient.

 #sum all even fib seq integers under 4 million
 fibs = [1,2]
 sum = 0
 while fibs[-1]  400:
 nexty = fibs[-1] + fibs[-2]
 fibs.append(nexty)

 for xer in fibs:
 if xer%2 == 0:
 sum += xer
 print sum

 This gets the correct solution, but what would be ways to improve
 speed or use more complicated parts of Python to do the same thing.
 Thanks in advance
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How inefficient is this code?

2014-05-07 Thread C Smith
I guess intuiting efficiency doesn't work in Python because it is such
high-level? Or is there much more going on there?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Stephen Mik-Novice Python Programmer(Version 3.4.0)Can't get help using Dictionaries, Lists to 'Hangman Game Problem

2014-05-05 Thread C Smith
Stephen, respond to the list so someone with more experience can help
you. I am still learning a lot about Python, but when over-generalized
questions are asked, I can tell that more experienced tutor-members
will not be able to help you much unless you can learn to frame the
questions correctly. You will notice this trend on many forums or
mailing lists not even related to Python. Sites like stackoverflow.com
(another great resource) will follow similar trends.

One thing you could do is post the code from hangman.py. Some people
will be averse to downloading even a .py file for various reasons, so
you are more likely to get a response by posting the entire code in
PLAIN TEXT. Right now your text is not plain text and will make it
hard to copy/paste or indent code properly.

If the instructor said you can use the code, use it. Changing variable
names should take about 5 seconds, as long as you have at least
feigned interest in the class. If changing variable names sounds
daunting, don't feel hopeless, you have just not been exposed to it
before. Adding a dictionary does not have to change the program
dramatically. You could even just add a minor functionality like
keeping track of score for players and not change the major parts of
the program.

Earlier you said: 'embedded while lists'.
Did you mean 'embedded while loop'?
If you can have a flash drive for the final, could you load it up with
Python reference material? If you can, make sure it is in a format
that you are comfortable searching and understanding. If you try to
cheat in programming, it will be easy to tell if the instructor
decides to ask you about your code.

On Mon, May 5, 2014 at 12:19 PM, Stephen Mik mik.step...@yahoo.com wrote:
 Stephen Mik-hung-up on Hangman Python code, pseudo code,worries about
 using Dictionaries,Lists.embedded while lists,for loops:
 Thank you,. C. Smith for responding to my help plea on Python-Tutor.org. One
 version of the Hang Man problem is listed in the textbook,but it doesn't
 use Dictionaries,Lists,embedded while lists;so I am fairly flummoxed as to
 what is needed in the pseudo code,or Python code. If I just copy the code
 from the Textbook,I am afraid that I will not learn very much about the
 Algorithm used to guess the scrambled word in Hang Man.The program
 assignment does not require a GUI to the screen,just printing words and some
 primitive ASCII Graphics of a man being hung if the word is not guessed in
 time. The instructor says we can use the code for the Hangman.py at the back
 of the chapter,but must of course change the variable names and add
 Dictionaries,Lists,etc. Another program is due by May 13,2014(A Tic-Tac-Toe
 program,which has MANY functions. And to top it off,the Final Exam is
 scheduled for Thursday,May 15,2014. In the Final we are NOT allowed textbook
 or class notes,just a Flash Drive and a Python interpreter. Anything else
 ,including looking up help on the Internet,is strictly forbidden.You talk
 about pressure,I sure feel it now! SWM
 On Sunday, May 4, 2014 4:45 PM, C Smith illusiontechniq...@gmail.com
 wrote:
 Hey, you will want to include some code to show your progress so far.
 Can you write a basic program and then work the requirements into it?
 Do you have some idea of where to start? Are you supposed to modify a
 completed version of hangman that is in your text, or come up with
 an original 'hangman' program? Does the hangman game need a graphical
 interface, or is just printing words to the screen fine?

 On Sun, May 4, 2014 at 7:17 PM, Stephen Mik
 mik.step...@yahoo.com.dmarc.invalid wrote:
 Dear Python World:
I am almost brand new to Python 3.4.0 and am taking a beginning Python
 Programming class at the nearby Community College. One major problem I
 have
 is time management with beginning pseudo code and coding for my Class
 Assignments. The instructor prefers Office Hour help,and does not respond
 to
 email.
One of my Class Assignments due on May 9,2014 deals with making a
 version of the Hangman Game which I'm sure somebody out there is
 familiar
 with. The program problem says to use 1.Dictionaries 2. Lists 3.Embedded
 While lists 4.for loops and more. I can refer to the Textbook for the
 class
 to get a basic idea of what some of the code will look like,but I cannot
 fathom how to use a Dictionary or List  in order to enhance the Basic
 Hangman Game Problem in the text  (written by Michael Dawson). The Text
 does
 cover Dictionaries,Lists,While Loops,For Loops but doesn't
 amplify
 and show with examples how some of these Data Structures can be used. And
 my
 instructor's Assignment directions are very terse and you do it by
 yourself.
If I can't get some ideas and hints from the Python Community by
 Monday,May 5,2014, I will have to hold off this difficult  programming
 assignment until Tuesday,May 6,2014 when the instructor will be available
 to
 help. That leaves me just 3 days to pseudocode,code in Python,fix syntax
 and
 run-time and Logical

Re: [Tutor] Stephen Mik-Novice Python Programmer(Version 3.4.0)Can't get help using Dictionaries, Lists to 'Hangman Game Problem

2014-05-04 Thread C Smith
Hey, you will want to include some code to show your progress so far.
Can you write a basic program and then work the requirements into it?
Do you have some idea of where to start? Are you supposed to modify a
completed version of hangman that is in your text, or come up with
an original 'hangman' program? Does the hangman game need a graphical
interface, or is just printing words to the screen fine?

On Sun, May 4, 2014 at 7:17 PM, Stephen Mik
mik.step...@yahoo.com.dmarc.invalid wrote:
 Dear Python World:
 I am almost brand new to Python 3.4.0 and am taking a beginning Python
 Programming class at the nearby Community College. One major problem I have
 is time management with beginning pseudo code and coding for my Class
 Assignments. The instructor prefers Office Hour help,and does not respond to
 email.
 One of my Class Assignments due on May 9,2014 deals with making a
 version of the Hangman Game which I'm sure somebody out there is familiar
 with. The program problem says to use 1.Dictionaries 2. Lists 3.Embedded
 While lists 4.for loops and more. I can refer to the Textbook for the class
 to get a basic idea of what some of the code will look like,but I cannot
 fathom how to use a Dictionary or List  in order to enhance the Basic
 Hangman Game Problem in the text  (written by Michael Dawson). The Text does
 cover Dictionaries,Lists,While Loops,For Loops but doesn't amplify
 and show with examples how some of these Data Structures can be used. And my
 instructor's Assignment directions are very terse and you do it by
 yourself.
 If I can't get some ideas and hints from the Python Community by
 Monday,May 5,2014, I will have to hold off this difficult  programming
 assignment until Tuesday,May 6,2014 when the instructor will be available to
 help. That leaves me just 3 days to pseudocode,code in Python,fix syntax and
 run-time and Logical errors before I can turn it in by Friday,May 16,2014.
 The instructor will only probably give me a suggestion and not some tangible
 ideas.Any thoughts out there about how to implement the Loops and Data
 Structures into a Hangman Game programming problem?
 SINCERELY,Stephen W. Mik

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

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


Re: [Tutor] Alice_in_wonderland Question

2014-05-04 Thread C Smith
ordered_keys = word_count.keys()
sorted(ordered_keys)

sorted() does not modify the list, but returns a sorted version of the
list for me on Python 2.7
my_sorted_list = sorted(ordered_keys)
This will alphabetize all of the words, regardless of frequency.

print (All the words and their frequency in, 'alice in wonderland')
for k in ordered_keys:

for k in my_sorted_keys:

print (k, word_count[k])

This will still print out all the words alphabetically, regardless of frequency.
Maybe you could have a different dictionary for each value, for
example, a dictionary of all the words that appear once, twice, three
times.

By 'asking the user for input information' do you mean so they could
pass any txt file into the program to be sorted?

On Sun, May 4, 2014 at 5:04 PM, Jake Blank jakenbl...@gmail.com wrote:
 Hi,
 So I'm doing a problem on the Alice_in_wonderland.txt where I have to write
 a program that reads a piece of text from a file specified by the user,
 counts the number of occurrences of each word, and writes a sorted list of
 words and their counts to an output file. The list of words should be sorted
 based on the counts, so that the most popular words appear at the top. Words
 with the same counts should be sorted alphabetically.

 My code right now is

 word_count = {}
 file = open ('alice_in_wonderland.txt', 'r')
 full_text = file.read().replace('--',' ')
 full_text_words = full_text.split()

 for words in full_text_words:
 stripped_words = words.strip(.,!?'`\- ();:)
 try:
 word_count[stripped_words] += 1
 except KeyError:
 word_count[stripped_words] = 1

 ordered_keys = word_count.keys()
 sorted(ordered_keys)
 print (All the words and their frequency in, 'alice in wonderland')
 for k in ordered_keys:
 print (k, word_count[k])

 The Output here is just all of the words in the document NOT SORTED by
 amount of occurrence.
 I need help sorting this output of words in the Alice_in_wonderland.txt, as
 well as help asking the user for the input information about the files.

 If anyone could give me some guidance you will really be helping me out.

 Please and Thank you




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

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


Re: [Tutor] converting strings to float: strange case

2014-04-28 Thread C Smith
.split() will split things based on whitespace or newlines. Do you know
that your file is only going to contain things that should convert to
floats? If you post your entire code, the error you have included will be
more helpful as it points to a certain line. The last line in your code has
(stri) should be (str).


On Mon, Apr 28, 2014 at 11:13 AM, Gabriele Brambilla 
gb.gabrielebrambi...@gmail.com wrote:

 Hi,

 I'm trying to convert a string to a float. It seems a basic thing but I
 don't know why I'm getting this erroris

 Traceback (most recent call last):
   File phresREADER.py, line 27, in module
 tra = float(stri)
 ValueError: could not convert string to float:

 My file has this line

 5.5e+000 5.5e+001 5.5e+002 5.5e+003

 my code is:

 my_line = f.readline()
 avg_energySTR = [str(i) for i in my_line.split(' ')]
 for stri in avg_energySTR:
 tra = float(stri)

 do you have any idea?

 thanks

 Gabriele

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


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


  1   2   3   4   5   >