Changing the font size of anOptionMenu widget

2013-01-24 Thread Angel
I am changing the font of an OptionMenu widget:

w = OptionMenu(master, variable, "one", "two", "three")

with 

w.configure()

That changes the font of the widget but how can I change also the font (size) 
of the menu that appears when the mouse clicks it?

Thanks in advandce,

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


Re: Changing the font size of anOptionMenu widget

2013-01-25 Thread Angel
Den fredagen den 25:e januari 2013 kl. 06:57:00 UTC+1 skrev Rick Johnson:
> 
> menu = optMenu.nametowidget(optMenu.menuname)
> 
That was what I was missing, the '.nametowidget'. It worked like a charm:

o1=Tkinter.OptionMenu(t,v3, "€", "$")
o1.config(font=self.font)
o1.nametowidget(o1.menuname).config(font=self.font)

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


Fonts & Tinker

2013-01-25 Thread Angel
I am changing the default font for a Tkinter application:

class FuelControl(Tkinter.Frame):
def __init__(self,master):
self.version='0.02'
self.font=tkFont.Font(family="Helvetica",size=18) 
print self.font.actual()
.
.
.

and everything looks ok:

{'family': 'Nimbus Sans L', 'weight': 'normal', 'slant': 'roman', 'overstrike': 
0, 'underline': 0, 'size': 18}

and the size of the text are 18 on the screen. Then a button creates a new 
window through this callback:

def loc_add(self):
addw=Tix.Tk()
addw.title('Add location')
print self.font.actual()
Tkinter.Label(addw,text='Nickname:', 
font=self.font).grid(row=0,column=0)
Tkinter.Label(addw,text='Fullname:', 
font=self.font).grid(row=1,column=0)
Tkinter.Label(addw,text='Address:',  
font=self.font).grid(row=2,column=0)
Tkinter.Label(addw,text='Fuel 
name:',font=self.font).grid(row=3,column=0)
...

The self.font stays with the right value:

{'family': 'Nimbus Sans L', 'weight': 'normal', 'slant': 'roman', 'overstrike': 
0, 'underline': 0, 'size': 18}

but the real displayed fonts in the window are smaller (default size of 12, 
maybe).

Am I missing something?

Thanks in advance,
A.

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


Re: Fonts & Tinker

2013-01-25 Thread Angel
Dammm it should be Tkinter for subject..:D
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fonts & Tinker

2013-01-30 Thread Angel
THis one workd fine:

.option_add('*Font', "Heveltica 14") 

Thanks!

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


Python 2.6.1 + wxPython 2.8.9.1 compiled form source

2010-05-20 Thread Angel
Hi,

I have a Red Hat 4.6 machone and I compiled and installed python 2.6.1
from source.

Then, I compiled wxPython 2.8.9.1 form source too.

And then, when I try to run it:

# python
Python 2.6.1 (r261:67515, Mar  4 2009, 20:10:49)
[GCC 3.4.6 20060404 (Red Hat 3.4.6-10)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import wx
Aborted

Any hint? Anything I am missing? Anyhere to check? Read?

Thanks in advance.

This in my environment:

LD_LIBRARY_PATH=/opt/wxPython/2.8.9.1/lib:/opt/python/2.6.1/lib:/opt/
hpmpi/lib/linux_amd64:/opt/intel/cce/10.1.008/lib:/opt/intel/fce/
10.1.008/lib:/lib:/lib64:/usr/lib:/usr/lib64:/usr/X11R6/lib:/usr/X11R6/
lib64:/usr/local/lib:/usr/local/lib64
PATH=/opt/wxPython/2.8.9.1/bin:/opt/python/2.6.1/bin:/root/aaks/bin:/
opt/hpmpi/bin:/opt/intel/cce/10.1.008/bin:/opt/intel/fce/10.1.008/bin:/
usr/local/bin:/usr/local/X11/bin:/opt/torque/2.3.6/bin:/opt/torque/
2.3.6/sbin:/usr/java/jdk1.6.0_12/bin:/usr/local/sbin:/usr/local/bin:/
sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:/etc:/usr/etc:/usr/local/
etc:.:/opt/maui/3.2.6p21/sbin:/opt/maui/3.2.6p21/bin:/root/bin:/opt/
pdsh/2.17/bin
PYTHONPATH=/opt/wxPython/2.8.9.1:/opt/python/2.6.1

And.. a verbose output:

# python -vv
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# trying /opt/wxPython/2.8.9.1/site.so
# trying /opt/wxPython/2.8.9.1/sitemodule.so
# trying /opt/wxPython/2.8.9.1/site.py
# trying /opt/wxPython/2.8.9.1/site.pyc
# trying /opt/python/2.6.1/site.so
# trying /opt/python/2.6.1/sitemodule.so
# trying /opt/python/2.6.1/site.py
# trying /opt/python/2.6.1/site.pyc
# trying /opt/python/2.6.1/lib/python2.6/site.so
# trying /opt/python/2.6.1/lib/python2.6/sitemodule.so
# trying /opt/python/2.6.1/lib/python2.6/site.py
# /opt/python/2.6.1/lib/python2.6/site.pyc matches /opt/python/2.6.1/
lib/python2.6/site.py
import site # precompiled from /opt/python/2.6.1/lib/python2.6/
site.pyc
# trying /opt/wxPython/2.8.9.1/os.so
# trying /opt/wxPython/2.8.9.1/osmodule.so
# trying /opt/wxPython/2.8.9.1/os.py
# trying /opt/wxPython/2.8.9.1/os.pyc
# trying /opt/python/2.6.1/os.so
# trying /opt/python/2.6.1/osmodule.so
# trying /opt/python/2.6.1/os.py
# trying /opt/python/2.6.1/os.pyc
# trying /opt/python/2.6.1/lib/python2.6/os.so
# trying /opt/python/2.6.1/lib/python2.6/osmodule.so
# trying /opt/python/2.6.1/lib/python2.6/os.py
# /opt/python/2.6.1/lib/python2.6/os.pyc matches /opt/python/2.6.1/lib/
python2.6/os.py
import os # precompiled from /opt/python/2.6.1/lib/python2.6/os.pyc
import errno # builtin
import posix # builtin
# trying /opt/wxPython/2.8.9.1/posixpath.so
# trying /opt/wxPython/2.8.9.1/posixpathmodule.so
# trying /opt/wxPython/2.8.9.1/posixpath.py
# trying /opt/wxPython/2.8.9.1/posixpath.pyc
# trying /opt/python/2.6.1/posixpath.so
# trying /opt/python/2.6.1/posixpathmodule.so
# trying /opt/python/2.6.1/posixpath.py
# trying /opt/python/2.6.1/posixpath.pyc
# trying /opt/python/2.6.1/lib/python2.6/posixpath.so
# trying /opt/python/2.6.1/lib/python2.6/posixpathmodule.so
# trying /opt/python/2.6.1/lib/python2.6/posixpath.py
# /opt/python/2.6.1/lib/python2.6/posixpath.pyc matches /opt/python/
2.6.1/lib/python2.6/posixpath.py
import posixpath # precompiled from /opt/python/2.6.1/lib/python2.6/
posixpath.pyc
# trying /opt/wxPython/2.8.9.1/stat.so
# trying /opt/wxPython/2.8.9.1/statmodule.so
# trying /opt/wxPython/2.8.9.1/stat.py
# trying /opt/wxPython/2.8.9.1/stat.pyc
# trying /opt/python/2.6.1/stat.so
# trying /opt/python/2.6.1/statmodule.so
# trying /opt/python/2.6.1/stat.py
# trying /opt/python/2.6.1/stat.pyc
# trying /opt/python/2.6.1/lib/python2.6/stat.so
# trying /opt/python/2.6.1/lib/python2.6/statmodule.so
# trying /opt/python/2.6.1/lib/python2.6/stat.py
# /opt/python/2.6.1/lib/python2.6/stat.pyc matches /opt/python/2.6.1/
lib/python2.6/stat.py
import stat # precompiled from /opt/python/2.6.1/lib/python2.6/
stat.pyc
# trying /opt/wxPython/2.8.9.1/genericpath.so
# trying /opt/wxPython/2.8.9.1/genericpathmodule.so
# trying /opt/wxPython/2.8.9.1/genericpath.py
# trying /opt/wxPython/2.8.9.1/genericpath.pyc
# trying /opt/python/2.6.1/genericpath.so
# trying /opt/python/2.6.1/genericpathmodule.so
# trying /opt/python/2.6.1/genericpath.py
# trying /opt/python/2.6.1/genericpath.pyc
# trying /opt/python/2.6.1/lib/python2.6/genericpath.so
# trying /opt/python/2.6.1/lib/python2.6/genericpathmodule.so
# trying /opt/python/2.6.1/lib/python2.6/genericpath.py
# /opt/python/2.6.1/lib/python2.6/genericpath.pyc matches /opt/python/
2.6.1/lib/python2.6/genericpath.py
import genericpath # precompiled from /opt/python/2.6.1/lib/python2.6/
genericpath.pyc
# trying /opt/wxPython/2.8.9.1/warnings.so
# trying /opt/wxPython/2.8.9.1/warningsmodule.so
# trying /opt/wxPython/2.8.9.1/warnings.py
# trying /opt/wxPython/2.8.9.1/warnings.pyc
# trying /opt/python/2.6.1/warnings.so
# trying /opt/python/2.6.1/warningsmodule.so
# trying /opt/python/2.6.1/warnings.py
# trying /opt/python/2.6.1/warn

Re: use python to split a video file into a set of parts

2013-05-07 Thread Dave Angel

On 05/07/2013 07:15 AM, iMath wrote:

I use the following python code to split a FLV video file into a set of parts 
,when finished ,only the first part video can be played ,the other parts are 
corrupted.I wonder why and Is there some correct ways to split video files



There are two parts to answering the question.  First, did it accurately 
chunk the file into separate pieces.  That should be trivial to test -- 
simply concatenate them back together (eg. using copy /b) and make sure 
you get exactly the original.  (using md5sum, for example) I think you will.


And second, why the arbitrary pieces don't play in some unspecified 
video player.  That one's more interesting, but hasn't anything to do 
with Python.  I'm curious why you would expect that it would play.  It 
won't have any of the header information, and the compressed data will 
be missing its context information.  To split apart a binary file into 
useful pieces requires a lot of knowledge about the file format.




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


Re: Making safe file names

2013-05-07 Thread Dave Angel

On 05/07/2013 03:58 PM, Andrew Berg wrote:

Currently, I keep Last.fm artist data caches to avoid unnecessary API calls and 
have been naming the files using the artist name. However,
artist names can have characters that are not allowed in file names for most 
file systems (e.g., C/A/T has forward slashes). Are there any
recommended strategies for naming such files while avoiding conflicts (I 
wouldn't want to run into problems for an artist named C-A-T or
CAT, for example)? I'd like to make the files easily identifiable, and there 
really are no limits on what characters can be in an artist name.



So what you need first is a list of allowable characters for all your 
target OS versions.  And don't forget that the allowable characters may 
vary depending on the particular file system(s) mounted on a given OS.


You also need to decide how to handle Unicode characters, since they're 
different for different OS.  In Windows on NTFS, filenames are in 
Unicode, while on Unix, filenames are bytes.  So on one of those, you 
will be encoding/decoding if your code is to be mostly portable.


Don't forget that ls and rm may not use the same encoding you're using. 
 So you may not consider it adequate to make the names legal, but you 
may also want they easily typeable in the shell.


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


Re: Making safe file names

2013-05-07 Thread Dave Angel

On 05/07/2013 08:51 PM, Andrew Berg wrote:

On 2013.05.07 19:14, Dave Angel wrote:

You also need to decide how to handle Unicode characters, since they're
different for different OS.  In Windows on NTFS, filenames are in
Unicode, while on Unix, filenames are bytes.  So on one of those, you
will be encoding/decoding if your code is to be mostly portable.

Characters outside whatever sys.getfilesystemencoding() returns won't be 
allowed. If the user's locale settings don't support Unicode, my
program will be far from the only one to have issues with it. Any problem 
reports that arise from a user moving between legacy encodings
will generally be ignored. I haven't yet decided how I will handle artist names 
with characters outside UTF-8,


There aren't any characters "outside UTF-8".  But a character is not "in 
utf-8", it can be encoded by utf-8.


 but inside UTF-16/32 (UTF-16

Nor outside UTF-16 or 32.


is just fine on Windows/NTFS, but on Unix(-ish) systems, many use UTF-8 in 
their locale settings).

Don't forget that ls and rm may not use the same encoding you're using.
So you may not consider it adequate to make the names legal, but you
may also want they easily typeable in the shell.

I don't understand. I have no intention of changing Unicode characters.


So you're comfortable typing arbitrary characters?  what about all the 
characters that have identical displays in your font? What about viewing 
0x07 in the terminal window?  Or 0x04?





This is not a Unicode issue since (modern) file systems will happily accept it. 
The issue is that certain characters (which are ASCII) are
not allowed on some file systems:
  \ / : * ? " < > | @ and the NUL character
The first 9 are not allowed on NTFS, the @ is not allowed on ext3cow, and NUL 
and / are not allowed on pretty much any file system. Locale
settings and encodings aside, these 11 characters will need to be escaped.



As soon as you have a small, finite list of invalid characters, writing 
an escape system is pretty easy.



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


Re: Why do Perl programmers make more money than Python programmers

2013-05-07 Thread Dave Angel

On 05/07/2013 09:11 PM, Benjamin Kaplan wrote:

On May 7, 2013 5:42 PM, "Neil Hodgson"  wrote:


jmfauth:


2) More critical, Py 3.3, just becomes non unicode compliant,
(eg European languages or "ascii" typographers !)
...



This is not demonstrating non-compliance. It is comparing performance,

not compliance.


Please show an example where Python 3.3 is not compliant with Unicode.

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


It's violating page 1+1j of the Unicode spec, where it says precisely how
long each operation is allowed to take. Only wise people can see that page.




Of course!   It's a complex page.


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


Re: Making safe file names

2013-05-07 Thread Dave Angel

On 05/07/2013 09:28 PM, Neil Hodgson wrote:

Andrew Berg:


This is not a Unicode issue since (modern) file systems will happily
accept it. The issue is that certain characters (which are ASCII) are
not allowed on some file systems:
  \ / : * ? "<  >  | @ and the NUL character
The first 9 are not allowed on NTFS, the @ is not allowed on ext3cow,
and NUL and / are not allowed on pretty much any file system. Locale
settings and encodings aside, these 11 characters will need to be
escaped.


There's also the Windows device name hole. There may be trouble with
artists named 'COM4', 'CLOCK$', 'Con', or similar.



In MSDOS 2, there was a switch that would tell the OS to ignore such 
names unless they were prefixed by \DEV.  But like the switchar switch, 
it was largely ignored by the ignorant, and probably doesn't exist in 
current versions of M$OS



http://support.microsoft.com/kb/74496
http://en.wikipedia.org/wiki/Nul_%28band%29

Neil


While we're looking for trouble, there's also case insensitivity. 
Unclear if the user cares, but tom and TOM are the same file in most 
configurations of NT.


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


Re: Making safe file names

2013-05-07 Thread Dave Angel

On 05/07/2013 10:06 PM, Andrew Berg wrote:

On 2013.05.07 20:28, Neil Hodgson wrote:

http://support.microsoft.com/kb/74496
http://en.wikipedia.org/wiki/Nul_%28band%29

I can indeed confirm that at least 'nul' cannot be used as a filename. However, 
I add an extension to the file names to identify them as caches.



Won't help.  NUL.txt is just as reserved as NUL is.  Extensions are 
ignored in this particular piece of historical nonsense.



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


Re: Making safe file names

2013-05-07 Thread Dave Angel

On 05/07/2013 11:40 PM, Steven D'Aprano wrote:


   

These are all Unicode characters too. Unicode is a subset of ASCII, so
anything which is ASCII is also Unicode.




Typo.  You meant  Unicode is a superset of ASCII.


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


Re: Globally available I/O connection (K8055 I/O board)

2013-05-08 Thread Dave Angel

On 05/08/2013 04:50 PM, flex...@gmail.com wrote:

I'm having a bit of an issue trying to make a globally available connection to 
my Velleman K8055 I/O board...

I've documented my issue as best I can here: 
http://stackoverflow.com/questions/16449706/python-access-global-instance-of-connection



I don't think that's a Python question at all.  You have some constraint 
your hardware gives you that requires you to run function k8055(0) once, 
and to use that result object to access the board subsequently.  Looks 
to me like you're doing exactly that.  Are there any other calls to that 
function in your code?


If you were messing up with your access to the global object 
globalK8055, you'd get an exception.


The only Python mistake I can think of that you might be doing is if 
you're using your script as a module, or otherwise doing circular 
imports, or if you're accessing some module under more than one name.


In particular, if you run SmartyPi/appglobals.py as a script, it'd be 
calling the k8055() function once and saving the value.  And then when 
somebody imports it as

from smartypi.appglobals import globalK8055 as k

they'd get a NEW instance of the module and a new value for globalK8055.

If you have some form of logging mechanism (including print), you could 
record each time the k8055() is called.



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


Re: Get filename using filefialog.askfilename

2013-05-08 Thread Dave Angel

On 05/08/2013 04:14 PM, cheirasa...@gmail.com wrote:

El martes, 7 de mayo de 2013 23:53:32 UTC+2, Terry Jan Reedy  escribió:

On 5/7/2013 4:27 PM, cheirasa...@gmail.com wrote:







Yeah. This is an answer. A lot of thanks.



For a moment there, I thought you were being sarcastic, and ungrateful 
at that.  But I figured that it must have been my imagination.


Usually, it's better to teach a man to fish, rather than just handing 
him one.  But some would rather just have an answer, but not the 
understanding of how to acquire it.


So, some unsolicited advice.  And mixed in, maybe the actual answer to 
your original question.


1) Lose googlegroups, or figure a way to avoid its bad habits.  Your 
responses here are doublespaced, which makes it hard to read, especially 
when you include so much that has nothing to do with your response. 
Also, triple posting leads to a number of problems, not the least of 
which is the number of other responders who killfile anything from 
googlegroups.  See http://wiki.python.org/moin/GoogleGroupsPython.


2) Include enough of your code that people can actually figure out what 
you're up to.  You're asking a question about a method of an object 
filedialog, but you never show how it's created.


3) Include enough of your error messages or diagnostic prints that we 
can see what's going on.


> output is: <..name="file.doc"...mode=..encoding..  >

You elided the only important part of that line, the type of the object 
you're asking about.  Most of us would know that a file object has an 
attribute of name.  But instead I spent quite a while trying to find 
what GUI library you were using that might be handing back something 
representing a file.


4) include the environment you're running in.  In your first thread, you 
included a line:

   Using Windows 7, Python 3.3, sfml 1.3.0 library, ...

Very helpful.  But no such hints here.

5) try not to override builtin names with your own local variables.  In 
this case, you defined a local variable called file, which overwrites, 
presumably by coincidence, its own type name.



Thanks for pointing out the "annotated source code" on fossies.org.  I 
wasn't aware of that location.






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


Re: help on Implementing a list of dicts with no data pattern

2013-05-08 Thread Dave Angel

On 05/08/2013 07:47 PM, rlelis wrote:

Hi guys,



Please read this http://wiki.python.org/moin/GoogleGroupsPython.



I'm working on this long file, where i have to keep reading and
storing different excerpts of text (data) in different variables (list).

Once done that i want to store in dicts the data i got from the lists mentioned 
before. I want them on a list of dicts for later RDBMs purpose's.

The data i'm working with, don't have fixed pattern (see example bellow), so 
what i'm doing is for each row, i want to store combinations of  word/value 
(Key-value) to keep track of all the data.

My problem is that once i'm iterating over the list (original one a.k.a 
file_content in the link), then i'm nesting several if clause to match
the keys i want. Done that i select the keys i want to give them values and 
lastly i append that dict into a new list. The problem here is that i end up 
always with the last line repeated several times for each row it found's.

Please take a look on what i have now:
http://pastebin.com/A9eka7p9



If you want a response here, please post the code here.  If it's over 50 
lines, simplify it first.  And be sure and tell us what version of 
Python and what other dependencies you might have.  And what OS you're 
targeting.



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


Re: help on Implementing a list of dicts with no data pattern

2013-05-09 Thread Dave Angel

On 05/09/2013 05:57 AM, rlelis wrote:

On Thursday, May 9, 2013 12:47:47 AM UTC+1, rlelis wrote:

Hi guys,



I'm working on this long file, where i have to keep reading and

storing different excerpts of text (data) in different variables (list).



Once done that i want to store in dicts the data i got from the lists mentioned 
before. I want them on a list of dicts for later RDBMs purpose's.



The data i'm working with, don't have fixed pattern (see example bellow), so 
what i'm doing is for each row, i want to store combinations of  word/value 
(Key-value) to keep track of all the data.



My problem is that once i'm iterating over the list (original one a.k.a 
file_content in the link), then i'm nesting several if clause to match

the keys i want. Done that i select the keys i want to give them values and 
lastly i append that dict into a new list. The problem here is that i end up 
always with the last line repeated several times for each row it found's.



Please take a look on what i have now:

http://pastebin.com/A9eka7p9


Sorry, i thought that a link to pastebin could be helpfully since it captures 
the syntax highlights and spacings. I don't have a fifty line code there. The 
25 lines below, where to show you guys a picture of what is going on, to be 
more intuitive.
This is what i have for now:



The entire following set of comments is probably outdated since you 
apparently did NOT use readlines() or equivalent to get file_content. 
So you'd better give us some sample data, a program that can actually 
run without getting exceptions due to misnamed variables, and a 
description of just what you expected to be in each result variable.


It'd also be smart to mention what version of Python you're targeting.

 what follows was a waste of my time ...

file_content is not defined, but we can guess you have read it from a 
text file with readlines(), or more efficiently that it's simply a file 
object for a file opened with "r".  Can we see sample data, maybe for 3 
or four lines?


file_content = [
"A4 value2 aging",
"b8 value99 paging",
"-1 this is aging a test",
"B2  repeaagingts",
]

The sample, or the description, should indicate if repeats of the 
"columns" column are allowed, as with b and B above.



highway_dict = {}
aging_dict = {}
queue_row = []
for content in file_content:
if 'aging' in content:
# aging 0 100
collumns = ''.join(map(str, 
content[:1])).replace('-','_').lower()
total_values =''.join(map(str, content[1:2]))
aging_values = ''.join(map(str, content[2:]))


Those three lines would be much more reasonable and readable if you 
eliminated all the list stuff, and just did what was needed.  Also, 
calling a one-character string "collumns" or "total_values" makes no 
sense to me.


collumns = content[:1].replace('-','_').lower()
total_values = content[1:2]
aging_values = content[2:]



aging_dict['total'], aging_dict[collumns] = total, aging_values


That line tries to get clever, and ends up obscuring what's really 
happening.  Further, the value in total, if any is NOT what you just 
extracted in total_values.

aging_dict['total'] = total
aging_dict[collumns] = aging_values



queue_row.append(aging_dict)


Just what do you expect to be in the aging_dict here?  If you intended 
that each item of queue_row contains a dict with just one item, then you 
need to clear aging_dict each time through the loop.  As it stands the 
list ends up with a bunch of dicts, each with possibly one more entry 
than the previous dict.


All the same remarks apply to the following code.  Additionally, you 
don't use collumns for anything, and you use lanes and state when you 
presumably meant lanes_values and state_values.


if 'highway' in content:




#highway|   4   |   disable |   25
collumns = ''.join(map(str, 
content[:1])).replace('-','_').lower()
lanes_values  =''.join(map(str, content[1:2]))  
state_values = ''.join(map(str, content[2:3])).strip('')
limit_values = ''.join(map(str, content[3:4])).strip('')

highway_dict['lanes'], highway_dict['state'], 
highway_dict['limit(mph)'] = lanes, state, limit_values
queue_row.append(highway_dict)



Now, when

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


Re: help on Implementing a list of dicts with no data pattern

2013-05-09 Thread Dave Angel

On 05/09/2013 10:33 AM, rlelis wrote:

I apologize once again.
Is my first post here and i'm getting used to the group as long as i get the 
feedback of my errors by you guys.
I'm using Python 2.7.3 with no dependencies, i'm simply using the standard
library.
Here is the "big picture" of the scenario(i have added it in the pastebin link 
too)

FILE OUTPUT DESIRED:
aging:
aging  |total |age
aging  |0 |100
aging  |2 |115
aging  |3 |1
aging  |4 |10

highway:
highway   | lanes |   state   |   limit(mph)
highway   |   4   |   disable |   25
highway   |   2   |   disable |   245
highway   |   3   |   disable |   125
highway   |   2   |   enable  |   255
highway   |   3   |   disable |   212
highway   |   8   |   disable |   78

FILE INPUT EXCERPT EXAMPLE:
aging 0 100
aging 2 115
aging 3 1
highway 4 disable 25
highway 2 disable 245
highway 0 enable 125

Meanwhile i have change the code a little bit and achieve a output closer to 
what i want:


You're still missing the file read code.  My earlier assumption that it 
was a simple readlines() was bogus, or the line:

   if "aging" in file-content:

would never work.

Perhaps you have something like:

infile = open("","r")
file_content = [line.split() for line in infile]

if you confirm it, I'll try to go through the code again, trying to make 
sense of it.




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


Re: help on Implementing a list of dicts with no data pattern

2013-05-09 Thread Dave Angel

On 05/09/2013 12:14 PM, rlelis wrote:

On Thursday, May 9, 2013 12:47:47 AM UTC+1, rlelis wrote:
@Dave Angel
this is how i mange to read and store the data in file.
data = []
# readdata
f = open(source_file, 'r')
for line in f:
 header = (line.strip()).lower()
 # conditions(if/else clauses) on the header content to filter desired 
data
 data.append(header)



From earlier message:
> highway_dict = {}
> aging_dict = {}
> queue_counters={}
> queue_row = []
> for content in file_content:
if 'aging' in content:

So your data is a list of strings, each representing one line of the 
file.  When you run this, you'll get something like:


NameError: name 'file_content' is not defined

If I assume you've just neglected to include the assignment, 
file_content = data, then the next problem is


 if 'aging' in content:

will never fire.  Likewise
if 'highway' in content:

will never fire.  So the rest of the code is irrelevant.

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


Re: help on Implementing a list of dicts with no data pattern

2013-05-09 Thread Dave Angel

On 05/09/2013 05:22 PM, rlelis wrote:

On Thursday, May 9, 2013 7:19:38 PM UTC+1, Dave Angel wrote:

Yes it's a list of string. I don't get the NameError: name 'file_content' is 
not defined in my code.


That's because you have the 3 lines below which we hadn't seen yet.



After i appended the headers i wanted to cut the data list it little bit more 
because there was some data (imagine some other collumns) to the left that 
didn't needed.

file_content = []
for d in data:
 file_content.append(d[1:])

from this point on i've showed the code,
highway_dict = {}
aging_dict = {}
queue_counters={}
queue_row = []
for content in file_content:
 if 'aging' in content:
 # aging 0 100
 # code here



OK, so I now have some code I can actually run.  Unfortunately, it 
produces an error:


Traceback (most recent call last):
  File "ricardo.py", line 23, in 
aging_dict['total'], aging_dict[columns] = total, aging_values
NameError: name 'total' is not defined

So I'll make a reasonable guess that you meant total_values there.  I 
still can't understand how you're testing this code, when there are 
trivial bugs in it.


Next, I get:

Traceback (most recent call last):
  File "ricardo.py", line 32, in 
highway_dict['lanes'], highway_dict['state'], 
highway_dict['limit(mph)'] = lanes, state, limit_values

NameError: name 'lanes' is not defined

and then:

Traceback (most recent call last):
  File "ricardo.py", line 32, in 
highway_dict['lanes'], highway_dict['state'], 
highway_dict['limit(mph)'] = lanes_values, state, limit_values

NameError: name 'state' is not defined

Each of those not-defined errors was pointed out by me earlier in the 
thread.


I don't see any output logic, so I guess it's up to us to guess what the 
meanings and scope of the various lists and dicts are.  I figure the 
queue_row is your final collection that you hope to get results from. 
It's a list containing many references to a single queue_counters 
object.  So naturally, they all look the same.


If you want them to be different, you have to create a new one each 
time.  Move the line:

queue_counters={}

inside the loop, right after the line:
for content in file_content:

There are a bunch of other things wrong, like not lining up the columns 
when you're substringing content, but this may be your major stumbling 
block.  Note:  you may have to also move the highway_dict and 
aging_dict;  I haven't figured out what they're for, yet.


Following is the code I've been using to try to figure out what you were 
intending:



file_content = [
"aging 0 100",
"aging 2 115",
"aging 3 1",
"highway 4 disable 25",
"highway 2 disable 245",
"highway 0 enable 125",
]

highway_dict = {}
aging_dict = {}
#queue_counters={}
queue_row = []
for content in file_content:
queue_counters={}
if 'aging' in content:
# aging 0 100
columns = ', '.join(map(str, 
content[:1])).replace('-','_').lower()

print "columns:", columns
total_values =''.join(map(str, content[1:2]))
aging_values = '\t'.join(map(str, content[2:]))

aging_dict['total'], aging_dict[columns] = 
total_values, aging_values

queue_counters[columns] = aging_dict
if 'highway' in content:
#highway|   4   |   disable |   25
columns = ''.join(map(str, 
content[:1])).replace('-','_').lower()

lanes_values  =''.join(map(str, content[1:2]))
state_values = ''.join(map(str, content[2:3])).strip('')
limit_values = ''.join(map(str, content[3:4])).strip('')

highway_dict['lanes'], highway_dict['state'], 
highway_dict['limit(mph)'] = lanes_values, state_values, limit_values

queue_counters[columns] = highway_dict
queue_row.append(queue_counters)


print
print "h dict:", highway_dict
print
print "aging dict:", aging_dict
print
print "q counters:", queue_counters
for key, item in  queue_counters.iteritems():
print key, item

print
print "q row:", queue_row
for item in queue_row:
print item






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


Re: in need of some help regarding my rock paper scissors game

2013-05-12 Thread Dave Angel

On 05/12/2013 03:33 PM, Alex Norton wrote:

im new to python and im in the middle of making a RPS game for a college
unit.

i have used PyQt to create the GUI and i have received help regarding
adding the code to the buttons.


I'm not at all familiar with PyQT, but I have used other GUIs, and I'm 
quite familiar with Python itself.




but its missing something as the error

'Traceback (most recent call last): File "C:\Users\Me\Desktop\testy.py",
line 174, in bWater.clicked.connect( water_clicked ) AttributeError: 'int'
object has no attribute 'clicked'' appears when i run the module.


You've defined two very different bWater objects.  One is an instance 
attribute of the class Ui_MainWindow, while the other is an int at 
global scope.  The latter is never usefully referenced, but it's there 
to cause a confusing error message.  Those three calls through the 
clicked attrbute are evidently intended for the button object, which is 
inside the class instance.  My guess is that those three lines should be 
inside the setupUI method, and should have self. prefix on each.


Next problem is that there's a comment at the beginning:

# Form implementation generated from reading ui file 'mygui.ui'
#
# Created: Fri May 10 20:27:13 2013
#  by: PyQt4 UI code generator 4.10.1
#
# WARNING! All changes made in this file will be lost!

which implies this file is a generated one.  If you ever rerun that UI 
generator, you'll wipe out any changes you've made.  Again, I'm not 
familiar with PyQT, so I don't know how likely that is.


Next problem is that you have no top-level code that calls main(), which 
is evidently the code that gets things moving.  Generally, you want to 
put all the top-level code inside main(), in which case the call to 
main() would be the only top-level code left.  But there are exceptions. 
 imports should nearly always go to the top, at top level.  And you 
conditional functions need to stay at top-level just as you have them 
(the two clauses with try/cath in them).


Final problem that I can spot is that if you DO need to reference those 
four functions from mainline code, you'll have to move them earlier in 
the file.  But if you agreed with my earlier suggestion to move the 
three lines inside that method, then this wouldn't be a problem any more.




i was wondering if somebody could walk me through making the game complete
and to add the results of the game (win/lose/stalemate) to the loutcome
label



Once you get to the innards of PyQT, I'll be no help at all.  But I hope 
I've given you a little push in the right direction.



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


Re: Differences of "!=" operator behavior in python3 and python2 [ bug? ]

2013-05-13 Thread Dave Angel

On 05/13/2013 06:53 PM, Mark Lawrence wrote:

On 13/05/2013 22:17, Alister wrote:

On Mon, 13 May 2013 19:28:29 +0100, Fábio Santos wrote:


I think it is more readable. When doing more complicated statements I
use != instead, but when it's a single test I prefer not … ==

It's a personal thing. It may also have to do with the fact that I
didn't know python had != when I was a novice.
On 13 May 2013 19:08, "Ned Batchelder"  wrote:



I would then still write it as not (x == y) to make it clear to myself &
avoid any possible confusion although I think that X != Y is much
cleaner.
2 lines from the zen stand out here:-

Explicit is better than implicit.
in the face of ambiguity refuse the temptation to guess.

there are many features of Python (& other languages) i did not now when
I started but have adopted once I understood what they were & how they
worked. then again use what you are most comfortable with.

Practicality beats purity



I much prefer the alternative <> for != but some silly people insisted
that this be removed from Python3.  Just how stupid can you get?



So which special methods should the <> operator call?  By rights it 
ought to call both __gt__ and __lt__ and return True if either of them 
is True.



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


Re: Differences of "!=" operator behavior in python3 and python2 [ bug? ]

2013-05-13 Thread Dave Angel

On 05/13/2013 07:30 PM, Cameron Simpson wrote:

On 13May2013 19:22, Dave Angel  wrote:
| On 05/13/2013 06:53 PM, Mark Lawrence wrote:
| >I much prefer the alternative <> for != but some silly people insisted
| >that this be removed from Python3.  Just how stupid can you get?
|
| So which special methods should the <> operator call?  By rights it
| ought to call both __gt__ and __lt__ and return True if either of
| them is True.

Surely it should require both of them to be true...


Then it would never be true.  At least not for numbers.



Personally I'm for != given we have ==. Aside from notational
consistency it makes conceptual sense for unordered types, which
<> does not really.


That's the point of mentioning __gt__ and __lt__,  they aren't available 
on unordered types.




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


Re: Python for philosophers

2013-05-13 Thread Dave Angel

On 05/13/2013 07:32 PM, Citizen Kant wrote:


   



  Am I getting closer to the point?



Depends on whom you think you're talking to.  Clearly, you've replied to 
yourself, and top-posted besides.  That's not a conversation, it's a 
monologue.



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


Re: Determine actually given command line arguments

2013-05-15 Thread Dave Angel

On 05/15/2013 08:24 AM, Roy Smith wrote:

In article ,
  Henry Leyh  wrote:


Is there a simple way to determine which
command line arguments were actually given on the commandline, i.e. does
argparse.ArgumentParser() know which of its namespace members were
actually hit during parse_args().


I think what you're looking for is sys.argv:

$ cat argv.py
import sys
print sys.argv

$ python argv.py foo bar
['argv.py', 'foo', 'bar']



Colin & Roy:
The OP mentioned sys.argv in his original query.

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


Re: Question re: objects and square grids

2013-05-15 Thread Dave Angel

On 05/15/2013 12:56 PM, Andrew Bradley wrote:

Hello everyone.

I am having a good time programming with Python 3.3 and Pygame. Pygame
seems like the perfect platform for the kind of simple games that I want to
make.



Pygame indeed looks pretty good to me as well.  But I haven't done 
anything with it, so I can't give you specific Pygame advice.




 

So far, I have done this:

A1 = pygame.Rect(10, 12, 43, 43)
A2
A3
A4
B1
B2
etc.



This is a code smell in Python (or any reasonable language).  I'd 
suggest that instead of trying to have 200 separate global variables, 
you have one, maybe called grid, as follows:


maxrows = 10
maxcols = 20
grid = []
for row in range(maxrows):
rowdata = []
for column in range(maxcols):
arg1 = ...
arg2 = ...
arg3 = ...
arg4 = ...
rowdata.append(pygame.Rect(arg1, arg2, arg3, arg4)
grid.append(rowdata)


Now, this can be done shorter with list comprehensions, but I figured 
this would be clearer for you.  I also may have the 10 and 20 reversed, 
but you can work that out.


You'd need to make four formulae to get the four arguments to the Rect 
call, using row and column respectively.  Remember that row and column 
will be numbered from zero, not from one.


But now, you can either address a single rect by
   grid[4][8]

or you can do something to all of them, or to an entire row, or to an 
entire column, pretty easily.



While you're testing your formulae, you might want to replace the 
rowdata.append line with something like:


rowdata.append( (arg1, arg2, arg3, arg4) )


And perhaps your maxrows, maxcols might be lower while you're testing.

And you can just print grid to see how those arguments are looking.

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


Re: Question re: objects and square grids

2013-05-15 Thread Dave Angel

On 05/15/2013 02:14 PM, Andrew Bradley wrote:

Please reply on the list, not privately, unless it's something like a 
simple thank-you.  Typically, you'd do a reply-all, then delete the 
people other than the list itself.  Or if you're using Thunderbird, you 
could just reply-list.


> Thank you very much for your response: it seems excellent, but I'm 
afraid I

> do not understand it fully. Your code here:
>
> maxrows = 10
> maxcols = 20
> grid = []
> for row in range(maxrows):
>  rowdata = []
>  for column in range(maxcols):
>  arg1 = ...
>  arg2 = ...
>  arg3 = ...
>  arg4 = ...
>  rowdata.append(pygame.Rect(arg
> 1, arg2, arg3, arg4)
>  grid.append(rowdata)
>
> Seems very good, but keep in mind I just started programming last 
week, and

> this is hard for me to wrap my head around. Do I really just write grid =
> []? or is this like a def grid(): function?

This code was intended to replace the 200 lines you started, A1= 
pygame... A2=  A3=   etc.  I'd have put them inside a function, but this 
is just one of the things I'd have initialized in such a function.  grid 
is a list of lists, not a function.



> What do you mean by rowdata = []?

[] is the way you define an empty list.  Another way might be:
rowdata = list()


> And how exactly would I make the formula for a rect call?

Well, for row==0 and col==0, you say you wanted 10, 12, 43, and 43 for 
the four parameters.   But you never said how you were going to 
(manually) calculate those numbers for other cells.  Only once you've 
decided that can you fill in "formulas" for arg1 and arg2.  I suspect 
that arg3 and arg4 are simply 43 and 43 respectively, since you want all 
the cells to be the same size.


taking my clue from Ian, I might try:

x_offset = 10
y_offset = 12
width = height = 43
arg1 = column * width + x_offset
arg2 = row * height + y_offset
arg3 = width
arg4 = height

That assumes that there is no gap between cells in this grid.  If you 
want a gap, then the width value used in the arg1 formula would be more 
than 43 (width).  Likewise the height value used in the arg2 formula 
would be more than 43 (height).


> If there's a good website for these kind of details, I would 
appreciate that too.


You cannot begin to write a non-trivial program in Python without 
understanding lists pretty thoroughly.  Perhaps you should start with 
Alan Gauld's tutorial, which doesn't assume previous programming experience.

   http://www.alan-g.me.uk/

I haven't studied it, as Python was about my 35th programming language. 
 But he's very active on Python-tutor, and explains things very well. 
So his website is probably very good as well.


Now, as you can see from Ian's message, writing a game using pygame will 
require quite a bit of other understanding.  He demonstrates with 
classes to represent cells, which is indeed what I'd do.  But I suspect 
you're not nearly ready to consider writing classes.  (You use classes 
all the time.  For example, 5 is an instance of class int.)



--
DaveA


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


Re: Question re: objects and square grids

2013-05-15 Thread Dave Angel
Please put new comments AFTER the part you're quoting.  In other words, 
don't top-post.  Also please trim off the stuff that's no longer 
relevant, so people don't have to read through it all wondering where 
your implied comments are.


On 05/15/2013 06:48 PM, Andrew Bradley wrote:

ok, now I have tested this more thoroughly, and it seems i can only do the
grid[x][y] function up to grid[9][9], when i really should be able to be
doing up to grid[10][20].


No, you shouldn't expect it to go to 10,20.  Remember I said that Python 
is zero-based.  So it goes from 0 to 9 inclusive, and from 0 to 19 
inclusive.  Upper left corner is grid[0][0], while lower right is 
grid[9][19].  Check to make sure that range works, which I think it will.




What exactly is the function of this row_squares list?


It's a temporary to hold one row.  You could delete it after the outer 
loop ends, if you like. Normally, if this whole thing were inside a 
function, the variable would go away when the function ended, and you'd 
be returning the grid list only.


You could have avoided the separate name by doing some tricky syntax. 
But I'm trying to show you the clearest way of doing things from a 
beginner perspective.






On Wed, May 15, 2013 at 4:35 PM, Andrew Bradley wrote:


Now I want to show you what I have written:

row = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
column = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20)


No point in initializing them to tuples, since you're not going to use 
those.  Besides, in a moment row and column become ints, and this just 
confuses things.  The range() function below builds a temporary list 
which looks just like what you tediously typed in (except it's square 
brackets instead of round).



SQUARESIZE = 43

grid = []
for row in range(10):
 row_squares = []
 for column in range(20):
 rect = Rect(12 + column * SQUARESIZE, 10 + row * SQUARESIZE,
SQUARESIZE, SQUARESIZE)
 row_squares.append(rect)
 grid.append(row_squares)

It appears to be working (that is, the program still runs without
crashing).


Sorry, but that's no criteria.  Question is whether it's doing what you 
want.  Are the rows 20 across and are there 10 of them?  Do the values 
of each individual rect look right?  print is your friend.



So now, how can I utilize this new grid list? Thank you for the
help so far, I feel like the entire grid is now being worked out.
-Andrew



That's a Pygame question, and I told you at the beginning, I can't 
really help with that.  I'd like to learn, but not this week.


Others - can you show some minimal code to use these grid parameters to 
color selected squares of the pygame window?


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


Re: Question re: objects and square grids

2013-05-15 Thread Dave Angel

On 05/15/2013 08:53 PM, Andrew Bradley wrote:



  

  So now, how can I utilize this new grid list? Thank you for the

help so far, I feel like the entire grid is now being worked out.
-Andrew



That's a Pygame question, and I told you at the beginning, I can't really
help with that.  I'd like to learn, but not this week.

Others - can you show some minimal code to use these grid parameters to
color selected squares of the pygame window?



Yes, I would very much like some help or general advice now about utilizing
this grid thing. How can I refer to these square's new numerical values to
do things with them? Will I be using things like "grid[0][1]" in specific
functions and methods to refer to squares now?


Yes, exactly.  Any place in your code (the part I cannot help with) that 
you need to specify a rect, you can specify something like grid[3][18]. 
 Eventually, as Ian pointed out, you'll want to store more information 
about each cell.  But at that time, you could have a more complex object 
(that YOU define) instead of just a rect.  I just don't think you're 
ready for defining such an object.



That is what I would like to
do, somehow.





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


Re: executing python scripts that are symlinked

2013-05-16 Thread Dave Angel

On 05/16/2013 03:48 AM, Charles Smith wrote:

Hi.

How can I say, from the cmd line, that python should take my CWD as my
CWD, and not the directory where the script actually is?


I have a python script that works fine when it sits in directory WC,
but if I move it out of WC to H and put a symlink from H/script to WC,
it doesn't find the packages that are in WC.  Also, if I use the
absolute path to H, it won't find them, but I guess I can understand
that.

Someone said on the net that python doesn't know whether a file is
real or a symlink, but I think that somehow, python is able to find
out where the real file is and treat that as its base of operations.



You'd really better specify your environment - exact OS and Python 
version.  symlink and cwd usually imply a Unix-type system, but cmd is a 
Windows thing.


Then give examples of what your cwd is, what string you're typing at the 
shell prompt, and what's happening.


For example windows is good at changing cwd long before the executable 
gets control, in some situations.


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


Re: executing python scripts that are symlinked

2013-05-16 Thread Dave Angel

On 05/16/2013 04:29 AM, Charles Smith wrote:

On 16 Mai, 10:18, Dave Angel  wrote:

On 05/16/2013 03:48 AM, Charles Smith wrote:


Hi.



How can I say, from the cmd line, that python should take my CWD as my
CWD, and not the directory where the script actually is?



I have a python script that works fine when it sits in directory WC,
but if I move it out of WC to H and put a symlink from H/script to WC,
it doesn't find the packages that are in WC.  Also, if I use the
absolute path to H, it won't find them, but I guess I can understand
that.



Someone said on the net that python doesn't know whether a file is
real or a symlink, but I think that somehow, python is able to find
out where the real file is and treat that as its base of operations.


You'd really better specify your environment - exact OS and Python
version.  symlink and cwd usually imply a Unix-type system, but cmd is a
Windows thing.

Then give examples of what your cwd is, what string you're typing at the
shell prompt, and what's happening.



Well, I'm on a ubuntu platform,


Good.  Linux seldom gets in the way.


running subversion, but I can't commit
this debugging tool into the working copy where I'm using it, so I
maintain it in my home directory.  The tool does use production
packages, though.

So, if I say,

   $ python fapi-test.py

and fapi-test.py really is there,


where?  Be explicit.  When copying the python invocation line above, you 
never bothered to include the current directory that's generally 
displayed right in front of that $ prompt.



then it works, using the codec
production package.


What codec production package.  And where is it installed?  And how do 
you intend that Python find it?


  But if I use a symlink instead,

So you delete the pfapi-tst.py out of the current directory, and create 
instead a symlink in the current directory that points to its real 
location  And without changing current directory, you run the same 
command and it runs till it gets to the import line, at which point it 
gives a traceback that has nothing to do with the file you're running??? 
 The traceback thinks you're running test2.py.


 it says


Traceback (most recent call last):
   File "test2", line 1, in 
 from codec.support import *
ImportError: No module named codec.support


Python tells me Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)




Take a look at Stephen's example.  He runs some things, shows you 
exactly what he's running, and what happens.  The things he runs may not 
match what you did, but we cannot tell.


From within your script, you can display os.getcwd(), you can ...


import sys, os
print "cwd is", os.getcwd()
print "file is",  __file__
print "PATH is", os.getenv("PATH")
print "python-path is", os.getenv("PYTHONPATH")
print "sys.path is", sys.path

import codec
print "codec file is", codec.__file__

if you run that both as a regular file and on a symlink pointing to that 
file, comparing the two runs could give you a clue as to what's 
different.  My suspicion is that you have a different cwd when you test 
it the second way.


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


Re: spilt question

2013-05-16 Thread Dave Angel

On 05/16/2013 11:00 AM, loial wrote:

I want to split a string so that I always return everything BEFORE the LAST 
underscore

HELLO_.lst # should return HELLO
HELLO_GOODBYE_.ls  # should return HELLO_GOODBYE

I have tried with rsplit but cannot get it to work.

Any help appreciated



The rsplit() method was a good idea; it will work.  So exactly what did 
you try and what about it did not work.  How are you stuck going from 
your partial answer to a complete one?


While you're at it, you need to consider at least two more cases

HELLO.txt#should return ""
HELLO_and_goodbye#should return "HELLO_and"

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


Re: spilt question

2013-05-16 Thread Dave Angel

On 05/16/2013 11:15 AM, Chris Angelico wrote:

On Fri, May 17, 2013 at 1:00 AM, loial  wrote:

I want to split a string so that I always return everything BEFORE the LAST 
underscore

HELLO_.lst # should return HELLO
HELLO_GOODBYE_.ls  # should return HELLO_GOODBYE

I have tried with rsplit but cannot get it to work.

Any help appreciated


Try with a limit:


"HELLO_GOODBYE_.ls".rsplit("_",1)

['HELLO_GOODBYE', '.ls']

"HELLO_GOODBYE_.ls".rsplit("_",1)[0]

'HELLO_GOODBYE'

You can easily get docs on it:


help("".rsplit)

Help on built-in function rsplit:

rsplit(...)
 S.rsplit(sep=None, maxsplit=-1) -> list of strings

 Return a list of the words in S, using sep as the
 delimiter string, starting at the end of the string and
 working to the front.  If maxsplit is given, at most maxsplit
 splits are done. If sep is not specified, any whitespace string
 is a separator.

ChrisA



Now that you've all done his homework for him, see if The OP can spot 
the one case where that won't work.  It's easy to test for, but still 
important to get right (for some definition of right).


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


Re: How to write fast into a file in python?

2013-05-17 Thread Dave Angel

On 05/17/2013 12:35 AM, lokeshkopp...@gmail.com wrote:

On Friday, May 17, 2013 8:50:26 AM UTC+5:30, lokesh...@gmail.com wrote:

I need to write numbers into a file upto 50mb and it should be fast

can any one help me how to do that?

i had written the following code..

 
value = 0

with open(filename, "w") as f:

while f.tell()< size:

f.write("{0}\n".format(value))
  

  If you must use googlegroups, at least read this
  http://wiki.python.org/moin/GoogleGroupsPython.



it takes about 20sec i need 5 to 10 times less than that.

size = 50mb



Most of the time is spent figuring out whether the file has reached its 
limit size.  If you want Python to go fast, just specify the data.  On 
my Linux system, it takes 11 seconds to write the first 633 values, 
which is just under 50mb.  If I write the obvious loop, writing that 
many values takes .25 seconds.


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


Re: Please help with Threading

2013-05-18 Thread Dave Angel

On 05/18/2013 04:58 AM, Jurgens de Bruin wrote:

This is my first script where I want to use the python threading module. I have 
a large dataset which is a list of dict this can be as much as 200 dictionaries 
in the list. The final goal is a  histogram for each dict 16 histograms on a 
page ( 4x4 ) - this already works.
What I currently do is a create a nested list [ [ {}  ], [ {} ] ] each inner list 
contains 16 dictionaries, thus each inner list is a single page of 16 histograms. 
Iterating over the outer-list  and creating the graphs takes to long. So I would like 
multiple inner-list to be processes simultaneously and creating the graphs in 
"parallel".
I am trying to use the python threading for this. I create 4 threads loop over 
the outer-list and send a inner-list to the thread. This seems to work if my 
nested lists only contains 2 elements - thus less elements than threads. 
Currently the scripts runs and then seems to get hung up. I monitor the 
resource  on my mac and python starts off good using 80% and when the 4-thread 
is created the CPU usages drops to 0%.

My thread creating is based on the following : 
http://www.tutorialspoint.com/python/python_multithreading.htm

Any help would be create!!!



CPython, and apparently (all of?) the other current Python 
implementations, uses a GIL to prevent multi-threaded applications from 
shooting themselves in the foot.


However the practical effect of the GIL is that CPU-bound applications 
do not multi-thread efficiently;  the single-threaded version usually 
runs faster.


The place where CPython programs gain from multithreading is where each 
thread spends much of its time waiting for some external trigger.


(More specifically, if such a wait is inside well-written C code, it 
releases the GIL so other threads can get useful work done.  Example is 
a thread waiting for internet activity, and blocks inside a system call)



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


Re: How to write fast into a file in python?

2013-05-18 Thread Dave Angel

On 05/18/2013 01:00 PM, Carlos Nepomuceno wrote:

Python really writes '\n\r' on Windows. Just check the files.


That's backwards.  '\r\n' on Windows, IF you omit the b in the mode when 
creating the file.




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


Re: Please help with Threading

2013-05-19 Thread Dave Angel

On 05/19/2013 05:46 PM, Dennis Lee Bieber wrote:

On Sun, 19 May 2013 10:38:14 +1000, Chris Angelico 
declaimed the following in gmane.comp.python.general:


On Sun, May 19, 2013 at 10:02 AM, Carlos Nepomuceno
 wrote:

I didn't know Python threads aren't preemptive. Seems to be something really 
old considering the state of the art on parallel execution on multi-cores.

What's the catch on making Python threads preemptive? Are there any ongoing 
projects to make that?






With interpreted code eg in CPython, it's easy to implement preemption
in the interpreter. I don't know how it's actually done, but one easy
implementation would be "every N bytecode instructions, context
switch". It's still done at a lower level than user code (N bytecode


Which IS how the common Python interpreter does it -- barring the
thread making some system call that triggers a preemption ahead of time
(even time.sleep(0.0) triggers scheduling). Forget if the default is 20
or 100 byte-code instructions -- as I recall, it DID change a few
versions back.

Part of the context switch is to transfer the GIL from the preempted
thread to the new thread.

So, overall, on a SINGLE CORE processor running multiple CPU bound
threads takes a bit longer just due to the overhead of thread swapping.

On a multi-core processor, the effect is the same, since -- even
though one may have a thread running on each core -- the GIL is only
assigned to one thread, and other threads get blocked when trying to
access runtime data structures. And you may have even more overhead from
processor cache misses if the a thread gets assigned to a different
core.

(yes -- I'm restating the same thing as I had just trimmed below
this point... but the target is really the OP, where repetition may be
helpful in understanding)



So what's the mapping between real (OS) threads, and the fake ones 
Python uses?  The OS keeps track of a separate stack and context for 
each thread it knows about;  are they one-to-one with the ones you're 
describing here?  If so, then any OS thread that gets scheduled will 
almost always find it can't get the GIL, and spend time thrashing.   But 
the change that CPython does intentionally would be equivalent to a 
sleep(0).


On the other hand, if these threads are distinct from the OS threads, is 
it done with some sort of thread pool, where CPython has its own stack, 
and doesn't really use the one managed by the OS?


Understand the only OS threading I really understand is the one in 
Windows (which I no longer use).  So assuming Linux has some form of 
lightweight threading, the distinction above may not map very well.




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


Re: Harmonic distortion of a input signal

2013-05-19 Thread Dave Angel

On 05/19/2013 07:36 PM, killybear...@gmail.com wrote:

One more question. Function np.argmax returns max of non-complex numbers ?
Because FFT array of my signal is complex.



It'd be easier to track the thread if you actually replied to the 
message you're responding to, and also if you included some context. 
But I'll paste the latter in here:


Terry Reedy said:
> Compute the magnitude spectrum:

>>> spect = abs(np.fft.fft(x)[:25])
>>> spect
> array([  0.,  31.85194222,   0.,  10.67342282,
>  0.,   6.47213595,   0.,   4.69726931,
>  0.,   3.73254943,   0.,   3.13762901,
>  0.,   2.7436023 ,   0.,   2.47213595,
>  0.,   2.28230601,   0.,   2.15105461,
>  0.,   2.06487174,   0.,   2.01589594,
> 0.])

> Find the index of the maximum element:

>>> np.argmax(spect)
> 1


Notice that argmax's argument is the result of an abs() call.  It's got 
real numbers representing the magnitude of the various complex numbers.


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


Re: Please help with Threading

2013-05-20 Thread Dave Angel

On 05/20/2013 03:55 AM, Fábio Santos wrote:

My use case was a tight loop processing an image pixel by pixel, or
crunching a CSV file. If it only uses local variables (and probably hold a
lock before releasing the GIL) it should be safe, no?



Are you making function calls, using system libraries, or creating or 
deleting any objects?  All of these use the GIL because they use common 
data structures shared among all threads.  At the lowest level, creating 
an object requires locked access to the memory manager.



Don't forget, the GIL gets used much more for Python internals than it 
does for the visible stuff.



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


Re: How to run a python script twice randomly in a day?

2013-05-21 Thread Dave Angel

On 05/21/2013 06:32 AM, Cameron Simpson wrote:

On 21May2013 17:56, Chris Angelico  wrote:
| On Tue, May 21, 2013 at 11:12 AM, Cameron Simpson  wrote:
| > - randrange() is like other python ranges: it does not include the end 
value.
| >   So your call picks a number from 0..58, not 0..59.
| >   Say randrange(0,60). Think "start, length".
|
| Nitpick: It's not start, length; it's start, stop-before. If the start
| is 10 and the second argument is 20, you'll get numbers from 10 to 19.
| But your conclusion is still accurate :)

But it's still a useful thing to think when you're trying to reason
about ranges unless you're doing something unusual.




No, it's only happens to look like length when start is zero.  So as a 
mnemonic, it's highly misleading.



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


Re: Diagnosing socket "Connection reset by peer"

2013-05-22 Thread Dave Angel

On 05/22/2013 04:46 AM, loial wrote:

   

 Is there any additional traceing I can do(either within my python code or 
on the network) to establish what is causing this error?




Try using Wireshark.  It can do a remarkable job of filtering, 
capturing, and analyzing packets.  It can also read and write pcap 
files, which you could either save for later analysis, or send to 
someone who might help.  (Note - unfiltered pcap files can be very large 
on a busy network, but if you can quiet other traffic, you may not need 
to filter at all.)



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


Re: help in obtaining binary equivalent of a decimal number in python

2013-05-23 Thread Dave Angel

On 05/23/2013 07:30 AM, lokeshkopp...@gmail.com wrote:

i need to get 32 bit binary equivalent of a decimal and need to change the 0's 
to 1's and 1's to 0's
For Example
if the input is 2
Output should be:
the 32bit equivalent of 2 :       0010
and the 1's compliment is:       1101



is there any pre-defined function to get the above results in python??



I'm curious as to the intent of the assignment. Are you supposed to be 
learning about base conversion, about ones and twos complement, or about 
Python?


Assuming the intent is to learn about Python, the built-in function 
bin() will take a Python integer (which is not decimal) and convert it 
to a str.  At that point, you can manipulate the string any way you like.


x = 45
print bin(45)
0b101101


Perhaps you want to start by stripping off the leading '0b' using a 
slice.  Then you want to pad it to 32 columns by prepending some number 
of zeroes.  Then you want to insert some spaces at regular intervals.


Presumably doing the ones-complement operation on that string is then 
pretty easy for you.


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


Re: Debugging parallel nose tests?

2013-05-23 Thread Dave Angel

On 05/23/2013 09:09 AM, Roy Smith wrote:


 

nosetests --process-timeout=60 --processes=40 test_api.py



Do you have a 40-processor system?  And do you have enough RAM to run 
all of those processes?



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


Re: PEP 378: Format Specifier for Thousands Separator

2013-05-23 Thread Dave Angel

On 05/23/2013 11:26 AM, Carlos Nepomuceno wrote:



Date: Thu, 23 May 2013 06:44:05 -0700
Subject: Re: PEP 378: Format Specifier for Thousands Separator
From: prueba...@latinmail.com
To: python-list@python.org

[...]


You left out the part where a and f are initialized:


>>> a='%s'
>>> f=(3,5)



eggs(a,f)

Traceback (most recent call last):
File "", line 1, in 
eggs(a,f)
File "", line 1, in eggs
def eggs(spam, ham): return spam % ham
TypeError: not all arguments converted during string formatting

'%s'%(5%3)

'2'


So % doesn't handle tuples! Why's that? Is it intentional (by design)?  




It's a conflict in the design.  A tuple is used to supply multiple 
arguments to the % operator.  So if you want to have a tuple as the 
first argument, you need to enclose it in another tuple.


try the following:

print a % (f,)

The trouble is, it doesn't generalize very readily, so it's difficult to 
use in a function like eggs()


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


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-24 Thread Dave Angel

On 05/24/2013 04:04 AM, lokeshkopp...@gmail.com wrote:

i need to write a code which can sort the list in order of 'n' without use 
builtin functions
can anyone help me how to do?



You could sort, but you couldn't print out the results, so what's the 
point?  In Python 3.3 at least, print() is a built-in function.


Is the homework assignment more clearly worded than your summary?  And 
if so, how far have you gotten on it?


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


Re: suppress newlines in my script

2013-05-24 Thread Dave Angel

On 05/24/2013 09:59 AM, sloan...@gmail.com wrote:



 http://wiki.python.org/moin/GoogleGroupsPython >



  print PE2.format(count)


Thanks for the tip about the CSV module.  I did not know about that.


So why aren't you using it?  There's not much point in solving "the 
newlines problem" if you're going to later switch to a library which 
doesn't have the problem.  The csv module will eliminate the newlines, 
and the commas, organizing your data for you directly (assuming this 
really is a csv file, and that the separator is comma).  None of your 
present code seems to believe it's a csv file, so maybe that's just a 
misdirection.





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


Re: Read txt file, add to iptables not working on new host

2013-05-24 Thread Dave Angel

On 05/24/2013 12:32 PM, JackM wrote:

So Chris, does this version look better? Changed to inFile to with.


#!/usr/bin/python
import os
import time

# Input, Output, and TimeStamp
logFile = open('/var/www/html/statistics/logs/banList.log','w')
stamp = time.asctime(time.localtime())

# Daily Flush of blockList rules before re-applying Blocks
os.popen('/sbin/iptables -F INPUT')
logFile.write(stamp+'\nFlushing Rules..\n')

# Loop to read in file and Apply rules to IPtables
with open('/var/www/html/mydomain.com/banlist.txt','r') as inFile:
 for line in inFile:  # TODO: Use 'with' for a bit of protection
 ip = line.split(';')[0]


You want to write the command to the logfile here, BEFORE you try the 
popen().  That way if there's a problem, you can see what it was about 
to try before it crashed.



 output = os.popen( '/sbin/iptables -A INPUT -s ' + ip + ' -j
REJECT' )
 logFile.write(ip+' - Has been blocked\n')






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


Re: Total Beginner - Extracting Data from a Database Online (Screenshot)

2013-05-24 Thread Dave Angel

On 05/24/2013 01:32 PM, logan.c.gra...@gmail.com wrote:

Hey guys,

I'm learning Python


Welcome.


and I'm experimenting with different projects -- I like learning by doing. I'm 
wondering if you can help me here:

na

What this is is a publicly-accessible webpage


No, it's just a jpeg file, an image.


that's a simple database of people who have used the website. Ideally what I'd 
like to end up with is an excel spreadsheet with data from the columns #fb, # 
vids, fb sent?, # email tm.

I'd like to use Python to do it -- crawl the page and extract the data in a 
usable way.



But there's no page to crawl.  You may have to start by finding an ocr 
to interpret the image as characters.  Or find some other source for 
your data.



I'd love your input! I'm just a learner.




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


Re: Total Beginner - Extracting Data from a Database Online (Screenshot)

2013-05-24 Thread Dave Angel

On 05/24/2013 07:36 PM, Carlos Nepomuceno wrote:


 
page = urllib2.urlopen("http://example.com/page.html";).read().strip()

#to create the tables list
tables=[[re.findall('(.*?)',r,re.S) for r in re.findall('(.*?)',t,re.S)] 
for t in re.findall('(.*?)',page,re.S)]


Pretty simple. Good luck!


Only if the page is html, which the OP's was not. It was an image.  Try 
parsing that with regex.




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


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Dave Angel

On 05/25/2013 10:03 AM, Roy Smith wrote:

In article <74e33270-a79a-4878-a400-8a6cda663...@googlegroups.com>,
  lokeshkopp...@gmail.com wrote:


ya steven i had done the similar logic but thats not satisfying my professor
he had given the following constrains
  1. No in-built functions should be used
  2. we are expecting a O(n) solution
  3. Don't use count method


A couple of points here:

1) In general, people on mailing lists are not into doing homework
problems for other people.

2) If you're going to bring us a homework problem, at least describe the
whole problem up front.  It really doesn't help to dribble out new
requirements one at a time.

3) rustompm...@gmail.com already posted a pointer to the wikipedia
article describing the required algorithm in detail.

4) I don't know what "no built-in functions should be used" means.  I
assume it means, "don't call sort()"?  If you can't even call
int.__lt__(), it's going to be really hard to do this.



The OP has already admitted that he didn't want a sort at all.  He wants 
to COUNT the items, not sort them.  So nothing in his orginal post 
relates to the real homework assignment.


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


Re: Reading *.json from URL - json.loads() versus urllib.urlopen.readlines()

2013-05-27 Thread Dave Angel

On 05/27/2013 04:47 PM, Bryan Britten wrote:

Hey, everyone!

I'm very new to Python and have only been using it for a couple of days, but 
have some experience in programming (albeit mostly statistical programming in 
SAS or R) so I'm hoping someone can answer this question in a technical way, 
but without using an abundant amount of jargon.

The issue I'm having is that I'm trying to pull information from a website to 
practice Python with, but I'm having trouble getting the data in a timely 
fashion. If I use the following code:


import json
import urllib

urlStr = "https://stream.twitter.com/1/statuses/sample.json";

twtrDict = [json.loads(line) for line in urllib.urlopen(urlStr)]


I get a memory issue. I'm running 32-bit Python 2.7 with 4 gigs of RAM if that 
helps at all.


Which OS?

The first question I'd ask is how big this file is.  I can't tell, since 
it needs a user name & password to actually get the file.  But it's not 
unusual to need at least double that space in memory, and in Windoze 
you're limited to two gig max, regardless of how big your hardware might be.


If you separately fetch the file, then you can experiment with it, 
including cutting it down to a dozen lines, and see if you can deal with 
that much.


How could you fetch it?  With wget, with a browser (and saveAs), with a 
simple loop which uses read(4096) repeatedly and writes each block to a 
local file.  Don't forget to use 'wb', as you don't know yet what line 
endings it might use.


Once you have an idea what the data looks like, you can answer such 
questions as whether it's json at all, whether the lines each contain a 
single json record, or what.


For all we know, the file might be a few terabytes in size.


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


Re: How to get an integer from a sequence of bytes

2013-05-27 Thread Dave Angel

On 05/27/2013 08:31 PM, Steven D'Aprano wrote:

On Mon, 27 May 2013 11:30:18 -0400, Ned Batchelder wrote:


On 5/27/2013 10:45 AM, Mok-Kong Shen wrote:

 From an int one can use to_bytes to get its individual bytes, but how
can one reconstruct the int from the sequence of bytes?



The next thing in the docs after int.to_bytes is int.from_bytes:


And I can't believe I missed that too :-(



And that approach probably works for negative ints too.


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


Re: Problems with python and pyQT

2013-05-28 Thread Dave Angel

On 05/28/2013 05:41 AM, silusilus...@gmail.com wrote:

Thanks for your reply: very useful!!
I have another question: with hex command i display (for example)

0x1

is it possible to display 0x01?


hex() is a function, not a command.  And it only takes the one 
parameter, the int to be converted.


For more generality, try the str.format() method.  The x type converts 
to hex without any prefix, and then you can add the width and fill field.


http://docs.python.org/2/library/stdtypes.html#str.format
http://docs.python.org/2/library/string.html#formatstrings
http://docs.python.org/2/library/string.html#format-specification-mini-language

For starters, try:

print "0x{0:0>2x}".format(12)
or
print "0x{0:0>2X}".format(12)
if you like uppercase hex characters

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


Re: Python for IPSA (Power flow analysis)

2013-05-28 Thread Dave Angel

On 05/28/2013 06:00 AM, Debbie wrote:

Hi there,
I am new to Python,


Welcome.  Could you tell us a little about yourself, such as whether 
you've experience in a few other languages, or if Python is your first 
programming experience?  Also, what version of Python (presumably 2.7 or 
2.6) and what OS ?



and wondering if you could help me with python based coding for the IPSA (Power 
system analysis software). I have a electrical distribution network with 
generators, buses and loads, on which I am performing the load flow analysis 
every 1 hour for a period of 1 year.

The code to perform instantaneous load/power flow analysis is given below. I 
need to modify it such that I can perform this load flow analysis every 1 hour 
for a period of 1 year. Please help.

from ipsa import *


I have no idea what functionality is in ipsa, so this whole message is a 
guess.  First question is whether the ReadFile() below and the 
DoLoadFlow() read the whole year's data, or data for a particular hour. 
 And if the latter, how do you get the next set of data?





ipsasys = IscInterface()
net = ipsasys.ReadFile("refinery.iif")
bok = net.DoLoadFlow();
if bok:
 busbars = net.GetBusbars()
 print "Load Flow results:"
 print ""
 print "BusName Vmag(kV)"
 print ""
 for bus in busbars.itervalues():
 name = bus.GetName()
 vm = bus.GetVoltageMagnitudekV()
 res = "%-8s  %10.5f" % (name, vm)
 print res
else:
 print "Load Flow failed!"

Regards,
Debbie



First you want to make a function to print out a particular hour's data. 
 That might turn out to be something like:


def one_hour(net):
busbars = net.GetBusbars()
print "Load Flow results:"
print ""
print "BusName Vmag(kV)"
print ""
for bus in busbars.itervalues():
name = bus.GetName()
vm = bus.GetVoltageMagnitudekV()
res = "%-8s  %10.5f" % (name, vm)
print res

(Just pasted from your code, I added in the probable parameter to the 
definition)


Now your main function might be something like:


def main(filename):
ipsasys = IscInterface()
net = ipsasys.ReadFile(filename)

#if net gets you data for one hour, figure out how
#to get the data for the whole year, in the form
#of a list or an iterator called nets

bok = net.DoLoadFlow();
if bok:
for net in nets:
one_hour(net)

else:
print "Load Flow failed!"


#and your top-level code is:
main("refinery.iif")


As to ordering in the source file, put the import first:
   from ipsa import *

then your function definitions one_hour() and main(), then
your top-level code.

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


Re: Python #ifdef

2013-05-28 Thread Dave Angel

On 05/28/2013 03:46 PM, Carlos Nepomuceno wrote:

Are there Python 'preprocessor directives'?


Python doesn't define a preprocessor, and CPYthon doesn't implement one. 
 Nothing to stop you from doing so, however.


I'd like to have something like '#ifdef' to mix code from Python 2 and 3 in a 
single file.

Is that possible? How?  



It's quite possible that you don't need a preprocessor do what you want, 
since Python does much less compile-time checking than C.  Also, it's 
possible to store function objects and module objects in variables, and 
thus to hide many things from the body of the code.


One biggie is print, since that's a reserved word (and a statement) in 
Python 2.x.  But if you're using 2.7 you can use from __future__ import 
print, or something like that, and just use 3.x function semantics.



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


Re: Fatal Python error

2013-05-29 Thread Dave Angel

On 05/29/2013 07:48 AM, Joshua Landau wrote:

Hello all, again. Instead of revising like I'm meant to be, I've been
delving into a bit of Python and I've come up with this code:



To start with, please post in text mode.  By using html, you've 
completely messed up any indentation you presumably had.



class ClassWithProperty:
  @property
def property(self):
pass


Did you really mean to hide the built-in property?  I don't know if this 
does that, but it's certainly confusing.  And perhaps that's a 
difference between 2.x and 3.x




thingwithproperty = ClassWithProperty()

def loop():
try:
thingwithproperty.property
  except:
pass

loop()

try:
loop()
except RuntimeError:
pass

As you will expect, this does nothing... on Python2.7 and PyPy. Python3.3
prefers to spit out a "Fatal Python error: Cannot recover from stack
overflow.", which seems a bit unexpected.



A stack overflow means you have infinite recursion.  Try fixing the 
property name above, and see if that makes a difference.




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


Re: Fatal Python error

2013-05-29 Thread Dave Angel

On 05/29/2013 08:45 AM, Oscar Benjamin wrote:

On 29 May 2013 12:48, Joshua Landau  wrote:

Hello all, again. Instead of revising like I'm meant to be, I've been
delving into a bit of Python and I've come up with this code:


Here's a simpler example that gives similar results:

$ py -3.3
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600
32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

def broken():

...   try:
... broken()
...   except RuntimeError:
... broken()
...

broken()

Fatal Python error: Cannot recover from stack overflow.

Current thread 0x058c:
   File "", line 3 in broken
   File "", line 3 in broken
...

Under Python 2.7.5 it just goes into an infinite loop. Under Python
3.2.5 and 3.3.2 it crashes the interpreter as shown above.

What the broken() function is doing is totally stupid: responding to a
recursion error with more recursion. However this may indicate or be
considered a bug in the 3.x interpreter.


Oscar



More likely a bug in the 2.x interpreter.  Once inside an exception 
handler, that frame must be held somehow.  If not on the stack, then in 
some separate list.  So the logic will presumably fill memory, it just 
may take longer on 2.x .


Joshua:  Avoid doing anything complex inside an exception handler.  If 
nothing else, the exception frame is huge.  I probably would have 
spotted it except for the indentation problem triggered by html.  The 
top level code following your function didn't have any loops, so it 
wasn't a problem.


Can anyone help Joshua put his gmail into text mode?




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


Re: Short-circuit Logic

2013-05-29 Thread Dave Angel

On 05/29/2013 12:50 PM, Ian Kelly wrote:

On Wed, May 29, 2013 at 8:33 AM, rusi  wrote:

0.0 == 0.0 implies 5.4 == 5.4
is not a true statement is what (I think) Steven is saying.
0 (or if you prefer 0.0) is special and is treated specially.


It has nothing to do with 0 being special.  A floating point number
will always equal itself (except for nan, which is even more special),
and in particular 5.4 == 5.4.  But if you have two different
calculations that produce 0, or two different calculations that
produce 5.4, you might actually get two different numbers that
approximate 0 or 5.4 thanks to rounding error.  If you then compare
those two ever-so-slightly different numbers, you will find them
unequal.



Rounding error is just one of the problems.  Usually less obvious is 
quantization error.  If you represent a floating number in decimal, but 
you're using a binary floating point representation, it just might change.


Another error is roundoff error.  Even in a pure decimal system of (say) 
40 digits, I could type in a 42 digit number and it would get quantized. 
 So just because two 42 digit numbers are different doesn't imply that 
the 40 digit internal format would be.



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


Re: User Input

2013-05-30 Thread Dave Angel

On 05/30/2013 08:37 AM, Eternaltheft wrote:

sorry about that, i got confused xD. yeah it works good now.
what i meant to say was can i return a function that i made, if the user inputs 
nothing?



There wouldn't be anything to stop you.  However, if you have multiple 
returns from the same function, it's usually wise to return the same 
type of information from each of them.  That's why Chris suggested 
simply assigning to filename in the if clause.


But without the whole function, and maybe even a description of what the 
function is expected to do, we can only guess.


Your comments still make no sense to me,

> filename = input('file name: ')
> if not filename:  #i get filename is not defined

But filename IS defined, immediately above. If it were undefined, you'd 
not be able to test it here.  Big difference between "not defined" and 
"is empty string".


>return(drawBoard) #possible to return function when no file input 
from user?


If drawBoard is a function object, it's certainly possible to return it. 
 But again, without seeing the rest of the function, and maybe how it's 
intended to be used, I can't confirm whether it makes sense.


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


Re: Can anyone please help me in understanding the following python code

2013-05-30 Thread Dave Angel

On 05/30/2013 08:42 AM, bhk...@gmail.com wrote:

http://wiki.python.org/moin/GoogleGroupsPython  >




In the above output, the control goes to "HERE AFTER SPLIT" after the "Merging" 
statement which is of-course the last statement in the function.On what condition this is happening.

Ideally as per my understanding, after the last statement of a function the 
control should come out of the function.

Please correct me if I am wrong here.

There is something with respect-to functions in python that I am not able to 
understand.




I think you misunderstand recursion.  And you should study it in a 
simpler example before trying to tackle that sort function.


After the last statement of a function, or after an explicit return 
statement, the function does indeed return control to whoever called it. 
 And if the call was in the middle of some other function, that's the 
place where execution will continue.  Functions may nest this way to 
pretty large depths of complexity.


If you're not sure you understand that, we should stop here.  So in your 
reply, tell me if you can readily grasp function dfunc() calling 
cfunc(), which calls bfunc(), which calls afunc().  When afunc() 
returns, you'll be right in the middle of bfunc(), right after the call 
was made.


Now to recursion.  One can write a function which solves a particular 
problem by doing some of the work, but by calling on other functions 
which solve simpler subproblems.  Recursion comes in when those other 
functions are simply instances of the same one.  So instead of dfunc() 
calling cfunc(), we have rfunc() calling rfunc() calling rfunc() calling 
rfunc().


Let's take a classic problem for explaining recursion:  factorial.

We can write a simple function that solves the problem for 0:

def afunc(n):
if n == 0:
 return 1
else:
 throw-some-exception

Silly function, I know.  Now let's write one that solves it for one.

def bfunc(n):
if n == 1:
 return 1 * afunc(n-1)
else:
 throw-some-exception

Now for two:

def bfunc(n):
if n == 2:
 return 2 * bfunc(n-1)
else:
 throw-some-exception


Notice that each function calls the one above it to solve the "simpler" 
problem.  Now if we wanted this to work for n=100, it would get really 
tedious.  So let's see if we can write one function that handles all of 
these cases.


def rfunc(n):
if n == 0:
return 1
else:
return n * rfunc(n-1)

Now if we call this with n==3, it'll make the zero check, then it'll 
call another function with the value 2.  that one will in turn call 
another function with the value 1.  And so on.  So this function calls 
itself, as we say recursively.


Now, for this simple case, we could have used a simple loop, or just 
called the library function.  But it's a simple enough example to follow 
in its entirety (if I've been clear in my writing).


Your mergeSort() function calls itself recursively, and each time it 
does, it passes a *smaller* list to be sorted.  Eventually the calls 
recurse down to a list of size 1, which is already sorted by definition. 
 The check for that is the line


  if len(alist)>1:

near the beginning of the function.  That's analogous to my if n==0 
line, although to match it most directly, I could have reversed the 
if/else and written the test as if n!=0


Chris showed you how to change your output so you could see the nesting 
levels.  I have done that sort of thing in the past, and found it very 
useful.  But first you have to understand nested functions, and simple 
recursion.



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


Re: User Input

2013-05-30 Thread Dave Angel

On 05/30/2013 09:10 AM, Eternaltheft wrote:

yeah i found out why it wasn't defined before because i tried to put it into a 
function.


That's not a sentence, and it doesn't make sense in any permutation I 
can do on it.




this is my drawBoard function:

import turtle as Turtle
Turtle.title("Checkers")
b = 75

def drawBoard(b):

 Turtle.speed(0)

 Turtle.up()

 Turtle.goto(-4 * b, 4 * b)
 Turtle.down()

 for i in range (8):
 Turtle.forward(b)
 Turtle.right(90)
 Turtle.forward(b)
 Turtle.right(90)
 Turtle.forward(b)
 Turtle.right(90)
 Turtle.forward(b)
 Turtle.right(90)
 Turtle.forward(b)

 for i in range (1):
 Turtle.right(90)
 Turtle.forward(b*2)
 Turtle.right(90)

 for i in range(8):
 Turtle.forward(b)
 Turtle.right(90)
 Turtle.forward(b)
 Turtle.right(90)
 Turtle.forward(b)
 Turtle.right(90)
 Turtle.forward(b)
 Turtle.right(90)
 Turtle.forward(b)

 for i in range(1):
 Turtle.left(90)
 Turtle.forward(b)
 Turtle.left(90)

 for i in range (8):
 Turtle.forward(b)
 Turtle.left(90)
 Turtle.forward(b)
 Turtle.left(90)
 Turtle.forward(b)
 Turtle.left(90)
 Turtle.forward(b)
 Turtle.left(90)
 Turtle.forward(b)

 for i in range (1):
 Turtle.right(90)
 Turtle.forward(b)
 Turtle.right(90)

 for i in range(8):
 Turtle.forward(b)
 Turtle.right(90)
 Turtle.forward(b)
 Turtle.right(90)
 Turtle.forward(b)
 Turtle.right(90)
 Turtle.forward(b)
 Turtle.right(90)
 Turtle.forward(b)

 for i in range(1):
 Turtle.left(90)
 Turtle.forward(b)
 Turtle.left(90)

 for i in range (8):
 Turtle.forward(b)
 Turtle.left(90)
 Turtle.forward(b)
 Turtle.left(90)
 Turtle.forward(b)
 Turtle.left(90)
 Turtle.forward(b)
 Turtle.left(90)
 Turtle.forward(b)

 for i in range (1):
 Turtle.right(90)
 Turtle.forward(b)
 Turtle.right(90)

 for i in range(8):
 Turtle.forward(b)
 Turtle.right(90)
 Turtle.forward(b)
 Turtle.right(90)
 Turtle.forward(b)
 Turtle.right(90)
 Turtle.forward(b)
 Turtle.right(90)
 Turtle.forward(b)

 for i in range(1):
 Turtle.left(90)
 Turtle.forward(b)
 Turtle.left(90)

 for i in range (8):
 Turtle.forward(b)
 Turtle.left(90)
 Turtle.forward(b)
 Turtle.left(90)
 Turtle.forward(b)
 Turtle.left(90)
 Turtle.forward(b)
 Turtle.left(90)
 Turtle.forward(b)

 for i in range (1):
 Turtle.right(90)
 Turtle.forward(b)
 Turtle.right(90)

 for i in range(8):
 Turtle.forward(b)
 Turtle.right(90)
 Turtle.forward(b)
 Turtle.right(90)
 Turtle.forward(b)
 Turtle.right(90)
 Turtle.forward(b)
 Turtle.right(90)
 Turtle.forward(b)


drawBoard(b)

Turtle.done()

it draws an 8x8 board table.

what i initially wanted to do was to return this function if nothing was 
inputted from the user. i hope that makes more sense :S



It makes sense if you're also returning a function object when the user 
does have something to say.  But I can't see how you might be doing 
that, unless you're using a lambda to make up a custom function object.


And you still don't show us the function that contains this input 
statement.  Nor how it gets used.  Is the user supposed to supply a 
value for b, and you put it in a variable called filename ?


And perhaps you meant for your function to CALL drawBoard(), rather than 
returning the function object drawBoard.


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


Re: Create a file in /etc/ as a non-root user

2013-05-31 Thread Dave Angel

On 05/31/2013 05:27 AM, Luca Cerone wrote:

fd = open('/etc/file','w')

fd.write('jpdas')

fd.close()



Hi Bibhu, that is not a Python problem, but a permission one.
You should configure the permissions so that you have write access to the 
folder.
However unless you know what you are doing it is discouraged to save your
file in the /etc/ folder.

I don't know if on Mac the commands are the same, but in Unix systems (that I 
guess Mac is) you can manage permissions with chmod.



That directory is protected from users for a reason.  You defeat that 
and risk the system.


Bibhu:  for that reason I'd suggest simply telling your users to run 
your script as root.  If they trust you, and it breaks something, at 
least they know why they were doing it.


   sudo  python  riskyscript.py




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


Re: Getting Error can't find '__main__' module in 'X'

2013-06-02 Thread Dave Angel

On 06/02/2013 07:04 AM, meakaakka wrote:

Hey I am newbie in python.I have installed python 2.7.5 correctly.It is working 
fine but I am having some issues.I have set windows Enviroment variables.


Please be a lot more specific.  Do you have any particular environment 
variables you suspect, and if so, what have you set them to?



The problem is when I try to save my program in a folder(C:\Users\John\X)it 
shows that module error


Then you'd better tell us what program you were using to save it with. 
I've never seen that error from emacs or Notepad++, but perhaps you're 
doing something else.



but when I save it outside this X folder ( C:\Users\John ) It runs 
successfully.How to fix it?



Perhaps you'd better start at the beginning.  Thanks for telling us 
you're using python Version 2.7.5,  Now perhaps you mean not that this 
error occurs during the save, but instead during running of the program.


So let's try again.  Don't try to answer just certain parts of the 
below, but instead make your own problem description that's at least as 
thorough. By the time you're done, you just might solve the problem 
yourself, or you'll have learned something new about the problem.  But 
at least you'll help us help you.



You have saved some program (what is its name?) (why not include it 
here, since it probably only needs about 3 lines, including an import of 
some form?) in the directory  C:\Users\John\X.


You then run it, from a cmd prompt, as follows:

C:\Users\John\X > python  myprog.py

and you get the following error.

(You fill this in.  It's a group of lines called a traceback, and the 
whole thing can be useful.  Don't summarize or retype it, use copy/paste).


You then move the file to directory  C:\Users\John\betterplace, do a cd 
there, and run it again from that directory.  Now it works, no import 
errors, and runs to completion.


So what else is in that first directory?  Are you referencing X 
somewhere in your code?  Are you referencing __name__  (which is a 
reserved term with very specific meaning)?


Have you tried keeping the program in C:\Users\John\X  but running with 
a different current directory?


C:\Users\John\testdir > python  ..\X\myprog.py

If I had to mount my crystal ball, I'd say you've got some form of 
recursive import going on (thus __main__), and that some module or 
package has the name X.  You might also have more than one copy of some 
python source file, or a sys.path that's messed up.


Some general advice for the future:  Avoid using any uppercase in file 
and directory names for source code.  Avoid any single-letter names. 
Avoid doing recursive imports, and NEVER import the script itself from 
some other file.


One more thing.  Before replying, please read this since you're using 
googlegroups:


   http://wiki.python.org/moin/GoogleGroupsPython.


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


Re: PyWart: The problem with "print"

2013-06-03 Thread Dave Angel

On 06/03/2013 04:49 AM, Mark Lawrence wrote:

On 03/06/2013 04:10, Dan Sommers wrote:

On Sun, 02 Jun 2013 20:16:21 -0400, Jason Swails wrote:


... If you don't believe me, you've never hit a bug that 'magically'
disappears when you add a debugging print statement ;-).


Ah, yes.  The Heisenbug.  ;-)

We used to run into those back in the days of C and assembly language.
They're much harder to see in the wild with Python.



Strikes me it's a bit like problems when prototyping circuit boards. The
card doesn't work, so you mount it on an extender card, problem goes
away, remove extender card, problem reappears.  Wash, rinse, repeat :)



That's when you use a little kappy-zapper spray.

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


Re: How to get an integer from a sequence of bytes

2013-06-03 Thread Dave Angel

On 06/03/2013 10:31 AM, Grant Edwards wrote:

On 2013-06-03, Dennis Lee Bieber  wrote:

On Sun, 02 Jun 2013 21:25:45 +0200, Mok-Kong Shen
 declaimed the following in
gmane.comp.python.general:



b'7' is the byte with the character 7 in a certain code, so that's
ok. In other PLs one assigns an int to a byte, with that int in either


In other languages "byte" is an 8-bit signed/unsigned numeric.


That's a common assumption, but historically, a "byte" was merely the
smallest addressable unit of memory.  The size of a "byte" on widely
used used CPUs ranged from 4 bits to 60 bits.



 I recall rewriting the unpacking algorithm to get the 10 
characters from each byte, on such a machine.



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


Re: lstrip problem - beginner question

2013-06-04 Thread Dave Angel

On 06/04/2013 12:01 PM, Mark Lawrence wrote:

On 04/06/2013 16:49, mstagliamonte wrote:

[strip the double line spaced nonsense]

Can you please check your email settings.  It's bad enough being plagued
with double line spaced mail from google, having it come from yahoo is
just adding insult to injury, thanks :)



Mark:
The OP is posting from googlegroups, just using a yahoo return address. 
 So you just have one buggy provider to hate, not two.


>>
>>> If the header is something like:
>>
>>> h01 = ('>scaffold_1')
>>
>>> I just use:
>>
>>> h01.lstrip('>scaffold_')
>>
>>> and this returns me '1'
>>
>>>
>>
>>> But, if the header is:
>>

madmax...@yahoo.it:

If you must use googlegroups, at least fix the double-posting and 
double-spacing bugs it has.  Start by reading:


 http://wiki.python.org/moin/GoogleGroupsPython




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


Re: How to store a variable when a script is executing for next time execution?

2013-06-06 Thread Dave Angel

On 06/06/2013 06:50 AM, Avnesh Shakya wrote:

hi,
I am running a python script and it will create a file name like 
filename0.0.0 and If I run it again then new file will create one more like 
filename0.0.1.. my code is-

i = 0


Redundant initialization of i.


for i in range(1000):
 try:
 with open('filename%d.%d.%d.json'%(0,0,i,)): pass
 continue
 except IOError:
 dataFile = file('filename%d.%d.%d.json'%(0,0,i,), 'a+')
 break
But It will take more time after creating many files, So i want to store value of last 
var "i" in a variable


There are no variables once the program ends.  You mean you want to 
store it in the file.  That's known as persistent storage, and in the 
general case you could use pickle or something like that.  But in your 
simple case, the easiest thing would be to simply write the last value 
of i out to a file in the same directory.


Then when your program starts, it opens that extra file and reads in the 
value of i.  And uses that for the starting value in the loop.


 so that when i run my script again then I can use it. for example-

  my last created file is filename0.0.27 then it should store 27 in a 
variable and when i run again then new file should be created 0.0.28 according to last 
value "27", so that i could save time and it can create file fast..

Please give me suggestion for it.. How is it possible?
Thanks



Incidentally, instead of opening each one, why not check its existence? 
 Should be quicker, and definitely clearer.


Entirely separate suggestion, since I dislike having extra housekeeping 
files that aren't logically necessary, and that might become out of synch :


If you're planning on having the files densely populated (meaning no 
gaps in the numbering), then you could use a binary search to find the 
last one.  Standard algorithm would converge with 10 existence checks if 
you have a limit of 1000 files.


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


Re: trigger at TDM/2 only

2013-06-06 Thread Dave Angel

On 06/06/2013 08:03 PM, cerr wrote:

Hi,

I have a process that I can trigger only at a certain time. Assume I have a TDM 
period of 10min, that means, I can only fire my trigger at the 5th minute of 
every 10min cycle i.e. at XX:05, XX:15, XX:25... For hat I came up with 
following algorithm which oly leaves the waiting while loop if minute % TDM/2 
is 0 but not if minute % TDM is 0:
min = datetime.datetime.now().timetuple().tm_hour*60 + 
datetime.datetime.now().timetuple().tm_min
while not (min%tdm_timeslot != 0 ^ min%(int(tdm_timeslot/2)) != 0):


You might have spent three minutes and simplified this for us.  And in 
the process discovered the problem.


(BTW, min() is a builtin function, so it's not really a good idea to be 
shadowing it.)


You didn't give python version, so my sample is assuming Python 2.7 
For your code it shouldn't matter.


tdm = 10
tdm2 = 5

y = min(3,4)
print y

for now in range(10,32):
print now, now%tdm, now%tdm2,
print not(now % tdm !=0 ^ now%tdm2 !=0) #bad
print not((now % tdm !=0) ^ (now%tdm2 !=0))  #good


Your problem is one of operator precedence.  Notice that ^ has a higher 
precedence than != operator, so you need the parentheses I added in the 
following line.


What I don't understand is why you used this convoluted approach.  Why not

print now%tdm != tdm2

For precedence rules, see:
  http://docs.python.org/2/reference/expressions.html#operator-precedence




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


Re: Trying to work with data from a query using Python.

2013-06-07 Thread Dave Angel

On 06/07/2013 01:44 PM, ethereal_r...@hotmail.com wrote:



   


 rows = cur.fetchall()

 for row in rows:
 print row




Now assume that fetchall would print the following:


I doubt if fetchall() prints anything.  presumably it returns something, 
extracted from the db.




LOEL910624ND5 from the column vat as RFC.
227 from the column amount_untaxed.


Now I would need to print that in the following format.

04|85|LOEL910624ND5|227|||

04 always goes in the first column and 85 always goes in the second, vat goes 
in the third and the amount_untaxed goes in the eight column but we still need 
to have 22 columns in total.





I don't use psycopg2, and I'd suggest few others here do either.

Since the problem has nothing to do with psycopg2, could you simplify 
the problem?  Whatever fetchall() returns, it's presumably either a dict 
or list.  Or is it a list of lists?


Find out what kind of data it is, and stub it with something like:

rows = ["ab", "127"]

Then if you define what the items in that list (or whatever) are 
supposed to mean, we can tell you how to stick all those pipe-symbols 
between.  One likely answer would be the csv module.






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


Re: Questions on "import" and "datetime"

2013-06-10 Thread Dave Angel

On 06/10/2013 01:01 PM, Zachary Ware wrote:

On Mon, Jun 10, 2013 at 10:37 AM, Yunfei Dai  wrote:

Hi all,


Hi Yunfei,



I have some questions on "import":

1."from datetime import datetime" works well. But I am confused why "import datetime.datetime" 
leads to importerror. "from xlrd import open_workbook" could be replaced by "from 
xlrd.open_workbook" without any problem.




It's a historical flaw in datetime that the class has the same name as 
the module it's in.  It should have been called class Datetime 
(according to pep 10, class names should be capitalized).  If that were 
the case, it'd be clear that datetime.Datetime is a class.


It would also be clearer that
from datetime import Datetime

creates an alias in the present global namespace for the 
datetime.Datetime class, as simply Datetime.


This class has attributes that you can access, like Datetime.hour, and 
it has static methods like Datetime.fromTimeStamp().
 And like all classes, it's "callable", meaning that you can create an 
instance by pretending it's a function:

   obj = Datetime(2013, 12, 1)

But since it's not a module inside a package, you can't use the form:

import datetime.Datetime

Now, just interpret all the above with a lowercase "D" and the confusion 
becomes clearer.  The compiler/interpreter doesn't care either way.


   

"from ... import ..." imports an object from a module and assigns it
to a local name that is the same as the name in the other module.  In
other words, the following two examples do the same thing:

from foo import bar

import foo;bar = foo.bar

If foo.bar happens to be a module (module 'bar' in package 'foo'), you
could also do this:

import foo.bar as bar

...and that restriction is where your problem lies.



In other words, since datetime.datetime is a class, not a module, you 
can't just import it.






2.I am also comfused that "datetime.datetime" is a function but whithin 
"datetime.datetime" there are lots of other functions. So what is the type of 
"datetime.datetime" on earth? is it a function, or a class or a folder(library) here?




As I said before, datetime.datetime is a class, and the functions within 
it are called methods.


You can see it all for yourself very easily.  Use the __file__ attribute 
to locate the source for datetime module on your system.  Here's what it 
looks like on mine:


>>> import datetime
>>> datetime.__file__
'/usr/local/lib/python3.3/datetime.py'

Then you can go look at that file.  For my copy, the datetime class 
begins at 1301.  But you can just search for the following line:




class datetime(date):

HTH

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


Re: Newbie: question regarding references and class relationships

2013-06-10 Thread Dave Angel

On 06/10/2013 01:42 PM, Rui Maciel wrote:

Peter Otten wrote:


Have you read the code in the interpreter session I posted?

If you do not agree that the demonstrated behaviour is puzzling I'll have
to drop my claim...


I don't see how it should be puzzling.  You've deleted the attribute, so it
ceassed to exist.


Clearly you didn't reason through all the code in Peter's example.





Likewise if you can show a benefit of the


position = []


line.


I wrote the code that way to declare intent and help document the code.  In
this case that the class Point is expected to have an attribute named
position which will point to a list.



So why do you also have an instance attribute of the same name?  If you 
really want all instances to have the same value for position, you'd 
better change the __init__() function so it doesn't mask that single value.


Could it be that you really meant that instances of class Point are each 
expected to have an attribute named Position?  Could it be that you want 
each instance's position to be independent of the others?


By having a class attribute with the same name as the instance 
attribute, you're occasionally going to use the class version when you 
meant the instance one.


I suspect you didn't realize the distinction between class attributes 
and instance attributes, and that a comment would be a much better way 
to communicate than creating a misleading value.


In one of your other messages, you asked:

> How do you guarantee that any object of a class has a
>  specific set of attributes?

Answer is to define those INSTANCE attributes in the __init__() method 
(or occasionally in the __new__() method), and to make sure you don't 
ever delete them.  The attributes of the object are instance attributes, 
while the attributes defined inside the class are class attributes.


Occasionally, it can be useful to let a class attribute be a 'backup' to 
the instance attributes, but you've got to think through your use case. 
 If memory is really tight, and if nearly all of the instances want the 
same value, then you could omit the instance attribute except for the 
exceptional ones, and let the class attribute fill in.  But as Peter 
says, if it's mutable, you then open yourself to somebody changing them 
all, thinking it was only changing the one.  But there are good reasons 
not to use this trick to save memory.



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


Re: Popen and reading stdout in windows

2013-06-10 Thread Dave Angel

On 06/10/2013 02:37 PM, Joseph L. Casale wrote:

I have a use where writing an interim file is not convenient and I was hoping to
iterate through maybe 100k lines of output by a process as its generated or
roughly anyways.

Seems to be a common question on ST, and more easily solved in Linux.
Anyone currently doing this with Python 2.7 in windows and can share some
guidance?



You leave out an awful amount of detail.  I have no idea what ST is, so 
I'll have to guess your real problem.


You've got a process (myprog.exe) which generates a medium amount of 
output to stdout, and you want to process that data in a python program 
as it's being output, but without first writing it to a file.


If by process you meant grep, the answer would be as simple as

myprocess | grep  parm1 parm2

But you want to write something (not called grep) in Python.

myprocess | python myfilter.py

The question is how to write myfilter.py


Answer is to use stdin as you would a file.  it's already open for you, 
and it'll get the data as it's being generated (plus or minus some 
buffering).  So you can simply do something like:




import sys
for index, line in enumerate(sys.stdin):
print index, line


This trivial "filter" adds a line number in front of every line.  But 
you could do anything there.  And you might not need enumerate if you 
don't care about the line number.


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


Re: Newbie: question regarding references and class relationships

2013-06-10 Thread Dave Angel

On 06/10/2013 06:54 PM, Chris Angelico wrote:

On Tue, Jun 11, 2013 at 8:39 AM, Grant Edwards  wrote:

On 2013-06-10, Terry Jan Reedy  wrote:


Another principle similar to 'Don't add extraneous code' is 'Don't
rebind builtins'.


OK, we've all done it by accident (especially when starting out), but
are there people that rebind builtins intentionally?


There are times when you don't care what you shadow, like using id for
a database ID.

ChrisA



And times where you're deliberately replacing a built-in

try:
   input = raw_input
except 



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


Re: Do you consider Python a 4GL? Why (not)?

2013-06-11 Thread Dave Angel

On 06/11/2013 03:48 PM, Laurent Pointal wrote:

Dennis Lee Bieber wrote:


On Tue, 4 Jun 2013 18:17:33 -0700, Dan Stromberg 
declaimed the following in gmane.comp.python.general:

 



The C compiler suites used this ability to read the error log from a
compile, and move to the line/column in the source file associated with
each error. (Before "integrated" development environments)


This is a + for compiled environments that you effectively cannot have with
Python, non-syntaxic errors found at runtime.



Sure.  I think they're usually called exceptions.  And lo and behold, 
they come with filenames and line numbers.




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


Re: Simple algorithm question - how to reorder a sequence economically

2013-06-12 Thread Dave Angel

On 05/25/2013 09:49 PM, Roy Smith wrote:

In article <15a1bb3a-514c-454e-a966-243c84123...@googlegroups.com>,
  John Ladasky  wrote:


Because someone's got to say it... "The generation of random numbers is too
important to be left to chance." ‹ Robert R. Coveyou


Absolutely.  I know just enough about random number generation to
understand that I don't really know anything about it :-)

That being said, people who really care about random numbers, tend to
rely on some sort of physical process instead of computer algorithms.  A
classic example would be /dev/random.  A somewhat more fun example is
http://www.youtube.com/watch?v=7n8LNxGbZbs.  Something radioactive and a
geiger counter are a good source of randomness (time intervals between
decay events).




That's good unless you're a cat, and you belong to Schroedinger...


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


Re: Survey of Python-in-browser technologies

2013-06-12 Thread Dave Angel

On 05/24/2013 08:38 PM, Carlos Nepomuceno wrote:



Date: Fri, 24 May 2013 17:11:18 -0700
Subject: Re: Survey of Python-in-browser technologies
From: drsali...@gmail.com
To: carlosnepomuc...@outlook.com
CC: python-list@python.org


Security is an important topic... but I'm not sure how I could gather
info about the security of these implementations.  Still, it's an idea
worth at least keeping in the back of my mind.


Security specialists opinions and facts about known vulnerabilities would be a 
start, although it may be time consuming to gather all data.

Just a thought! ;)  



Thank you for putting your response after the part you're quoting.  And 
for trimming out the irrelevant parts.


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


Re: User Input

2013-06-12 Thread Dave Angel

On 05/30/2013 10:03 AM, Eternaltheft wrote:

do you think ti would be better if i call drawBoard?



Better is meaningless without context.

Are you being charged per keystroke?

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


Re: A few questiosn about encoding

2013-06-12 Thread Dave Angel

On 06/12/2013 05:24 AM, Steven D'Aprano wrote:

On Wed, 12 Jun 2013 09:09:05 +, Νικόλαος Κούρας wrote:


Isn't 14 bits way to many to store a character ?


No.

There are 1114111 possible characters in Unicode. (And in Japan, they
sometimes use TRON instead of Unicode, which has even more.)

If you list out all the combinations of 14 bits:

   00
   01
   10
   11
[...]
   10
   11

you will see that there are only 32767 (2**15-1) such values. You can't
fit 1114111 characters with just 32767 values.




Actually, it's worse.  There are 16536 such values (2**14), assuming you 
include null, which you did in your list.


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


Re: Performance of list.index - how to speed up a silly algorithm?

2013-06-13 Thread Dave Angel

On 06/13/2013 10:55 AM, Onyxx wrote:

I would convert your list to a  pandas dataframe.



You're leaving a message on a public forum without any context in the 
message, using a title that was apparently last used in 2010.


Are you really trying to reply to a message from over 3 years ago???

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


Re: Debugging memory leaks

2013-06-13 Thread Dave Angel

On 06/13/2013 02:07 PM, writeson wrote:

Dieter,

Thanks for the response, and you're correct, debugging memory leaks is tough! So far I 
haven't had much luck other than determining I have a leak. I've used objgraph to see 
that objects are being created that don't seem to get cleaned up. What I can't figure out 
so far is why, they are local variable objects that "should" get cleaned up 
when they go out scope.



Pure python code shouldn't have any leaks, but instead can have what I 
call stagnation.  That's data that's no longer useful, but the program 
has fooled the system into thinking it should hang onto it.


A leak happens in C code, when all the pointers to a given hunk of 
memory have gone away, and there's no way to access it any longer.


In pure Python, you don't work with pointers, but with references, and 
they are ref-counted.  When the count goes to zero, the object is freed. 
 Periodically a gc sweep happens, which catches those circular 
references which never actually go to zero.



So post a fragment of code that seems to cause the problem, and maybe 
someone can explain why.


1) objects with a __del__() method
2) objects that are "cached" by some mechanism
3) objects that collectively represent a lot of data
4) objects that are exposed to buggy C code


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


Re: Creating a Super Simple WWW Link, Copy, & Paste into Spreadsheet Program

2013-06-13 Thread Dave Angel

On 06/13/2013 03:28 PM, buford.lum...@gmail.com wrote:

Hi, I'm new to Python. Would someone be able to write me and/or to show me how 
to write a simple program that:


Hi, welcome to Python, and to the Python-list

It's NOT a simple program, except by a very constrained definition of 
simple.




1-follows a hyperlink from MS Excel to the internet (one of many links like 
this, http://www.zipdatamaps.com/76180, for e.g.) and then,

2-copies some data (a population number, e.g. 54195) and then,

3-pastes that data back into the same MS Excel spreadsheet, into the adjacent 
cell.

... and that’s it... row after row of hyperlinks all in one column...



What's the real problem, or is it assignment?  Do you have lots of 
repetitive data you want to fetch once a day from many websites?  Do you 
have an assignment that constrains you to use Excel and Windows, and 
Python?  Do you have a boss that likes innovation?  Are you supposed to 
fetch the links from a live instance of Excel ?


What version of Python, and what OS does this have to run on?

If you break the problem into its component parts, SOME of them are 
fairly simple.  If you try to solve the problem as a whole, it's not 
simple, unless you can just copy much of it from your textbook, or from 
earlier assignments.


If this were my problem, I'd throw out Excel to begin with.  If your 
hyperlinks happen to be in an excel spreadsheet, then export them, 
probably to a csv file.  Do that by hand.  If it later proves valuable 
to automate that, consider it a new problem.  Similarly getting the data 
back into Excel -- just use csv files.


So now you have a URL, and you want to get something from the web.  You 
could use one of the urlib libraries to fetch the page.  You're pretty 
vague about "some data" but you could use substring to extract some 
bytes from the page.


You can use the csv module to load in the spreadsheet, and iterate 
through the rows.  For each row, you could use the previous paragraph to 
convert the URL into some data.  Then write the row back out, but to a 
different csv file.


If you want anything more specific than that (and probably not from me), 
you'd have to get a lot more specific about your real requirements.  And 
convince somebody that it's not homework.


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


Re: Turnign greek-iso filenames => utf-8 iso

2013-06-13 Thread Dave Angel

On 06/13/2013 05:46 PM, Chris Angelico wrote:

On Fri, Jun 14, 2013 at 3:48 AM, Νικόλαος Κούρας  wrote:




You are right, but i still believe Stevn would not act maliciously in the
server.  He proved himself very helpfull already.


You thought that about me, too. (And you were still correct. I did not
act maliciously, I just didn't do what you thought I'd do.) By the
time you know what someone will do with your server, it is too late.
And remember, I made it really obvious what I'd done; someone else may
well not.

Oh, and as to privilege escalation... there have been exploits found
in various applications, but the biggest one *ever* is the social
attack. It'd be VERY easy for Steven to get access, put a file in his
home directory, ask you to run it as root, and give himself full
access. And how would you know what that script does? You are
incompetent at managing a Linux system. You would be compromised
faster than an unpatched XP.

ChrisA



Perhaps more relevant is changes that are made by mistake, or by side 
effect of software tools, or by virus or by adware.  When you unlock a 
door, you're never sure just what will happen.  This is why even with my 
own system, I use the least-privileged logon that lets me do what I need 
to do.


I was involved in cleaning up the mess left behind by some guys who 
installed an April-fools joke on their boss' machine.  They didn't mean 
any harm, but there code had bugs.


And when new to Unix, I once typed a very complicated command (involving 
the find program, but also invoking other code) which would have had the 
final effect of deleting our entire source tree, including the (RCS) 
source control.  I would have tested the operation first, except that 
some fool disabled the editor for csh when running as root.  Anyway, the 
only thing that saved me was that Unix (in that era) had such a slow 
file system that I was able to kill it before it deleted a half-dozen 
file.  Nothing volatile was lost, and the missing files were trivial to 
restore from the daily backup tapes.


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


Re: how to use two threads to produce even and odd numbers?

2013-06-14 Thread Dave Angel

On 06/14/2013 07:50 AM, Zoe Wendy wrote:

Welcome to the forum.  Are you new to Python?  Are you new to 
programming?  What version of Python are you using?  Is this a class 
assignment?



I am going to compile a small python program in order to use Queue to produce a 
random with a thread.


That sentence doesn't parse.


For example,  using one thread to print odd number, while another thread to 
print even number.



Is there a reason for that?  What's your real goal?


Here is my codes, please offer me some advice:


First advice is not to post in html, as it frequently loses indentation 
(and other things)  All of your code fragment is at the left margin. 
Please post as text message.  And avoid googlegroups, as it will greatly 
reduce the number of people willing to read your messages.  If you're 
subscribed to the list (in non-digest form), simply use your email 
program, telling it to post as text messages.


Next - you don't actually use the Queue.




import threading
import random
import time
from Queue import Queue

class jishu (threading.Thread):

def __init__(self, threadname, queue):
threading.Thread.__init__(self, name = threadname)
self.sharedata = queue

def run(self):
for i %2 == 1 in range(200):
print self.getName(),'adding',i,'to queue'


This will intermix parts of the line with the ones printed by the other 
thread.



self.sharedata.put(i)
time.sleep(random.randrange(10)/10.0)
print self.getName(),'Finished'


# oushu thread

class oushu(threading.Thread):


def __init__(self, threadname, queue):
threading.Thread.__init__(self, name = threadname)
self.sharedata = queue


def run(self):

for i %2 == 0 in range(200):
print self.getName(),'got a value:',self.sharedata.get()
time.sleep(random.randrange(10)/10.0)
print self.getName(),'Finished'



Once the indentation is fixed, this code won't actually do anything 
because you lack any code to instantiate these classes.


Did you mean to use the queues to pipe the text back to the main thread, 
so that it can be printed discretely?


You do realize that compute-bound threads are counterproductive? Two 
threads will probably take much longer to run than one.  If your real 
goal is to partially randomize the order that the numbers are picked, 
there are much simpler ways to do it.


On the other hand, if this is an assignment, or if it's leading up to a 
much more complex problem, then it's a good start.


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


Re: Version Control Software

2013-06-14 Thread Dave Angel

On 06/14/2013 10:24 AM, Grant Edwards wrote:

On 2013-06-14, Roy Smith  wrote:


All that being said, it is, as Anssi points out, a horrible, bloated,
overpriced, complicated mess which requires teams of specially
trained ClearCase admins to run.  In other words, it's exactly the
sort of thing big, stupid, Fortune-500 companies buy because the IBM
salesperson plays golf with the CIO.


Years ago, I worked at one largish company where a couple of the
embedded development projects used ClearCase.  The rest of us used CVS
or RCS or some other cheap commercial systems.  Judging by those
results, ClearCase requires a full-time administrator for every 10 or
so users.  The other systems seemed to require almost no regular
administration, and what was required was handled by the developers
themselves (mayby a couple hours per month).  The cost of ClearCase
was also sky-high.



if I remember rightly, it was about two-thousand dollars per seat.  And 
the people I saw using it were using XCOPY to copy the stuff they needed 
onto their local drives, then disabling the ClearCase service so they 
could get some real work done.  Compiles were about 10x slower with the 
service active.


Now that was on Windows NT, when Clearcase was first porting from Unix. 
 So perhaps things have improved.



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


Re: Memory usage steadily going up while pickling objects

2013-06-14 Thread Dave Angel

On 06/14/2013 07:04 PM, Giorgos Tzampanakis wrote:

I have a program that saves lots (about 800k) objects into a shelve
database (I'm using sqlite3dbm for this since all the default python dbm
packages seem to be unreliable and effectively unusable, but this is
another discussion).

The process takes about 10-15 minutes. During that time I see memory usage
steadily rising, sometimes resulting in a MemoryError. Now, there is a
chance that my code is keeping unneeded references to the stored objects,
but I have debugged it thoroughly and haven't found any.

So I'm beginning to suspect that the pickle module might be keeping an
internal cache of objects being pickled. Is this true?



You can learn quite a bit by using the  sys.getrefcount() function.  If 
you think a variable has only one reference (if it had none, it'd be 
very hard to test), and you call sys.getrefcount(), you can check if 
your assumption is right.


Note that if the object is part of a complex object, there may be 
several mutual references, so the count may be more than you expect. 
But you can still check the count before and after calling the pickle 
stuff, and see if it has increased.


Note that even if it has not, that doesn't prove you don't have a problem.

Could the problem be the sqlite stuff?  Can you disable that part of the 
logic, and see whether just creating the data still produces the leak?



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


Re: Fatal Python error: Py_Initialize: can't initialize sys standard streams

2013-06-15 Thread Dave Angel

On 06/15/2013 10:44 PM, lucabrasi wrote:

On Saturday, June 15, 2013 5:03:27 PM UTC-7, MRAB wrote:

On 15/06/2013 23:10, alex23 wrote:




   should be banned>



Do you have a separate installation of Python? It's possible it may be



conflicting. If you rename it's folder to something else (which will



temporarily break that install), do you still see this same issue in



Inkscape?








Your message was a hard-to-read doble-spaced copy of someone else's 
comments.  If you have nothing to add, why bother posting?  Especially 
with googlegroups.


If you do have something to say, make sure it follows the part you're 
quoting, and that it does not begin with those bracket separators. 
Otherwise it simply lies buried in the context, and your contribution or 
question is lost.


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


Re: OT: C vs Python terminology

2013-06-16 Thread Dave Angel

On 06/16/2013 07:22 AM, Andreas Perstinger wrote:

On 16.06.2013 08:32, Denis McMahon wrote:

C:

int a, b;
b = 6;
a = b;

In C, this places the numeric value 6 into the memory location identified
by the variable "b",


so far so good.


then copies the value from the location pointed to by "b" into the
location pointed to by "a".


Wrong. Neither "a" nor "b" are pointers, thus they don't point to a
memory location.
This part should be written as
"then copies the value at the location identified by "b" to the location
identified by "a".


But it doesn't.  It binds b to the same object to which a is currently 
bound.



b is a pointer to a memory location containing the value 6

 > a is a pointer to another memory location also containing the value 6

Again, neither "a" nor "b" are pointers.
"b" is the name of a memory location containing the integer value 6.
"a" is the name of another memory location containing the integer value 6.



Not even close.  If you don't like the terms "bound" or "points", the 
perhaps you'd be happy with "b" is the name that currently knows how to 
find an int object containing 6.  That object has no name, and never 
will.  And it can exist for a long time with no names directly bound to it.



Python:

b = 6
a = b

In Python, this first puts the value 6 in in a memory location and points
"b" at that memory location, then makes "a" point to the same memory
location as "b" points to.

b is a pointer to a memory location containing the value 6
a is a pointer to the same memory location


I wouldn't use the term "pointer" in context with Python. Using the
terms from the language reference I would write that as
"In Python, this first creates an integer object with value 6 and then
binds the name "b" to it. Then it binds the name "a" to the same object.
Thus both "a" and "b" reference the same object, i.e. they are different
names for the same object."

Bye, Andreas


Doing all of this discussion with immutable objects masks the real 
behavior, as someone can use a false model and seem to justify that 
model.  I don't think you're doing that, but others in the thread are.


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


Re: OT: C vs Python terminology

2013-06-16 Thread Dave Angel

On 06/16/2013 11:02 AM, Andreas Perstinger wrote:

On 16.06.2013 14:55, Dave Angel wrote:

On 06/16/2013 07:22 AM, Andreas Perstinger wrote:
   
But it doesn't.  It binds b to the same object to which a is currently
bound.


Are you aware that Denis was talking about the behaviour of C in the
above quote?



Nope, missed that.  Sorry for the noise.


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


Re: Variables versus name bindings [Re: A certainl part of an if() structure never gets executed.]

2013-06-17 Thread Dave Angel

On 06/17/2013 08:41 PM, Steven D'Aprano wrote:




In Python 3.2 and older, the data will be either UTF-4 or UTF-8, selected
when the Python compiler itself is compiled.


I think that was a typo.  Do you perhaps UCS-2 or UCS-4


In Python 3.3, the data will
be stored in either Latin-1, UTF-4, or UTF-8, depending on the contents
of the string.




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


Re: Variables versus name bindings [Re: A certainl part of an if() structure never gets executed.]

2013-06-17 Thread Dave Angel

On 06/17/2013 10:42 PM, Steven D'Aprano wrote:

On Mon, 17 Jun 2013 21:06:57 -0400, Dave Angel wrote:


On 06/17/2013 08:41 PM, Steven D'Aprano wrote:


 

In Python 3.2 and older, the data will be either UTF-4 or UTF-8,
selected when the Python compiler itself is compiled.


I think that was a typo.  Do you perhaps UCS-2 or UCS-4


Yes, that would be better.

UCS-2 is identical to UTF-16, except it doesn't support non-BMP
characters and therefore doesn't have surrogate pairs.

UCS-4 is functionally equivalent to UTF-16,


Perhaps you mean UTF-32 ?

 as far as I can tell. (I'm

not really sure what the difference is.)



Now you've got me curious, by bringing up surrogate pairs.  Do you know 
whether a narrow build (say 3.2) really works as UTF16, so when you 
encode a surrogate pair (4 bytes) to UTF-8, it encodes a single Unicode 
character into a single UTF-8 sequence (prob.  4 bytes long) ?




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


Re: os.putenv() has no effect

2013-06-18 Thread Dave Angel

On 06/18/2013 12:49 PM, Johannes Bauer wrote:

Hi group,

I've tracked down a bug in my application to a rather strange
phaenomenon: os.putenv() doesn't seem to have any effect on my platform
(x86-64 Gentoo Linux, Python 3.2.3):


os.getenv("PATH")

'/usr/joebin:/usr/local/bin:/usr/bin:/bin:/usr/games/bin:/usr/sbin:/sbin:~/bin'

os.putenv("PATH", "/")
os.getenv("PATH")

'/usr/joebin:/usr/local/bin:/usr/bin:/bin:/usr/games/bin:/usr/sbin:/sbin:~/bin'



os.getenv("FOO")
os.putenv("FOO", "BAR")
os.getenv("FOO")



Does anybody know why this would happen or what I could be doing wrong?
Help is greatly appreciated.



Quoting (retyping) from the getenv docs, "...however, calls to putenv() 
don't update os.environ, so it is actually preferable to assign to items 
of os.environ."


As to why, I'm not at all sure.  Only that many environments don't 
support putenv().  But why that should stop it working in the obvious 
way ?  No idea.


os.environ is not an ordinary dict, it's a "mapping object".  And among 
other things, when you modify os.environ, Python will call putenv. 
Quoting from the os.environ docs, "If the platform supports the putenv() 
function, this mapping may be used to modify the environment.  putenv() 
will be called automatically wehn the mapping is modified."


In other words, you shouldn't use putenv(), but instead modify os.environ.

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


Re: Why is regex so slow?

2013-06-18 Thread Dave Angel

On 06/18/2013 09:51 PM, Steven D'Aprano wrote:

   


Even if the regex engine is just as efficient at doing simple character
matching as `in`, and it probably isn't, your regex tries to match all
eleven characters of "ENQUEUEING" while the `in` test only has to match
three, "ENQ".



The rest of your post was valid, and useful, but there's a misconception 
in this paragraph;  I hope you don't mind me pointing it out.


In general, for simple substring searches, you can search for a large 
string faster than you can search for a smaller one.  I'd expect


if "ENQUEUING" in bigbuffer

to be faster than

if "ENQ"  in bigbuffer

assuming that all occurrences of ENQ will actually match the whole 
thing.  If CPython's implementation doesn't show the speed difference, 
maybe there's some room for optimization.


See Boyer-Moore if you want a peek at the algorithm.

When I was writiing a simple search program, I could typically search 
for a 4-character string faster than REP SCASB could match a one 
character string.  And that's a single instruction (with prefix).

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


Re: A certainl part of an if() structure never gets executed.

2013-06-18 Thread Dave Angel
I think this is an excellent description of name binding with mutable 
objects.  I just have one clarification to insert below.


On 06/19/2013 01:08 AM, Tim Roberts wrote:

Nick the Gr33k  wrote:


On 16/6/2013 4:55 ??, Tim Roberts wrote:


Nick the Gr33k  wrote:
Because Python lets you use arbitrary values in a Boolean context, the net
result is exactly the same.


What is an arbitrary value? don even knwo what arbitrary means literally
in English.


Basically, it means "any".  In Python, you can use ANY value where a
Boolean is expected.  All types have a Boolean meaning.  For integers, 0 is
false, anything else is true.  For strings, an empty string "" is false,
anything else is true.  For lists, an empty list [] is false, anything else
is true.  For tuples, an empty tuple () is false, anything else is true.
For dicts, an empty dict {} is false, anything else is true.


The argument being returned in an "and" or "or" expression is the one
that *determined' the evaluation of the expression.


That's not exactly how I'd put it, but the statement is correct.  The last
thing it had to evaulate is the result of the expression.


And actually what's being returned is not the argument itself but the
argument's value.


But this is no different than any other programming language.  Expressions
always use the value of their operands, and they always return a value.

The name vs value thing is critical to understanding Python, in my opinion,
and it can be a stumbling block when you're coming from another language.
Here's how I think about it.

Python had two distinct spaces: there is a space for names, and there is a
space for objects (which are values).  Objects live in a nameless, faceless
object cloud.

A name is always bound to some object (which might be the "None" object). A
name always knows its object, but an object never knows what names it is
bound to.

The only things that can be used in expressions and function arguments are
objects.  Names are merely the way we specify which objects to be used.


Names are *one of* the ways we specify which objects are to be used. 
(We can also specify objects via an container and a subscript or slice, 
or via an attribute of another object.  And probably another way or two.)




 a = [3]

That creates a nameless list containing a single integer object with the
value 3.  It then binds the name "a" to that list.  Note that the list has
no clue that it is bound to any names.

 b = a

That binds "b" to the same list.  "b" and "a" are not related in any way,
except that they happen to be bound to the same object.  Note that there is
still only one list.

 a.append(4)

That modifies the list so that it now contains [3,4].  b is bound to the
same list, so if you
 print(b)
you'll see [3,4]

Now, let's say I do this:

 a = [5]

Here's where people get tripped up.  This does not change our original
list.  Instead, it creates a new nameless list containing 5, and binds the
name a to that list.  a and b are no longer bound to the same object.




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


Re: A certainl part of an if() structure never gets executed.

2013-06-19 Thread Dave Angel

On 06/19/2013 03:14 AM, Chris Angelico wrote:

On Wed, Jun 19, 2013 at 3:42 PM, Dave Angel  wrote:

Names are *one of* the ways we specify which objects are to be used. (We can
also specify objects via an container and a subscript or slice, or via an
attribute of another object.  And probably another way or two.)


But you always have to bootstrap it with either a name.


Whatever bootstrap really means in this context.  But if you have 
myname[3] + myname[5], the two objects being added are identified by a 
subscript operation, not just a name.



Or a literal.


A literal is used to create an object, and acts like a temporary name 
for that object, but once again the object being operated on isn't 
necessarily that one. You can subscript and get attributes from a 
literal as well.



So those are the only two ways to specify which objects are to be
used.



That would be a pretty weak language, and it wouldn't be python.


Now if you considered "." and "[" as operators, then I could understand 
your point.  But

   http://docs.python.org/3/reference/lexical_analysis.html#operators
seems to say differently.

Also see
   http://docs.python.org/3/reference/expressions.html#primaries


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


Re: Problem with the "for" loop syntax

2013-06-19 Thread Dave Angel

On 06/19/2013 05:14 PM, arturo balbuena wrote:

Hello guys...
I´m a begginer in Python, I'm doing a Hangman game, but I'm having trouble with 
this blank space. I would be greatful if you help me. :)

Here's my code:

http://snipplr.com/view/71581/hangman/

When I run the code it says: Invalid Syntax and this is the error:

http://i.imgur.com/jKYOPMY.png

http://i.imgur.com/ySoOZFR.png




If you want us to read it, put it in your message.  Show at least a few 
lines before and after the syntax error, and show the error itself, as 
text of course.  Use copy/paste.


Of course that assumes you're using a proper console/shell, and know how 
to use it.  So if you have to ask about that, start there.


In addition, specify the python version, and if appropriate, the OS and 
its version.


Generally, you can find your own problem.  Syntax errors that seem 
confusing are frequently really on the line before the line in which 
they're "discovered."



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


Re: New line conversion with Popen attached to a pty

2013-06-21 Thread Dave Angel

On 06/20/2013 06:20 AM, Jonathan Harden wrote:

Hi,

We have a class which executes external processes in a controlled environment and does 
"things" specified by the client program with each line of output. To do this 
we have been attaching stdout from the subprocess.Popen to a pseudo terminal (pty) made 
with pty.openempty and opened with os.fdopen. I noticed that we kept getting a bunch of 
extra new line characters.



Duplicate thread, delayed by the vagaries of email and gateways.  In 
that thread, the problem has been happily resolved.


Any responses, please keep them on the other thread with the same title.


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


Re: n00b question on spacing

2013-06-22 Thread Dave Angel

On 06/22/2013 07:12 PM, Chris Angelico wrote:

On Sun, Jun 23, 2013 at 1:24 AM, Rick Johnson
 wrote:

   _fmtstr = "Item wrote to MongoDB database {0}, {1}"
   msg = _fmtstr.format(_arg1, _arg2)


As a general rule, I don't like separating format strings and their
arguments. That's one of the more annoying costs of i18n. Keep them in
a single expression if you possibly can.



On the contrary, i18n should be done with config files.  The format 
string is the key to the actual string which is located in the 
file/dict.  Otherwise you're shipping separate source files for each 
language -- blecch.


The program that's intended to be internationalized is written using 
"programmereze" strings.  That's a strange inhuman language that's only 
approximately comprehensible by the developer and close associates. 
Then that gets translated into a bunch of language-specific config 
files, with English probably being one of them.


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


Re: n00b question on spacing

2013-06-22 Thread Dave Angel

On 06/22/2013 07:37 PM, Chris Angelico wrote:

On Sun, Jun 23, 2013 at 9:28 AM, Dave Angel  wrote:

On 06/22/2013 07:12 PM, Chris Angelico wrote:


On Sun, Jun 23, 2013 at 1:24 AM, Rick Johnson
 wrote:


_fmtstr = "Item wrote to MongoDB database {0}, {1}"
msg = _fmtstr.format(_arg1, _arg2)



As a general rule, I don't like separating format strings and their
arguments. That's one of the more annoying costs of i18n. Keep them in
a single expression if you possibly can.



On the contrary, i18n should be done with config files.  The format string


**as specified in the physical program**


is the key to the actual string which is located in the file/dict.
Otherwise you're shipping separate source files for each language -- blecch.


What I was trying to say is that the programmereze format string in the 
code is replaced at runtime by the French format string in the config file.




The simplest way to translate is to localize the format string; that's
the point of .format()'s named argument system (since it lets you
localize in a way that reorders the placeholders). What that does is
it puts the format string away in a config file, while the replaceable
parts are here in the source. That's why I say that's a cost of i18n -
it's a penalty that has to be paid in order to move text strings away.




Certainly the reorderability of the format string is significant.  Not 
only can it be reordered, but more than one instance of some of the 
values is permissible if needed.  (What's missing is a decent handling 
of such things as singular/plural, where you want a different version 
per country of one (or a few) words from the format string, based on 
whether a value is exactly 1.)


But the language is missing the indirection I described.  So you have to 
use a (function or whatever) wrapper to look up the actual format string 
in the config file.  My point is by making that file equivalent to a 
dict, you get to have an executable program in "programmereze" before 
creating any config files, but still able to handle any real language 
with one config file per language.


This is much preferable to the usual numeric lookup, where somebody 
specifies the 17th format string to be used at this place in the code. 
Even when you use C++ names, they're still only a crude approximation to 
the real purpose of the string.





The program that's intended to be internationalized is written using
"programmereze" strings.  That's a strange inhuman language that's only
approximately comprehensible by the developer and close associates. Then
that gets translated into a bunch of language-specific config files, with
English probably being one of them.


Heh. That's one way of looking at it... I don't really know what
language we speak; at what point is it deemed a separate dialect, and
at what point a unique language? Hmmm.

ChrisA




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


Re: n00b question on spacing

2013-06-22 Thread Dave Angel

On 06/22/2013 08:27 PM, Chris Angelico wrote:

On Sun, Jun 23, 2013 at 9:56 AM, Dave Angel  wrote:

On 06/22/2013 07:37 PM, Chris Angelico wrote:

On the contrary, i18n should be done with config files.  The format
string



**as specified in the physical program**



is the key to the actual string which is located in the file/dict.
Otherwise you're shipping separate source files for each language --
blecch.



What I was trying to say is that the programmereze format string in the code
is replaced at runtime by the French format string in the config file.

But the language is missing the indirection I described.  So you have to use
a (function or whatever) wrapper to look up the actual format string in the
config file.  My point is by making that file equivalent to a dict, you get
to have an executable program in "programmereze" before creating any config
files, but still able to handle any real language with one config file per
language.

This is much preferable to the usual numeric lookup, where somebody
specifies the 17th format string to be used at this place in the code. Even
when you use C++ names, they're still only a crude approximation to the real
purpose of the string.


What you're saying is that there are ways to ameliorate the problem
with i18n. What that means is that you broadly agree with my main
point, which is that the format string should be kept as close as
possible to the arguments. When you're NOT translating to multiple
languages, the string-literal is the most appropriate way to lay this
out, imo.



Absolutely (very broadly).  And when I am, it's still a string literal, 
just not the one the customer will see.  It still should be next to the 
arguments of the format. I'd be replacing something like:


line = "Customer's name: {%0}, address {%1}".format(args)

with

line = i18n(current_language, "Cussom's name: {%0}, addr {%1}", thename, 
theaddr)


And the English config file would look like (not counting any escaping 
or whatevers):


#SIG - American English, headerline
Cussom's name: {%0}, addr {%1}
   Customer's name: {%0}, addr {%1}

The key has the misspelling's and approximations, while the value has 
the actual string to be used as the object of format.

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


Re: n00b question on spacing

2013-06-22 Thread Dave Angel

On 06/22/2013 09:20 PM, MRAB wrote:

On 23/06/2013 00:56, Dave Angel wrote:

 


Certainly the reorderability of the format string is significant.  Not
only can it be reordered, but more than one instance of some of the
values is permissible if needed.  (What's missing is a decent handling
of such things as singular/plural, where you want a different version
per country of one (or a few) words from the format string, based on
whether a value is exactly 1.)


[snip]
One vs not-one isn't good enough. Some languages use the singular with
any numbers ending in '1'. Some languages have singular, dual, and
plural. Etc. It's surprising how inventive people can be! :-)



And there are plenty more where that came from.  Thanks for the reminder.

I guess instead of a format, we need a DWIM.

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


  1   2   3   4   5   6   7   8   9   10   >