Re: [Tutor] How to close a Tkinter window from a different thread?

2015-04-20 Thread Alan Gauld

On 20/04/15 04:34, boB Stepp wrote:


So, how do I:
1) Check for the existence of an already open window from a previous
running of the script?
2) If such a window exists, how do I close it from the new script
execution? And, then, of course generate a new instance of the
information window.


I would suggest forgetting about windows and think about
the processes that create them. Use the OS tools (via
the os module) to see if the first process is still running.
If so kill the process - which will in turn kill the window.

You can find the process based on its name or based on
its PID which you could store in a file somewhere
(like in /tmp?)


I feel the solution must be in Tkinter's access to the X Window
system, but nothing in the documentation is *clicking* with me yet.


Trying to manipulate GUIs via the windowing system should always
be a last resort, it is very hard to get right.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] sample dictionairies

2015-04-20 Thread Jim Mooney
For randomly generating data which look like addresses, I use:

> http://www.generatedata.com/
>
> While it has 'export to programming language' as a feature, Python isn't
> one of the supported languages.  Which is fine.  It can export into comma
> separated values, and writing a Python program to construct a dictionary
> from comma separated values is easy.
>
> Laura
>

That's a great source, and I can generate dictionaries using the other
advice. If you don't request comma delimited, each record per line has   |
as a field delimiter, so making big dicts was easy. Naturally, I tried
emailing one of the addresses - aliq...@nunc.org - but it appears to be
dead ;')

Come to think of it, since I used  |  as a delimiter, what happens if you
generate a CSV file from data that already has commas in the text?

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


[Tutor] Life Grid Implementation

2015-04-20 Thread niy mor
Is my code completing the assignment??? I need some *guidance* on
completing my assignment.

My Assignment:
A sparse life grid is used to store and represent the area in the game of
Life that contains organisms. The grid contains a rectangular grouping of
cells divided into an infinite number of rows and columns. The individual
cells, which can be alive or dead, are referenced by integer row and column
indices. The operations defined for the ADT are as follows:
• SparseLifeGrid() Creates a new infinite-sized game grid with all cells
initially dead.
 • minRange() Returns a 2-tuple (minrow, mincol) that contains the minimum
row index and the minimum column index that is currently occupied by a live
cell. The tuple (0, 0) is returned if there are no live cells.
 • maxRange() Returns a 2-tuple (maxrow, maxcol) that contains the maximum
row index and the maximum column index that is currently occupied by a live
cell. The tuple (0, 0) is returned if there are no live cells.
 • clearCell(row, col) Clears the individual cell (row, col) and sets it to
dead. If the cell is already dead, no action is taken.
 • setCell(row, col) Sets the indicated cell (row, col) to be alive. If the
cell is already alive, no action is taken.
 • isLiveCell(row, col) Returns a Boolean value indicating if the given
cell (row, col) contains a live organism.
• numLiveNeighbors(row, col) Returns the number of live neighbors for the
given cell (row, col). The neighbors of a cell include all of the cells
immediately surrounding it in all directions.

My Attempt Code:
class SparseLifeGrid :

Cell = ["row", "col"]

def __init__( self ):
self._rowList = []
self._colList = []
self._cellSet = set()

def _binarySearch( self, target ) :
low = 0
high = len(self._cellSet - 1)
while low <= high :
mid = (high + low) // 2
if theList[mid] == target :
return (True, mid)
elif target < theList[mid] :
high = mid - 1
else :
low = mid + 1

return (False, low)


def minRange( self ):
return (sorted(self._rowList)[0], sorted(self._rowList)[0])

def maxRange( self ):
return (sorted(self._rowList, reverse = True)[0],\
sorted(self._colList, reverse = True)[0])


 # Clears the individual cell (row, col) and sets it to dead. If the
cell is
 # already dead, no action is taken
def clearCell( self, row, col ):
for item in self :
if item == Cell(row, col) :
self.remove(item)

def setCell( self, row, col ):
LIVE_CELL = 1
Cell[row, col] = LIVE_CELL

def isLiveCell( self, row, col):
return Cell(row,col) in self

def numLiveNeighbors( self, row, col ):
surround = 0
if self.isLiveCell(row + 1, col) :
surround += 1
if self.isLiveCell(row - 1, col) :
surround += 1
if self.isLiveCell(row, col + 1) :
surround += 1
if self.isLiveCell(row, col - 1) :
surround += 1
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sample dictionairies

2015-04-20 Thread Alan Gauld

On 20/04/15 04:49, Jim Mooney wrote:


Come to think of it, since I used  |  as a delimiter, what happens if you
generate a CSV file from data that already has commas in the text?


The CSV format covers that eventuality: You put quotes around the
item with the comma.
And if there are already quotes?
And if there are newlines inside one of the fields?

Its all covered in the CSV spec.

Which is why you should use the csv module to work with csv files,
it knows how to deal with these various exceptional cases.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Life Grid Implementation

2015-04-20 Thread Ben Finney
niy mor  writes:

> Is my code completing the assignment???

Does it meet the requirements when you (and other people) run the code?

> I need some *guidance* on completing my assignment.

Can you be specific about what you don't understand?

If you don't understand the requirements, that is best discussed with
your course supervisor, not us.

-- 
 \   “Kissing a smoker is like licking an ashtray.” —anonymous |
  `\   |
_o__)  |
Ben Finney

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


Re: [Tutor] Life Grid Implementation

2015-04-20 Thread Alan Gauld

On 20/04/15 01:36, niy mor wrote:

Is my code completing the assignment???


No.


I need some *guidance* on
completing my assignment.


Try running your code.
Then fix the errors.
If you can't fix them come back to us and ask for help,
including the error message and a description of what
happened and what you expected.


My Attempt Code:
class SparseLifeGrid :

 Cell = ["row", "col"]


What is this for?


 def __init__( self ):
 self._rowList = []
 self._colList = []
 self._cellSet = set()

 def _binarySearch( self, target ) :
 low = 0
 high = len(self._cellSet - 1)
 while low <= high :
 mid = (high + low) // 2
 if theList[mid] == target :
 return (True, mid)
 elif target < theList[mid] :
 high = mid - 1
 else :
 low = mid + 1

 return (False, low)


This just tells you which half the item is in.
Is that what you wanted?


 def minRange( self ):
 return (sorted(self._rowList)[0], sorted(self._rowList)[0])


This returns the same value twice.


 def maxRange( self ):
 return (sorted(self._rowList, reverse = True)[0],\
 sorted(self._colList, reverse = True)[0])


You don;t need the line continuation character (/) if you are inside parens.

def f():
   return (expression1,
   expression2)


  # Clears the individual cell (row, col) and sets it to dead. If the
cell is
  # already dead, no action is taken
 def clearCell( self, row, col ):
 for item in self :
 if item == Cell(row, col) :
 self.remove(item)


How do you expect to iterate over self? self is your class instance
but it has nothing to iterate over?


 def setCell( self, row, col ):
 LIVE_CELL = 1
 Cell[row, col] = LIVE_CELL


Here you create a new Cell instance then try to assign a value to it, 
then throw it away. I'm pretty sure thats not what you want.



 def isLiveCell( self, row, col):
 return Cell(row,col) in self


Again how are you testing 'in' self. There is nothing in
your class to support that.



 def numLiveNeighbors( self, row, col ):
 surround = 0
 if self.isLiveCell(row + 1, col) :
 surround += 1
 if self.isLiveCell(row - 1, col) :
 surround += 1
 if self.isLiveCell(row, col + 1) :
 surround += 1
 if self.isLiveCell(row, col - 1) :
 surround += 1


How many neighbours does a cell have in a Life grid?
Is it only 4?


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] sample dictionairies

2015-04-20 Thread Mark Lawrence

On 20/04/2015 04:49, Jim Mooney wrote:

For randomly generating data which look like addresses, I use:


http://www.generatedata.com/

While it has 'export to programming language' as a feature, Python isn't
one of the supported languages.  Which is fine.  It can export into comma
separated values, and writing a Python program to construct a dictionary
from comma separated values is easy.

Laura



That's a great source, and I can generate dictionaries using the other
advice. If you don't request comma delimited, each record per line has   |
as a field delimiter, so making big dicts was easy. Naturally, I tried
emailing one of the addresses - aliq...@nunc.org - but it appears to be
dead ;')

Come to think of it, since I used  |  as a delimiter, what happens if you
generate a CSV file from data that already has commas in the text?



For those who don't know you can use any character as the delimiter and 
any character as the quote, see 
https://docs.python.org/3/library/csv.html#csv.reader


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: [Tutor] How to close a Tkinter window from a different thread?

2015-04-20 Thread boB Stepp
On Mon, Apr 20, 2015 at 2:10 AM, Alan Gauld  wrote:
> On 20/04/15 04:34, boB Stepp wrote:
>
>> So, how do I:
>> 1) Check for the existence of an already open window from a previous
>> running of the script?
>> 2) If such a window exists, how do I close it from the new script
>> execution? And, then, of course generate a new instance of the
>> information window.
>
>
> I would suggest forgetting about windows and think about
> the processes that create them. Use the OS tools (via
> the os module) to see if the first process is still running.
> If so kill the process - which will in turn kill the window.

I started poking around a little in this area in my books, but did not
know if this was the way to go or not. I was still hung up on how to
identify the correct process...

> You can find the process based on its name or based on
> its PID which you could store in a file somewhere
> (like in /tmp?)

I was thinking in these terms from a Tkinter window id perspective,
but storing the PID while the original window is known to be open
looks like the way to go. Thanks, Alan! I may have more questions on
this later as I have not explicitly worked with this via Python. I've
only killed processes via the command line before.

>> I feel the solution must be in Tkinter's access to the X Window
>> system, but nothing in the documentation is *clicking* with me yet.
>
>
> Trying to manipulate GUIs via the windowing system should always
> be a last resort, it is very hard to get right.

If I am learning nothing else from my exploration of GUI programming,
this is becoming ever more evident!

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


[Tutor] bin to dec conversion puzzlement

2015-04-20 Thread Jim Mooney
I can't seem to get my head around this 'simple' book example of
binary-to-decimal conversion, which goes from left to right:

B = '11011101'
I = 0
while B:
I = I * 2 + int(B[0])
B = B[1:]

print(I)
>>> 221

My thought was to go from right to left, multiplying digits by successive
powers of two, and adding, like so:

B = '11011101'
sum = 0

for exp, num in enumerate(reversed(B)):
sum += int(num) * 2**exp

print(sum)
>> 221

Both methods work but I just can't see how the first one does. Am I missing
something obvious here?

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


Re: [Tutor] How to close a Tkinter window from a different thread?

2015-04-20 Thread Laura Creighton
In a message of Mon, 20 Apr 2015 08:10:38 +0100, Alan Gauld writes:

>Trying to manipulate GUIs via the windowing system should always
>be a last resort, it is very hard to get right.

And the hardness increases exponentially if you want to be portable
across different operating systems.

Laura

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


Re: [Tutor] sample dictionairies

2015-04-20 Thread Jim Mooney
> Which is why you should use the csv module to work with csv files,
> it knows how to deal with these various exceptional cases.
> --
> Alan G
>

I should have known to simply try importing csv.
Must-remember-batteries-included ;')

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


Re: [Tutor] OT: Is there a good book that covers the history/evolution of software? [Inspired by the thread: lists, name semantics]

2015-04-20 Thread Laura Creighton
Newman, W., Sproull, R. (1979), Principles of Interactive Computer Graphics, 
Mcgraw-Hill College, ISBN 0-07-046338-7

is a very good read.  It is understandably dated, but then it was
history that you were looking for.  And the book has 2 parts -- a
history of the computer architectures we had (in 1979) and then
the part on how to make grapical programs on them.

Laura

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


Re: [Tutor] sample dictionairies

2015-04-20 Thread Laura Creighton
In a message of Sun, 19 Apr 2015 20:49:27 -0700, Jim Mooney writes:
>Come to think of it, since I used  |  as a delimiter, what happens if you
>generate a CSV file from data that already has commas in the text?
>
>-- 
>Jim

In Sweden, and lots of other places, we do numbers differently.
This is One thousand dollars and 43 cents. 1.000,43

Lots of the time you write that as 1000,43  same as in English you
get 1000.43 and 1,000.43.

So we tend to use comma separated values around here that are really
semi-colon separated values.  But I do not know how widespread that usage
is.

Laura

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


Re: [Tutor] Life Grid Implementation

2015-04-20 Thread niyana morgan
I don't understand how to do this. I attempted with my code and hoped a
tutor could help me with this
On Apr 20, 2015 3:31 AM, "Ben Finney"  wrote:

> niy mor  writes:
>
> > Is my code completing the assignment???
>
> Does it meet the requirements when you (and other people) run the code?
>
> > I need some *guidance* on completing my assignment.
>
> Can you be specific about what you don't understand?
>
> If you don't understand the requirements, that is best discussed with
> your course supervisor, not us.
>
> --
>  \   “Kissing a smoker is like licking an ashtray.” —anonymous |
>   `\   |
> _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


[Tutor] Please Help to build an addon for Anki

2015-04-20 Thread Mahesh Chiramure
Hi

I liked the addon "Picture-flasher" written for anki very much
and I was wondering if the same thing could be done with mp3 and/or
flac files. Means I am looking for an addon that chooses a random mp3
and/or flac file from a directory provided by me (to the addon as we
have to provide in "Picture-flasher") and plays it on successful
reviewing of a certain number of cards (as does the addon
"Picture-flasher"). As a music lover, I feel that this addon can
motivate a whole lot of music lovers out there to pay a visit to Anki
on their PC and review to listen to their favorite mp3 and/or flac
files as a reward.

I am not a programmer yet, please guide.

Hoping for a quick response.

Mahesh Chirmure
# -*- coding: utf-8 -*-
# Picture-Flasher (a plugin for Anki)
# Authors:
#   Emanuel Rylke, ema-...@web.de
#   D_Malik, malik6...@gmail.com
# Version 2
# License: GNU GPL, version 3 or later; http://www.gnu.org/copyleft/gpl.html

"""
A simple plugin that flashes pictures on-screen to reinforce reviews.

Before using:
- Get pictures from someplace. I downloaded pictures off reddit using the 
script at https://github.com/dpbrown/RedditImageGrab
- Change all lines (in the plugin source) marked with "CHANGEME" according to 
your preferences.

For more details, see the post at For more details, see the post at 
http://lesswrong.com/r/discussion/lw/frc/two_anki_plugins_to_reinforce_reviewing/
"""

from anki.hooks import addHook
from aqt import mw
from random import random, choice
from aqt.qt import QSplashScreen, QPixmap, QTimer
from os import listdir

#-- begin configuration --#
pictureDirectory = "E://Family stuff//22 Feb//Personal//College//A J//" 
#CHANGEME to the directory where you're storing your pictures. NB: This MUST 
end with a trailing slash e.g. D://Family stuff//19 Jan//Imgs//Wallys//, 
D://Family stuff//22 Feb//Imgs//Windows 7//.

flashTime = 3000 #CHANGEME to change how long pictures stay on the screen. The 
number is time in milliseconds.

#flashPosition = [20, 1050] #CHANGEME if you want the picture to be shown at a 
specific location. The numbers are x- and y-coordinates.

#CHANGEME: The next lines are a python dictionary associating deck names 
with probabilities of pictures being shown.
#Eg, when using the deck "brainscience", you will get a picture after 30% 
of cards. When using a deck without a listed name, "other" is used.
#Change this according to your decks. Decks with shorter, easier cards need 
lower probabilities.
deckPicsProbabilities = {
"rocketsurgery":   0.3,
"brainscience" :   0.5,
"other":   0.1,
}
#--- end configuration ---#

pics = listdir(pictureDirectory)

def showPics():
if mw.col.decks.current()['name'] in deckPicsProbabilities:
picsProbability = deckPicsProbabilities[mw.col.decks.current()['name']]
else:
picsProbability = deckPicsProbabilities["other"]

if random() < picsProbability:
mw.splash = QSplashScreen(QPixmap(pictureDirectory + choice(pics)))
try:
mw.splash.move(flashPosition[0], flashPosition[1])
except NameError:
pass
mw.splash.show()
QTimer.singleShot(flashTime, mw.splash.close)

addHook("showQuestion", showPics)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] bin to dec conversion puzzlement

2015-04-20 Thread Marc Tompkins
On Apr 20, 2015 6:56 AM, "Jim Mooney"  wrote:
>
> I can't seem to get my head around this 'simple' book example of
> binary-to-decimal conversion, which goes from left to right:
>
> B = '11011101'
> I = 0
> while B:
> I = I * 2 + int(B[0])
> B = B[1:]
>
> print(I)
> >>> 221
>
> My thought was to go from right to left, multiplying digits by successive
> powers of two, and adding, like so:
>
> B = '11011101'
> sum = 0
>
> for exp, num in enumerate(reversed(B)):
> sum += int(num) * 2**exp
>
> print(sum)
> >> 221
>
> Both methods work but I just can't see how the first one does. Am I
missing
> something obvious

Start from 0.
As long as there are any digits left,
a) Multiply by 2, add the leftmost digit.
b) Chop off the leftmost digit.
Lather, rinse, repeat.

It _does_ seem counterintuitive to do it from the left, but it's actually
quite simple.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] bin to dec conversion puzzlement

2015-04-20 Thread Oscar Benjamin
On 20 April 2015 at 08:44, Jim Mooney  wrote:
> I can't seem to get my head around this 'simple' book example of
> binary-to-decimal conversion, which goes from left to right:
>
> B = '11011101'
> I = 0
> while B:
> I = I * 2 + int(B[0])
> B = B[1:]


Follow through the loop and see what happens. To begin I is zero and B
is the full string. Consider B_orig to be the original string. After
the first iteration we have that
 I = B[0]   and   B = B_orig[1:]
then
 I = 2*B[0] + B[1]  and B = B_orig[2:]
then
I = 2*(2*B[0] + B[1]) + B[2]  = 4*B[0] + 2*B[1] + B[2]
then
I = 8*B[0] + 4*B[1] + 2*B[2] + B[3]
and eventually
I = 128*B[0] + 64*B[1] + ... + 2*B[6] + B[7]
which is the desired result.


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


[Tutor] introspection

2015-04-20 Thread Alex Kleider
Does python provide the introspective ability to retrieve the name to 
which an object is bound?


For example:
$ python3
Python 3.4.0 (default, Apr 11 2014, 13:05:18)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.

a = 69
print("Identifier <{}> is bound to {}.".format(a.__name__, a))

Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'int' object has no attribute '__name__'





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


Re: [Tutor] introspection

2015-04-20 Thread Joel Goldstick
On Mon, Apr 20, 2015 at 11:24 AM, Alex Kleider  wrote:
> Does python provide the introspective ability to retrieve the name to which
> an object is bound?
>
> For example:
> $ python3
> Python 3.4.0 (default, Apr 11 2014, 13:05:18)
> [GCC 4.8.2] on linux
> Type "help", "copyright", "credits" or "license" for more information.

 a = 69
 print("Identifier <{}> is bound to {}.".format(a.__name__, a))
>
> Traceback (most recent call last):
>   File "", line 1, in 
> AttributeError: 'int' object has no attribute '__name__'
>
>
An object can be bound to multiple names.  Within a namespace you can
use locals to see names, then compare various names like so:
>
>>> a = 3
>>> b = 6
>>> c = a
>>> locals()
{'a': 3, 'c': 3, 'b': 6, '__builtins__': , '__package__': None, '__name__': '__main__', '__doc__':
None}
>>> a is b
False
>>> a is c
True
>>>

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



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


Re: [Tutor] Life Grid Implementation

2015-04-20 Thread Alan Gauld

On 20/04/15 13:59, niyana morgan wrote:

I don't understand how to do this. I attempted with my code and hoped a
tutor could help me with this


Always write code that runs. Then fix the mistakes as they
happen. That way you only have a few lines of code to look
at. Your code is far too big and intertwined to be able
to debug easily.

Look at your specification:
• SparseLifeGrid() Creates a new infinite-sized game grid
   with all cells initially dead.
...
 • clearCell(row, col) Clears the individual cell (row, col)
   and sets it to dead. If the cell is already dead, no action
   is taken.
 • setCell(row, col) Sets the indicated cell (row, col)
   to be alive. If the cell is already alive, no action is taken.


I suggest you start over with a class definition and an init().
See if you can create an instance and if it has the
fields you expect. Thats your first API bullet done.

Once you can do that create the methods needed to populate
it with data (setCell()) and clear a cell(clearCell()).
Nothing else, just those two methods. Get them working.
Now you have three parts of your assignment done.

Only when you can do those things correctly attempt one of the remaining 
API methods - maybe the isLiveCell() method.


Then try minRange and maxRange after that.

Finally you can try numLiveNeighbours confident that the
rest of the class works.

Always run the code. Every time you complete a method
your code should work. If you write your tests as code
in a function, that function should always work even
after you complete a new stage. If anything that used
to work stops working, go back and fix it before trying
anything new. The code you changed will still be fresh
in your mind.

If you really get stuck come back here and ask.
Always copy any error messages in full.

HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] bin to dec conversion puzzlement

2015-04-20 Thread Alan Gauld

On 20/04/15 08:44, Jim Mooney wrote:

I can't seem to get my head around this 'simple' book example of
binary-to-decimal conversion, which goes from left to right:

B = '11011101'
I = 0
while B:
 I = I * 2 + int(B[0])
 B = B[1:]

...

Both methods work but I just can't see how the first one does.


The key is that the result gets multiplied by 2 each time
so for an N bit number the leftmost digit winds up being
effectively 2**N, which is what you want.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Please Help to build an addon for Anki

2015-04-20 Thread Alan Gauld

On 20/04/15 09:54, Mahesh Chiramure wrote:


I liked the addon "Picture-flasher" written for anki very much
and I was wondering if the same thing could be done with mp3 and/or
flac files.


Probably, but I (and probably most of the list) have no idea what anki 
is or what the addon does. This is a list for learning Python and its 
standard library. You could try asking on the general Python 
mailinglist/newsgroup where you might find someone familiar with it.


If you do try that you sould try explaining what anki is,
and what the addon does. ie how it 'adds on'.

Better still is if you can find an anki forum, since they will 
understand anki, addons and probably be familiar with the PictureFlasher 
one you describe.



--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] introspection

2015-04-20 Thread Alex Kleider

On 2015-04-20 09:15, Joel Goldstick wrote:
On Mon, Apr 20, 2015 at 11:24 AM, Alex Kleider  
wrote:
Does python provide the introspective ability to retrieve the name to 
which

an object is bound?

For example:
$ python3
Python 3.4.0 (default, Apr 11 2014, 13:05:18)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.


a = 69
print("Identifier <{}> is bound to {}.".format(a.__name__, a))


Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'int' object has no attribute '__name__'



An object can be bound to multiple names.  Within a namespace you can
use locals to see names, then compare various names like so:



a = 3
b = 6
c = a
locals()

{'a': 3, 'c': 3, 'b': 6, '__builtins__': , '__package__': None, '__name__': '__main__', '__doc__':
None}

a is b

False

a is c

True


Showing my desired use case might make my question more understandable:
def debug(var_name):
if args["--debug"]:
print("Identifier <{}> is bound to: {}"
.format(var_name.__name__, repr(var_name)))
I don't think the built in locals() can help me.
Thanks all the same.
Alex


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


Re: [Tutor] bin to dec conversion puzzlement

2015-04-20 Thread Alex Kleider

On 2015-04-20 09:21, Alan Gauld wrote:

On 20/04/15 08:44, Jim Mooney wrote:

I can't seem to get my head around this 'simple' book example of
binary-to-decimal conversion, which goes from left to right:

B = '11011101'
I = 0
while B:
 I = I * 2 + int(B[0])
 B = B[1:]

...

Both methods work but I just can't see how the first one does.


The key is that the result gets multiplied by 2 each time
so for an N bit number the leftmost digit winds up being
effectively 2**N, which is what you want.


Shouldn't that be 2**(N-1)?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] bin to dec conversion puzzlement

2015-04-20 Thread eryksun
On Mon, Apr 20, 2015 at 11:21 AM, Alan Gauld  wrote:
>>
>> B = '11011101'
>> I = 0
>> while B:
>>  I = I * 2 + int(B[0])
>>  B = B[1:]
>
>> Both methods work but I just can't see how the first one does.
>
> The key is that the result gets multiplied by 2 each time
> so for an N bit number the leftmost digit winds up being
> effectively 2**N, which is what you want.

The loop iterates N times, so the leftmost digit is multiplied by 2 a
total of N - 1 times, i.e. B[0] * 2 ** (N - 1).

Another way to see this is that multiplying by 2 is a bitwise left
shift. Thus you can replace the multiplication and addition with
bitwise operations as follows:

B = '11011101'
I = 0
while B:
I = (I << 1) | int(B[0], 2)
B = B[1:]
   assert I == 221

Shifting the values in like this may be more intuitively obvious.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] bin to dec conversion puzzlement

2015-04-20 Thread Alan Gauld

On 20/04/15 17:58, Alex Kleider wrote:


The key is that the result gets multiplied by 2 each time
so for an N bit number the leftmost digit winds up being
effectively 2**N, which is what you want.


Shouldn't that be 2**(N-1)?


Yes, sorry.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] introspection

2015-04-20 Thread Steven D'Aprano
On Mon, Apr 20, 2015 at 08:24:42AM -0700, Alex Kleider wrote:
> Does python provide the introspective ability to retrieve the name to 
> which an object is bound?

Short answer: no.

Slightly longer answer: it *may* be possible if you dig deep into the 
debugger API that you might find something which does what you want. I'm 
not saying that it will, only that if it exists, the debugger seems like 
the most likely place.

But... probably not.

In any case, even if you find something that will do this, it will be 
implementation-specific (e.g. Jython only, or IronPython only, or 
CPython only, but not all three) and probably rather dubious. After all, 
any object may have zero, one or more names, in completely different 
scopes. The whole idea of "what name does this object have" is rather 
dubious. The best one can do is say "in this namespace (locals), does 
this object have any names?".


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


Re: [Tutor] introspection

2015-04-20 Thread Alan Gauld

On 20/04/15 17:55, Alex Kleider wrote:


locals()

{'a': 3, 'c': 3, 'b': 6, '__builtins__': , '__package__': None, '__name__': '__main__', '__doc__':
None}



Showing my desired use case might make my question more understandable:
def debug(var_name):
 if args["--debug"]:
 print("Identifier <{}> is bound to: {}"
 .format(var_name.__name__, repr(var_name)))
I don't think the built in locals() can help me.


Why not? Provided you pass the required scope into your function:

def debug(var_name, scope):
if args["--debug"]:
print("Identifier <{}> is bound to: {}"
  .format(var_name, scope.get(var_name, 'no object'))

debug('a',locals()) # look in local vars


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] introspection

2015-04-20 Thread Peter Otten
Alex Kleider wrote:

> On 2015-04-20 09:15, Joel Goldstick wrote:
>> On Mon, Apr 20, 2015 at 11:24 AM, Alex Kleider 
>> wrote:
>>> Does python provide the introspective ability to retrieve the name to
>>> which
>>> an object is bound?
>>> 
>>> For example:
>>> $ python3
>>> Python 3.4.0 (default, Apr 11 2014, 13:05:18)
>>> [GCC 4.8.2] on linux
>>> Type "help", "copyright", "credits" or "license" for more information.
>> 
>> a = 69
>> print("Identifier <{}> is bound to {}.".format(a.__name__, a))
>>> 
>>> Traceback (most recent call last):
>>>   File "", line 1, in 
>>> AttributeError: 'int' object has no attribute '__name__'
>>> 
>>> 
>> An object can be bound to multiple names.  Within a namespace you can
>> use locals to see names, then compare various names like so:
>>> 
> a = 3
> b = 6
> c = a
> locals()
>> {'a': 3, 'c': 3, 'b': 6, '__builtins__': > (built-in)>, '__package__': None, '__name__': '__main__', '__doc__':
>> None}
> a is b
>> False
> a is c
>> True
> 
> Showing my desired use case might make my question more understandable:
> def debug(var_name):
>  if args["--debug"]:
>  print("Identifier <{}> is bound to: {}"
>  .format(var_name.__name__, repr(var_name)))
> I don't think the built in locals() can help me.
> Thanks all the same.
> Alex

In CPython you can inspect the callstack, but remember that 

(1) it is a costly operation
(2) there are many variables bound to multiple names or none at all.

$ cat show_name_binding2.py 
import sys

def bindings_of(value, depth):
frame = sys._getframe(depth + 1)
bindings = [n for n, v in frame.f_locals.items() if v is value]
if bindings:
return bindings
return [""]

def debug(value):
print("{} is bound to {}".format(
value, ", ".join(bindings_of(value, 1

def main():
x = 42
y = 42

debug(42)
debug("foo")

a = "bar baz"
b = " ".join(a.split())
assert a == b
debug("bar baz")

if __name__ == "__main__":
main()
$ python3 show_name_binding2.py 
42 is bound to y, x
foo is bound to 
bar baz is bound to a


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


[Tutor] Is it possible to "backport" the datetime module of Python 3.3 to Python 3.2?

2015-04-20 Thread Albert-Jan Roskam
Hi,

My Raspberry Pi 2 comes with Python 3.2 (and 2.7). I run some code that uses 
the datetime module but I get an error:

"AttributeError: 'datetime.datetime' object has no attribute 'timestamp'". On 
https://docs.python.org/3/whatsnew/3.3.html I see: "New 
datetime.datetime.timestamp() method: Return POSIX timestamp corresponding to 
thedatetime instance." Is upgrading Python 3.3 or higher my only option, or is 
it somehow possible to use the newer version of the datetime library for Python 
3.2? I do not want to modify the source code of the library that causes the 
error (pysolar).

Thanks!

 
Regards,

Albert-Jan




~~

All right, but apart from the sanitation, the medicine, education, wine, public 
order, irrigation, roads, a 

fresh water system, and public health, what have the Romans ever done for us?

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


Re: [Tutor] sample dictionairies

2015-04-20 Thread Ben Finney
Jim Mooney  writes:

> I should have known to simply try importing csv.

Better: You should now know to refer to the documentation
https://docs.python.org/3/library/>.

-- 
 \  “Speech is conveniently located midway between thought and |
  `\action, where it often substitutes for both.” —John Andrew |
_o__)  Holmes, _Wisdom in Small Doses_ |
Ben Finney

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


Re: [Tutor] introspection

2015-04-20 Thread Ben Finney
Alex Kleider  writes:

> Does python provide the introspective ability to retrieve the name to
> which an object is bound?

Objects aren't bound to names. So, no.

The binding from a reference (a name is a reference) to objects is
one-way.

See this excellent presentation from PyCon US 2015 by Ned Batchelder
https://www.youtube.com/watch?v=_AEJHKGk9ns>.

-- 
 \ “I must say that I find television very educational. The minute |
  `\   somebody turns it on, I go to the library and read a book.” |
_o__)—Groucho Marx |
Ben Finney

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


Re: [Tutor] bin to dec conversion puzzlement

2015-04-20 Thread Ben Finney
Jim Mooney  writes:

> I can't seem to get my head around this 'simple' book example of
> binary-to-decimal conversion, which goes from left to right:
>
> B = '11011101'
> I = 0
> while B:
> I = I * 2 + int(B[0])
> B = B[1:]
>
> print(I)
> >>> 221

That is, IMO, a needlessly confusing way to write that code.

Whoever wrote it is clearly pleased with how clever it is; but
cleverness is almost always a property of *bad* code because it's
difficult to understand at a glance. That's the case here.

One significant problem with the code as written is that it uses a
‘while’ loop and mutates the list, where there's no point; it should
just iterate over items *from* the list without changing it.

Another significant problem is that it uses moronically-short,
completely unexpressive names. This is Python not FORTRAN.

Try this::

binary_text = '11011101'
result = 0

for binary_digit in binary_text:
# Accumulate powers of 2 for each digit.
result = result * 2 + int(binary_digit)

print(result)

> Both methods work but I just can't see how the first one does. Am I
> missing something obvious here?

No, you were missing something needlessly obscured by the badly-written
code. Which book is this? I will be sure never to recommend it.

Hope that helps.

-- 
 \ “Science is a way of trying not to fool yourself. The first |
  `\ principle is that you must not fool yourself, and you are the |
_o__)   easiest person to fool.” —Richard P. Feynman, 1964 |
Ben Finney

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


Re: [Tutor] bin to dec conversion puzzlement

2015-04-20 Thread Jim Mooney
 The key is that the result gets multiplied by 2 each time

> so for an N bit number the leftmost digit winds up being
> effectively 2**N, which is what you want.
>


> Alan G


Ah, the light dawns once it was restated. It would be even simpler if you
could multiply each element of the binary number by it's respective power
of two, and sum them all at once. I hear Py 3.5 will have vector abilities.
I wonder it if would do something like that.

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


Re: [Tutor] bin to dec conversion puzzlement

2015-04-20 Thread Dave Angel

On 04/20/2015 04:15 PM, Jim Mooney wrote:

  The key is that the result gets multiplied by 2 each time


so for an N bit number the leftmost digit winds up being
effectively 2**N, which is what you want.





Alan G



Ah, the light dawns once it was restated. It would be even simpler if you
could multiply each element of the binary number by it's respective power
of two, and sum them all at once. I hear Py 3.5 will have vector abilities.
I wonder it if would do something like that.


It's important to understand these conversion methods, or I would have 
earlier mentioned that you can convert from a binary string simply by


x = int("1011", 2)

No loop needed.


But if you need a loop for an analagous algorithm, find a way to either 
minimize the number of times through the loop, or to reduce the work 
done in each loop.


Ben's algorithm is much simpler than the one in the book you're reading.

binary_text = '11011101'
result = 0

for binary_digit in binary_text:
# Accumulate powers of 2 for each digit.
result = result * 2 + int(binary_digit)

print(result)

But more importantly, it's much simpler than calculating various powers 
of two and multiplying the various coefficients by them, and somehow 
"sum them all at once".



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


Re: [Tutor] How to close a Tkinter window from a different thread?

2015-04-20 Thread boB Stepp
On Mon, Apr 20, 2015 at 2:10 AM, Alan Gauld  wrote:
> On 20/04/15 04:34, boB Stepp wrote:
>
>> So, how do I:
>> 1) Check for the existence of an already open window from a previous
>> running of the script?
>> 2) If such a window exists, how do I close it from the new script
>> execution? And, then, of course generate a new instance of the
>> information window.
>
>
> I would suggest forgetting about windows and think about
> the processes that create them. Use the OS tools (via
> the os module) to see if the first process is still running.
> If so kill the process - which will in turn kill the window.
>
> You can find the process based on its name or based on
> its PID which you could store in a file somewhere
> (like in /tmp?)

I'm currently at home and cannot access Solaris, but I believe that
the following will do what I want:

import os
import signal
from tkinter import *

def kill():
os.kill(pid, signal.SIGKILL)

root = Tk()
pid = os.getpid()

btn = Button(root, text='Kill me!!!', command=kill)
btn.pack()
root.mainloop()

The process id would have to be stored persistently to do the real
deal, of course, as Alan suggested. I cannot make this example work in
Windows. As far as I can tell, signal.SIGKILL won't work with Windows.
If I replace it with 9, then it does work. If I have understood what I
have read to date, using signal.SIGKILL is preferable to using 9.

Some questions:

1) Is the placement of "pid = os.getpid()" critical? My thinking is
that I want to capture the pid of the root window, store it, and then
use it if I need to kill the root and any children it has in my actual
GUI display. If, say, I placed it immediately before
"root.mainloop()", would it do what I want? Of course, I plan to
experiment with this at work tomorrow. I'll also continue to play
around with it in Windows.

2) The other possibility was to use "os.getppid" and, I suppose,
"os.kill(ppid, signal.SIGKILL)". Would this be preferable? Or will
wreak some sort of havoc?

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


Re: [Tutor] introspection

2015-04-20 Thread Alex Kleider

On 2015-04-20 13:24, Ben Finney wrote:

Alex Kleider  writes:


Does python provide the introspective ability to retrieve the name to
which an object is bound?


Objects aren't bound to names. So, no.

The binding from a reference (a name is a reference) to objects is
one-way.

See this excellent presentation from PyCon US 2015 by Ned Batchelder
https://www.youtube.com/watch?v=_AEJHKGk9ns>.


But my code knows the name. The code is provided the name; I want the 
code to tell me that name.

..but it seems unable to do so.
;-(

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


Re: [Tutor] introspection

2015-04-20 Thread Danny Yoo
What's supposed to happen in this situation?


##
class Person(object):
def __init__(self): pass

j = Person()
john = j
jack = j
##

What single name should we get back from the single Person object
here?  "j", "john", or "jack"?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor