Right solution to unicode error?

2012-11-07 Thread Anders
I've run into a Unicode error, and despite doing some googling, I
can't figure out the right way to fix it. I have a Python 2.6 script
that reads my Outlook 2010 task list. I'm able to read the tasks from
Outlook and store them as a list of objects without a hitch.  But when
I try to print the tasks' subjects, one of the tasks is generating an
error:

Traceback (most recent call last):
  File "outlook_tasks.py", line 66, in 
my_tasks.dump_today_tasks()
  File "C:\Users\Anders\code\Task List\tasks.py", line 29, in
dump_today_tasks
print task.subject
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in
position 42: ordinal not in range(128)

(where task.subject  was previously assigned the value of
task.Subject, aka the Subject property of an Outlook 2010 TaskItem)

>From what I understand from reading online, the error is telling me
that the subject line  contains an en dash and that Python is trying
to convert to ascii and failing (as it should).

Here's where I'm getting stuck.  In the code above I was just printing
the subject so I can see whether the script is working properly.
Ultimately what I want to do is parse the tasks I'm interested in and
then create an HTML file containing those tasks.  Given that, what's
the best way to fix this problem?

BTW, if there's a clear description of the best solution for this
particular problem – i.e., where I want to ultimately display the
results as HTML – please feel free to refer me to the link. I tried
reading a number of docs on the web but still feel pretty lost.

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


PyQt app in seperate thread

2006-11-22 Thread anders
I am writing a plugin for a piece of software in python, and I want to
start up a PyQt GUI in the plugin, without stalling the main thread
while the gui is running (later i will want to pass messages between
the main thread and the gui thread).

I'm new to pyqt, so I'm probably doing something very silly, but for
the moment I'm just trying to get the first pyqt tutorial example
running in a seperate thread:

8<

import sys
from PyQt4 import QtGui
from PyQt4 import QtCore

class MyThread( QtCore.QThread ):
def __init__( self ):
QtCore.QThread.__init__( self )

def run( self ):
app = QtGui.QApplication( sys.argv )
hello = QtGui.QPushButton( 'Hello world!' )
hello.resize( 500, 500 )
hello.show()
app.exec_()
QtCore.QThread.terminate(  )



mt = MyThread()
mt.start()
print 'Main thread continuing...'
mt.wait()
print 'GUI thread finished.'

8<

The app starts up (with a warning WARNING: QApplication was not created
in the main() thread. ). I get a window, but no button, and clicking on
the close button does nothing and I have to force the program to quit.

There's got to be a way to get this working, right? Can anyone help me
along the right path?

Cheers,

Anders

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


Re: PyQt app in seperate thread

2006-11-22 Thread anders

Phil Thompson wrote:
> On Wednesday 22 November 2006 12:37 pm, anders wrote:
> > I am writing a plugin for a piece of software in python, and I want to
> > start up a PyQt GUI in the plugin, without stalling the main thread
> > while the gui is running (later i will want to pass messages between
> > the main thread and the gui thread).
> >
> > I'm new to pyqt, so I'm probably doing something very silly, but for
> > the moment I'm just trying to get the first pyqt tutorial example
> > running in a seperate thread:
> >
> > 8<
> >
> > import sys
> > from PyQt4 import QtGui
> > from PyQt4 import QtCore
> >
> > class MyThread( QtCore.QThread ):
> > def __init__( self ):
> > QtCore.QThread.__init__( self )
> >
> > def run( self ):
> > app = QtGui.QApplication( sys.argv )
> > hello = QtGui.QPushButton( 'Hello world!' )
> > hello.resize( 500, 500 )
> > hello.show()
> > app.exec_()
> > QtCore.QThread.terminate(  )
> >
> >
> >
> > mt = MyThread()
> > mt.start()
> > print 'Main thread continuing...'
> > mt.wait()
> > print 'GUI thread finished.'
> >
> > 8<
> >
> > The app starts up (with a warning WARNING: QApplication was not created
> > in the main() thread. ). I get a window, but no button, and clicking on
> > the close button does nothing and I have to force the program to quit.
> >
> > There's got to be a way to get this working, right? Can anyone help me
> > along the right path?
>
> Read http://doc.trolltech.com/4.2/threads.html
>
> In particular the bit that says that exec_() must be called from the main
> thread and not from a QThread.
>
> Phil


OK so that's all good... so how do I go about doing what I want then?
Can I set up a window in the second thread and start its event loop
without running the event loop in the core app?

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


Re: PyQt app in seperate thread

2006-11-22 Thread anders

Phil Thompson wrote:
> On Wednesday 22 November 2006 2:06 pm, anders wrote:
> > Phil Thompson wrote:
> > > On Wednesday 22 November 2006 12:37 pm, anders wrote:
> > > > I am writing a plugin for a piece of software in python, and I want to
> > > > start up a PyQt GUI in the plugin, without stalling the main thread
> > > > while the gui is running (later i will want to pass messages between
> > > > the main thread and the gui thread).
> > > >
> > > > I'm new to pyqt, so I'm probably doing something very silly, but for
> > > > the moment I'm just trying to get the first pyqt tutorial example
> > > > running in a seperate thread:
> > > >
> > > > 8<
> > > >
> > > > import sys
> > > > from PyQt4 import QtGui
> > > > from PyQt4 import QtCore
> > > >
> > > > class MyThread( QtCore.QThread ):
> > > > def __init__( self ):
> > > > QtCore.QThread.__init__( self )
> > > >
> > > > def run( self ):
> > > > app = QtGui.QApplication( sys.argv )
> > > > hello = QtGui.QPushButton( 'Hello world!' )
> > > > hello.resize( 500, 500 )
> > > > hello.show()
> > > > app.exec_()
> > > > QtCore.QThread.terminate(  )
> > > >
> > > >
> > > >
> > > > mt = MyThread()
> > > > mt.start()
> > > > print 'Main thread continuing...'
> > > > mt.wait()
> > > > print 'GUI thread finished.'
> > > >
> > > > 8<
> > > >
> > > > The app starts up (with a warning WARNING: QApplication was not created
> > > > in the main() thread. ). I get a window, but no button, and clicking on
> > > > the close button does nothing and I have to force the program to quit.
> > > >
> > > > There's got to be a way to get this working, right? Can anyone help me
> > > > along the right path?
> > >
> > > Read http://doc.trolltech.com/4.2/threads.html
> > >
> > > In particular the bit that says that exec_() must be called from the main
> > > thread and not from a QThread.
> > >
> > > Phil
> >
> > OK so that's all good... so how do I go about doing what I want then?
> > Can I set up a window in the second thread and start its event loop
> > without running the event loop in the core app?
>
> No. Read the second sentence of the paragraph I referred to. Also read the
> section "QObject Reentrancy".
>
> Phil

OK I see that now. Thanks for pointing that out. So basically, I can't
do what I want at all. That's a bit of a pain. Is there no way of
tricking Qt into thinking I'm running it in the main thread?

A

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


Re: PyQt app in seperate thread

2006-11-22 Thread anders

Diez B. Roggisch wrote:
> > OK I see that now. Thanks for pointing that out. So basically, I can't
> > do what I want at all. That's a bit of a pain. Is there no way of
> > tricking Qt into thinking I'm running it in the main thread?
>
> Maybe you can either invert the thread-roles - that is, run your "main"
> application in a thread, and if needed start the Qt-thing, or you might
> consider spawning a process and using pyro. Which will work very neat, done
> so myself.
>
> Diez

Yeah I was thinking that's going to have to be the way to go... I can't
run the main app in a child thread, so I'll have to spawn the GUI as a
seperate process and communicate with it. Didn't know about pyro
though, thanks for the link. You've used it successfully with PyQt in a
seperate process?

Cheers,

Anders

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


Re: How to read the directory which the actively running python file is located in?

2006-12-01 Thread anders
in os module there is many funktion/methods to extract this information
to ask the path to the current running pythonprogram you can do likes
this

- CUT---
import os
print os.getcwd()

- CUT --

// Anders


Michael Malinowski skrev:

> Is there a way to read the directory that the currently running python file
> is located in?
> Cheers
> Mike.

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


Re: How to read the directory which the actively running python file is located in?

2006-12-01 Thread anders
in os module there is many funktion/methods to extract this information
to ask the path to the current running pythonprogram you can do likes
this

- CUT---
import os
print os.getcwd()

- CUT --

// Anders


Michael Malinowski skrev:

> Is there a way to read the directory that the currently running python file
> is located in?
> Cheers
> Mike.

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


I have a chance to do somting diffrent way not Python ?!

2007-04-28 Thread anders
Hi!
On my work we have a lot off diffrent server to make software for
diffrent os
from Windows, OS/X to Linux Solaris

Everyting is scripted with shell, but Windows  has batchfiles witch is
very
limited, compared to cshell etc.

So my boss has told me that it okej if i want to make somting better
och smooter,
for the windows machine.

First i looked a Ruby but didn't like it to interacting with the os,
nothinh wrong
but my eyes moved to Python becurse syntax is clean and every server
(not windows) has Python as base installed, and in the future i could
then move
the script to run on all servers.

So basicly i like advice about interac with os, compiler etc.
Nice webblinks to read more
and do/don't things.

best regards
Anders

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


GUI and distrubution

2007-08-24 Thread anders
I have looked att Python on www.showmedo.com
And after this i start testing writing som program i Python.
But...

So how is the preferably way to distribute software written i Python
i am NOT into hiding stuff, more a easy way of giving eg friends
a copy of the program without having them installtion a lott
och other stuff.

My next question is witch is the best GUI to use, also consider
the delivery question above.

// Anders

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


search speed

2009-01-30 Thread anders
Hi!
I have written a Python program that serach for specifik customer in
files (around 1000 files)
the trigger is LF01 + CUSTOMERNO

So a read all fils with dirchached

Then a loop thru all files each files is read with readLines() and
after that scaned

Today this works fine, it saves me a lot of manuall work, but a seach
takes around 5 min,
so my questin is is there another way of search in a file
(Today i step line for line and check)

What i like to find is just filenames for files with the customerdata
in, there can and often
is more than one,

English is not my first language and i hope someone understand my
beginner question
what i am looking for is somting like

if file.findInFile("LF01"):
...

Is there any library like this ??

Best Regards
Anders




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


Re: search speed

2009-01-31 Thread anders
Tanks everyone that spent time helping my, the help was great.
Best regards Anders
--
http://mail.python.org/mailman/listinfo/python-list


RE: Right solution to unicode error?

2012-11-08 Thread Anders Schneiderman
Thanks, Oscar and Ramit! This is exactly what I was looking for.

Anders 


> -Original Message-
> From: Oscar Benjamin [mailto:oscar.j.benja...@gmail.com]
> Sent: Wednesday, November 07, 2012 6:27 PM
> To: Anders Schneiderman
> Cc: python-list@python.org
> Subject: Re: Right solution to unicode error?
> 
> On 7 November 2012 22:17, Anders  wrote:
> >
> > Traceback (most recent call last):
> >   File "outlook_tasks.py", line 66, in 
> >     my_tasks.dump_today_tasks()
> >   File "C:\Users\Anders\code\Task List\tasks.py", line 29, in
> > dump_today_tasks
> > print task.subject
> > UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in
> > position 42: ordinal not in range(128)
> >
> > Here's where I'm getting stuck.  In the code above I was just printing
> > the subject so I can see whether the script is working properly.
> > Ultimately what I want to do is parse the tasks I'm interested in and
> > then create an HTML file containing those tasks.  Given that, what's
> > the best way to fix this problem?
> 
> Are you using cmd.exe (standard Windows terminal)? If so, it does not
> support unicode and Python is telling you that it cannot encode the string in 
> a
> way that can be understood by your terminal. You can try using chcp to set
> the code page to something that works with your script.
> 
> If you are only printing it for debugging purposes you can just print the 
> repr()
> of the string which will be ascii and will come out fine in your terminal. If 
> you
> want to write it to a html file you should encode the string with whatever
> encoding (probably utf-8) you use in the html file. If you really just want 
> your
> script to be able to print unicode characters then you need to use something
> other than cmd.exe (such as IDLE).
> 
> 
> Oscar

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


Create a contact book

2021-10-25 Thread anders Limpan
i would like to create a contact book were you can keep track of your friends. 
With this contact book you will both be able to add friends and view which 
friends that you have added. anyone interested in helping me out with this one 
?=)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Sorting NaNs

2018-06-10 Thread Anders Munch

Richard Damon wrote:


The two behaviors that I have heard suggested are:

1) If any of the inputs are a NaN, the median should be a NaN.
(Propagating the NaN as indicator of a numeric error)

2) Remove the NaNs from the input set and process what is left. If
nothing, then return a NaN (treating NaN as a 'No Data' placeholder).


3) Raise an exception.

I can't believe anyone even suggested 2).  "In the face of ambiguity, 
refuse the temptation to guess."


regards, Anders

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


Re: Sorting NaNs

2018-06-11 Thread Anders Munch

Steven D'Aprano:


It is not a guess if the user explicitly specifies that as the behaviour.


If that was the context, sure, no problem.

- Anders

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


Re: books: Dive into Python vs Beginning Python

2005-11-28 Thread Anders Eriksson
On Fri, 25 Nov 2005 11:25:43 +0100, Franz Mueller wrote:

> Hi,
> 
> which of the following books would you recommend:
> "Dive into Python" or "Beginning Python: From Novice to Professional"?
> 
Since "Dive into Python" is on the net, you can see for yourself if it's
any good (which I think it is!)

http://diveintopython.org/

// Anders
-- 
English isn't my first, or second, language. 
So anything rude or strange are due to the translation
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python connect to server using SSH protocol

2005-02-08 Thread Simon Anders
Hi
Laszlo Zsolt Nagy wrote:
[EMAIL PROTECTED] wrote:
How can python connect to server which use SSH protocol?
Is it easy since my python has to run third party vendor, write data,
read data inside the server (supercomputer).
 

In advance, I'm not sure if I understood your problem.  SSH is clearly a 
remote
shell. You will be able to execute other programs on the remote computer.
Is is suitable to use this:

child_stdin,child_stdout,child_stderr =  os.popen2('ssh -l my_username  
my_host')
This is what I was about to reply as well. But I did a short test 
program and encountered a problem:

import os
fi, foe = os.popen4 ('ssh dopey')
print >>fi, 'ls'
fi.close ()  # <-- this is annoying
for line in foe:
   print line,
foe.close ()
The above connects to a server, passes the command 'ls', which is 
executed there, and prints the returned result.

However, reading from foe succeeds only if fin has been closed before. 
An fi.flush() seems to be not sufficient. But if one wants Python to 
interactivly communicate with some shell on a remote machine, it is 
inconvenient to have to close and reopen the connection all the time.

There should be a better way.
   Simon
--
http://mail.python.org/mailman/listinfo/python-list


Operators as functions

2004-12-20 Thread Anders Andersson
Hello
I want to concatinate (I apologize for bad English, but it is not my 
native language) a list of strings to a string. I could use (I think):

s = ""
map(lambda x: s.append(x), theList)
But I want to do something like (I think that the code above is clumsy):
s = reduce("concatinating function", theList, "")
And here is the questions: What to replace "concatinating function" 
with? Can I in some way give the +-operator as an argument to the reduce 
function? I know operators can be sent as arguments in Haskell and since 
Python has functions as map, filter and listcomprehension etc. I hope it 
is possible in Python too. In Haskell I would write:

foldr (++) []
Thank you for answering!
--
Anders Andersson
--
http://mail.python.org/mailman/listinfo/python-list


Re: Operators as functions

2004-12-21 Thread Anders Andersson
Steve Holden wrote:
Anders Andersson wrote:
Hello
I want to concatinate (I apologize for bad English, but it is not my 
native language) a list of strings to a string. I could use (I think):

s = ""
map(lambda x: s.append(x), theList)
But I want to do something like (I think that the code above is clumsy):
s = reduce("concatinating function", theList, "")
And here is the questions: What to replace "concatinating function" 
with? Can I in some way give the +-operator as an argument to the 
reduce function? I know operators can be sent as arguments in Haskell 
and since Python has functions as map, filter and listcomprehension 
etc. I hope it is possible in Python too. In Haskell I would write:

foldr (++) []
Thank you for answering!
 >>> l = ["abc", "def", "ghi", "jkl"]
 >>> "".join(l)
'abcdefghijkl'
 >>> ", ".join(l)
'abc, def, ghi, jkl'
 >>>
regards
 Steve
Quiet unexpected, but very beautiful. I will use this! Thank you for 
replaying!

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


Re: Operators as functions

2004-12-21 Thread Anders Andersson
Peter Hansen wrote:
Anders Andersson wrote:
I want to concatinate (I apologize for bad English, but it is not my 
native language) a list of strings to a string. I could use (I think):

s = ""
map(lambda x: s.append(x), theList)
But I want to do something like (I think that the code above is clumsy):
s = reduce("concatinating function", theList, "")
And here is the questions: What to replace "concatinating function" 
with? Can I in some way give the +-operator as an argument to the 
reduce function? I know operators can be sent as arguments in Haskell 
and since Python has functions as map, filter and listcomprehension 
etc. I hope it is possible in Python too. In Haskell I would write:

You are looking for "import operator", followed by a use of
operator.add in the reduce() call.  Note, however, that you
cannot add different types (generally) together, so you will
run into trouble if you take the "naive" approach and just
trying concatenating the strings and the list as you show
above.  Instead, you will need to pass the sequence of
things through a call to map(str, sequence) first, to call
the str() method on everything and make sure you are adding
strings together.  Thus:
import operator
s = reduce(operator.add, map(str, theList))
or something like that.
However, none of this is considered the best approach these days,
with the advent of list comprehensions and generator expressions.
Here's the old approach (shown above) and the shiny new modern
Pythonic approach (requires Python 2.4):
 >>> theList = range(10)
 >>> import operator
 >>> reduce(operator.add, map(str, theList))
'0123456789'
 >>> ''.join(str(x) for x in theList)
'0123456789'
-Peter
Thank you for replaying. The operator.add is new to me and I will keep 
it in mind. It will perhaps come to use. I will use the join function 
since it looks more beatiful!

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


Hello Group and how to practice?

2015-05-31 Thread Anders Johansen
Hi my name is Anders I am from Denmark, and I am new to programming and python.

Currently, I am doing the codecademy.com python course, but sometime I feel 
that the course advances to fast and I lack repeating (practicing) some of the 
concepts, however I don't feel confident enough to start programming on my own.

Do you guys have some advice to how I can practicing programming and get the 
concept in under the skin?

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


Re: Hello Group and how to practice?

2015-05-31 Thread Anders Johansen
Den søndag den 31. maj 2015 kl. 16.22.10 UTC+2 skrev Cem Karan:
> On May 31, 2015, at 9:35 AM, Anders Johansen  wrote:
> 
> > Hi my name is Anders I am from Denmark, and I am new to programming and 
> > python.
> > 
> > Currently, I am doing the codecademy.com python course, but sometime I feel 
> > that the course advances to fast and I lack repeating (practicing) some of 
> > the concepts, however I don't feel confident enough to start programming on 
> > my own.
> > 
> > Do you guys have some advice to how I can practicing programming and get 
> > the concept in under the skin?
> 
> Choose something that you think is small and easy to do, and try to do it.  
> When you have trouble, read the docs you find online, and ask us questions; 
> the python community is pretty friendly, and if you show us what you've 
> already tried to do, someone is likely to try to help you out.
> 
> The main thing is to not get discouraged.  One of the hardest things to do is 
> figuring out what you CAN do with a computer; some things that look like they 
> should be easy, are actually major research questions.  Just keep trying, and 
> it will get easier over time.
> 
> Good luck!
> Cem Karan

Thank you Cem Karan for your reply. I will try and follow your advice. I am yet 
to install python on my computer, do you know of any easy to follow 
instructions on how to do so? Where do I start?
-- 
https://mail.python.org/mailman/listinfo/python-list


Calling JavaScript inside the webbrowser module

2011-10-30 Thread Anders Gunnarsson
Hi!

Is there anyway to communicate with JavaScript inside a website opened via the 
webbrowser module?

| import webbrowser
| webbrowser.open('http://python.org')

Here I'd like to do something like webbrowser.call('alert(1)')
and I'd like to be able to call the python app from javascript too.

I've looked at pywebkitgtk, but it's messy running on win32.

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


Re: Is 'everything' a refrence or isn't it?

2006-01-07 Thread Anders Hammarquist
In article <[EMAIL PROTECTED]>,
Fredrik Lundh <[EMAIL PROTECTED]> wrote:
>> and the Python use is consistent with the rest of computer science.
>
>The problem isn't the word "reference" in itself, the problem is when people
>are implying that "since Python passes object references to functions, it's
>using call by reference".

Actually, I think the problem is not in the "call" bit. Python behaves
more or less like all other call by reference languages in the call. What
is confusing people is what happens when you *assign* to a function argument.

Those confused are expecting Python function arguments to behave just
like C++ references (which are just syntactic sugar for a dereferenced
pointer) or an Ada "in out" parameter when assigned. Python doesn't,
because in Python assignment assigns a new reference to the name,
rather than changing the referenced object.

/Anders
-- 
 -- Of course I'm crazy, but that doesn't mean I'm wrong.
Anders Hammarquist  | [EMAIL PROTECTED]
Physics student, Chalmers University of Technology, | Hem: +46 31 88 48 50
G|teborg, Sweden.   RADIO: SM6XMM and N2JGL | Mob: +46 707 27 86 87
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Real-world use cases for map's None fill-in feature?

2006-01-09 Thread Anders Hammarquist
In article <[EMAIL PROTECTED]>,
Raymond Hettinger <[EMAIL PROTECTED]> wrote:
>Request for more information
>
>My request for readers of comp.lang.python is to search your own code
>to see if map's None fill-in feature was ever used in real-world code
>(not toy examples).

I had a quick look through our (Strakt's) codebase and found one example.

The code is used to process user-designed macros, where the user wants
to append data to strings stored in the system. Note that all data is
stored as lists of whatever the relevant data type is.

While I didn't write this bit of code (so I can't say what, if any,
alternatives were considered), it does seem to me the most straight-
forward way to do it. Being able to say what the fill-in value should
be would make the code even simpler.

oldAttrVal is the original stored data, and attValue is what the macro
wants to append.

--->8---
newAttrVal = []
for x, y in map(None, oldAttrVal, attrValue):
newAttrVal.append(u''.join((x or '', y or '')))
--->8---

/Anders

-- 
 -- Of course I'm crazy, but that doesn't mean I'm wrong.
Anders Hammarquist  | [EMAIL PROTECTED]
Physics student, Chalmers University of Technology, | Hem: +46 31 88 48 50
G|teborg, Sweden.   RADIO: SM6XMM and N2JGL | Mob: +46 707 27 86 87
-- 
http://mail.python.org/mailman/listinfo/python-list


PyMorphic Project

2006-08-07 Thread Anders Österholm
As a part of my Master Thesis in Cognitive Science at the University of Linköping in Sweden i have created a Squeak-like system in Python called PyMorphic. Project homepage is http://pymorphic.sourceforge.net/
I am about to make a new release with minor changes.There is a tutorial for you in the Toolbar of the main screen. The major technical focus lies on the auto-reloading of classes. This means that instances can be updated with new class definitions. The code that is used for the autoreloading can be found at  
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 Any comments on this project are welcome./Anders Österholm
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Can not download plugins for jEdit (help!!)

2006-11-09 Thread Anders Arnholm
Ant <[EMAIL PROTECTED]> skriver:
>> Vim, it can handle all the things.http://www.vim.org/
>
> I'm not convinced of that quite yet. jEdit's syntax highlighting seems
> more robust (see SocketServer.py in the standard library for an example
> - vim gets the highlighting of the first doc-comment wrong). I've also

I can't see that problem at all. Vim 7.0 standard win32 build and
6.4 on OpenBSD.

My vimrc hold and old rule that I'm not sure is needed or how it works
against the new standard python module:

:au BufEnter *.py :set smarttab smartindent \
cinwords="if,elif,else,for,while,def,try,rxcept,finally,class"

I have not yet seen any problenm from it but maybe it's time to remote
it soon.


/ Balp
-- 
http://anders.arnholm.nu/Keep on Balping
-- 
http://mail.python.org/mailman/listinfo/python-list


Observer implementation question ('Patterns in Python')

2007-10-12 Thread Anders Dahnielson
Sorry if this is a somewhat silly question...

I'm using the Observer implementation found in 'Patterns in
Python' [1] and find it really neat. But, I have not yet fully groked
the new-style class, classic class and property differences involved.
So can somebody please explain to me why this works (using a classic
class):

class C:
TheEvent = Event()
def OnTheEvent(self):
self.TheEvent(self, context)

instance = C()
instance.TheEvent += callback
instance.OnTheEvent()
instance.TheEvent -= callback

While this do not (using new-style class):

class C(object):
TheEvent = Event()
def OnTheEvent(self):
self.TheEvent(self, context)

instance = C()
instance.TheEvent += callback
instance.OnTheEvent()
instance.TheEvent -= callback

Raising an AttributeError :

Traceback (most recent call last):
  File "sig_test.py", line 7, in ?
 instance.TheEvent += callback
AttributeError: can't set attribute

So far I've figured out that it is the Event class (subclassing the
built-in property type) that is the culprit, but not why. (See
'Patterns in Python' [1] for code listing of the Event class.)

I would be grateful if some helpful soul could explain it.

[1] http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html#observer

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


Re: Observer implementation question ('Patterns in Python')

2007-10-13 Thread Anders Dahnielson
Thank you, James and Stargaming, for your replies!

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


Re: Getting to an SSH account over a HTTP proxy

2007-01-23 Thread Anders Arnholm
Jorgen Grahn <[EMAIL PROTECTED]> skriver:
> I am pretty sure there is. Or at least TCP-over-HTTP, or IP-over-HTTP. An
> acquaintance of mine used it to tonnel home through a corporate firewall. I
> think -- I didn't want to know the details.

Ypu can tunnel ip over anything. (Even email if you like...) Nu tunnel
out from that company was based on http-proxy. A small program called
connect (the final version I used was by Shun-ichi Goto and under
GPL.) Bascilly it makes a http-proxt connect to an other site (my sshd)
Then using sshd and pppd as program inte other end makes a good way to
tunnel IP also :-)

/ Anders
-- 
http://anders.arnholm.nu/Keep on Balping
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: c++ for python programmers

2007-02-14 Thread Anders Arnholm
Sam <[EMAIL PROTECTED]> skriver:
> On 13 Feb 2007 17:51:00 GMT, Jorgen Grahn
><[EMAIL PROTECTED]> wrote:
>> Well, C++ is a better language than C in many ways. So, if he needs to learn
>> one of them, why does it have to be C?
>>
>> Another reason some people choose C++ over Python for some tasks is that
>> they feel that larger programs benefit from strong, static type checking.
>> I like both ways, but depending on the task, one or the other is better.
>
> C++ is -not- strongly typed. You can cast anything to void *, and
> manipulate it in ways unimaginable. Plus there's the whole mess that
> is pointer arithmetic and a weak typesystem...


C++ can be both, The type systenm is as fragila as you like it to be.
I mainlty use c++ when i the need stronger typing that Python och C
can't give me. In some ways it's even stronger types than languanges
as Java and ObjectiveC. C++ it however at least four different
languanges, in one ball of soupe.

And yes you can do it, that doesn't mean you have to dio it. As
_functions in python or __, you can use them from anyware, you don't
have to.

/ Balp


-- 
http://anders.arnholm.nu/Keep on Balping
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: c++ for python programmers

2007-02-15 Thread Anders Arnholm
Nicola Musatti <[EMAIL PROTECTED]> skriver:
> On Feb 14, 2:41 pm, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> [...]
>> Don't forget the lack of standard garbage collection.
> memory related problems. I'm aware that most is not the same as all,
> but on the other hand garbage collection has it's problems too:

And that garbabe collection is only good for memory, garbage
collecting open files and network connections work much less
well. Giving the need to add a maonual "delete" function to be called
before the object is destroed when you need the life time controll.
And this having to be reflected in application depenednt way to figure
out how it works in each application.

/ Balp
-- 
http://anders.arnholm.nu/Keep on Balping
-- 
http://mail.python.org/mailman/listinfo/python-list


List all files using FTP

2008-03-06 Thread Anders Eriksson
Hello,

I need to list all the files on my FTP account (multiple subdirectories). I
don't have shell access to the account.

anyone that has a program that will do this?

// Anders
-- 
English is not my first, or second, language
so anything strange, or insulting, is due to
the translation.
Please correct me so I may improve my English!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List all files using FTP

2008-03-07 Thread Anders Eriksson
On Thu, 6 Mar 2008 20:07:46 +, Simon Brunning wrote:

> This might be of use:
> 
> <http://ftputil.sschwarzer.net/trac>

Nice, Just what I needed!

Thank you!

// Anders
-- 
English is not my first, or second, language
so anything strange, or insulting, is due to
the translation.
Please correct me so I may improve my English!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [NEWBIE] csv to excel format problem

2008-10-15 Thread Anders Eriksson
Hello Marco and welcome to the wonderful world of Python,

Your problem is that the file is a text file so the values you are reading
are text which you then write to the Excel sheet.

So you need to convert the text value to a float value. Now the Big Cahonas
has already been there so it's included: 

float( [x]) 

Convert a string or a number to floating point. If the argument is a
string, it must contain a possibly signed decimal or floating point number,
possibly embedded in whitespace. Otherwise, the argument may be a plain or
long integer or a floating point number, and a floating point number with
the same value (within Python's floating point precision) is returned. If
no argument is given, returns 0.0. 
Note: When passing in a string, values for NaN and Infinity may be
returned, depending on the underlying C library. The specific set of
strings accepted which cause these values to be returned depends entirely
on the C library and is known to vary

If you do this change it might work ;-)
Add these functions:
def isNaN(x):
return isinstance(x, float) and x!=x
def isInf(x):
return !isNaN(x) && isNaN( (x) - (x) )

in writeExcelRow change:
   for column in columns:
fcolumn = float(column)
if(isNaN(fcolumn) or isInf(fcolumn)):
# do some error handling
else:
worksheet.write(lno, cno, column,style)
cno = cno + 1

I'm sure that there are smarter ways of doing this and someone will
probably point them out ;-)

// Anders
-- 
English is not my first, or second, language
so anything strange, or insulting, is due to
the translation.
Please correct me so I may improve my English!

On Tue, 14 Oct 2008 03:03:52 -0700 (PDT), MM wrote:

> Hi to all,
> 
> I'm trying to import a tab separated values file onto Excel with the
> following script:
> 
> import csv
> from pyExcelerator import *
> 
> w = Workbook()
> worksheet = w.add_sheet('sim1')
> 
> def writeExcelRow(worksheet, lno, columns):
>   style = XFStyle()
>   style.num_format_str = '0.00E+00'
>   cno = 0
>   for column in columns:
> worksheet.write(lno, cno, column,style)
> cno = cno + 1
> 
> nrow = 0
> csvfile = file('res1.txt','r')
> csvreader = csv.reader(csvfile, delimiter='\t')
> 
> for line in csvreader:
> writeExcelRow(worksheet,nrow,line)
> nrow += 1
> 
> csvfile.close()
> w.save('numbers.xls')
> 
> All goes well and the resulting file "numbers.xls" has all the numbers
> in the right place
> 
> The problem is that excel sees the numbers as text and gives the error
> "numbers stored as text" that I have to correct manually.
> 
> The file res1.txt has the structure of a tab separated values of
> floating point numbers.
> 
> Thank you for the help.
> 
> Marco

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


Downloading binary files - Python3

2009-03-21 Thread Anders Eriksson
Hello,

I have made a short program that given an url will download all referenced
files on that url.

It works, but I'm thinking it could use some optimization since it's very
slow.

I create a list of tuples where each tuple consist of the url to the file
and the path to where I want to save it. E.g (http://somewhere.com/foo.mp3,
c:\Music\foo.mp3)

The downloading part (which is the part I need help with) looks like this:
def GetFiles():
"""do the actual copying of files"""
for url,path in hreflist:
print(url,end=" ")
srcdata = urlopen(url).read()
dstfile = open(path,mode='wb')
dstfile.write(srcdata)
dstfile.close()
print("Done!")

hreflist if the list of tuples.

at the moment the print(url,end=" ") will not be printed before the actual
download, instead it will be printed at the same time as print("Done!").
This I would like to have the way I intended.

Is downloading a binary file using: srcdata = urlopen(url).read()
the best way? Is there some other way that would speed up the downloading?

// Anders
-- 
English is not my first or second language
so any error or insult are done in the translation!
Please correct my English so I may become better at it!
--
http://mail.python.org/mailman/listinfo/python-list


I want to use a C++ library from Python

2008-09-10 Thread Anders Eriksson
Hello,

I have a C++ library compiled as Windows DLL's. It consists of 32 .h and 1
.lib and 1 .dll files. I don't have the source code.

How can I create a Python module from these files?

// Anders
-- 
English is not my first, or second, language
so anything strange, or insulting, is due to
the translation.
Please correct me so I may improve my English!
--
http://mail.python.org/mailman/listinfo/python-list


Re: I want to use a C++ library from Python

2008-09-10 Thread Anders Eriksson
Hello all and thanks for replying,


> Diez B. Roggisch wrote:
>> Which actually isn't really helpful, as a DLL itself says nothing about what
>> language was used to create it - and sending the OP to e.g. ctypes makes no
>> sense at all in the face of C++.
> 
> The library - or more precisely the calling convention of the library - 
> is related to the solution. On Windows a dll might be a container for a 
> .NET assembly and C++ code can (theoretically) be compiled to .NET, too.
> 
No, the library is not an .NET assembly. It's an VC++ Library compiled as
an Dll.

>> Whereas the first link for "python c++" is Boost::Python, a C++-wrapper to
>> make C++-code accessible from Python.
> 
> C++ bindings can be created with SIP, SWIG, Boost or hand written code. 
> Multiple sites claim that SIP generates the fastest code.
> 
I have looked (very briefly) at the three framework you mention but they
all need the source code of the C++?

I don't have the source code! Just the header files and the library and
dll.

Have I overlooked something or am I just screwed?

// Anders
-- 
English is not my first, or second, language
so anything strange, or insulting, is due to
the translation.
Please correct me so I may improve my English!
--
http://mail.python.org/mailman/listinfo/python-list


is py2exe still active ?

2010-12-07 Thread Anders Persson
Hi!
When a look att py2exe homepage it is not looking like mutch happen,
as a beginner i was thinking to start with Python 3, but i like to now
if py2exe will be for 3 too.

Is any one have any info ?

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


Re: Books recommendation

2010-12-07 Thread Anders Persson
You can't compile Python to exe files, but there is program packing
your script to a exe files, look att

www.py2exe.org

Beware that you must have py2exe version match your pythonversion and
att current time the highest version is 2.7.

/A


On Dec 7, 2:39 pm, "Octavian Rasnita"  wrote:
> Hello,
>
> Do you have, or can I find elsewhere a recommendation for books,tutorials and 
> sites appropriate for beginners?
>
> I have a lot of experience in Perl but I am interested to also learn Python 
> for:
> - web development (with frameworks similar with Catalyst and Ruby on Rails, 
> good templating systems, good ORMS and form processors)
> - Desktop apps with WxPython
> - Create MS Windows apps, executables, dlls, ActiveX, OS interaction...
> - Text parsing, regular expressions...
>
> I am also interested to find where I can get Python modules from and how... 
> similar tools and sites with cpan and ppm for Perl.
>
> Thank you.
>
> Octavian

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


Re: grimace: a fluent regular expression generator in Python

2013-07-16 Thread Anders J. Munch

Ben Last wrote:

north_american_number_re = (RE().start

.literal('(').followed_by.exactly(3).digits.then.literal(')')
 
.then.one.literal("-").then.exactly(3).digits

.then.one.dash.followed_by.exactly(4).digits.then.end
 .as_string())


Very cool.  It's a bit verbose for my taste, and I'm not sure how well it will 
cope with nested structure.


Here's my take on what readable regexps could look like:

north_american_number_re = RE.compile(r"""
^
"(" digit{3} ")"  # And why shouldn't a regexp
"-" digit{3}  # include en embedded comment?
"-" digit{4}
$
""")

The problem with Perl-style regexp notation isn't so much that it's terse - it's 
that the syntax is irregular (sic) and doesn't follow modern principles for 
lexical structure in computer languages.  You can get a long way just by 
ignoring whitespace, putting literals in quotes and allowing embedded comments.


Setting the re.VERBOSE flag achieves two out of three, so you can write:

north_american_number_re = RE.compile(r"""
^
( \d{3} )   # Definite improvement, though I really miss putting
- \d{3} # literals in quotes.
- \d{4}
$
""")

It's too bad re.VERBOSE isn't the default.

regards, Anders

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


Re: Tabs -vs- Spaces: Tabs should have won.

2011-07-17 Thread Anders J. Munch

Steven D'Aprano wrote:
> I can't fathom why 8 position tabs were *ever* the default, let alone why
> they are still the default.

That's because they were not invented as a means for programmers to vary 
indentation.


Originally, tabs were a navigation device: When you press the tab key, you skip 
ahead to the next tab column.  The notion that whitespace characters are 
inserted into the text would have been very alien to someone using text 
processing software anno 1970.  Same thing with space and enter; on typewriters
the space bar doesn't "type" anything onto the paper, it moves to the next 
column, and that thinking carried over to computers.


The reason the tab stop is a full 8 positions: for faster navigation.  If it 
were 3 positions, it would take forever to skip from the start of line to column 
60.  You'd appreciate that, if you were e.g. writing a fiduciary report with 
some text to the left and two number columns to the right, back in the day 
before spreadsheets and word processor tables.  Skip a column or two too far? 
Adjust by backspacing (another navigation key).


As for why 8 is still the default - well, what else should it be? 2, 3, 4, 5?  I 
for one am thankful that we have so far been spared the flamewar armegeddon of 
all the world's programmers trying to agree on that.


> Cameron Simpson wrote:
>> Personally, I like to use the tab _key_ as an input device, but to have
>> my editor write real spaces to the file in consequence.

Just like in the old days:)

regards, Anders

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


Re: Tabs -vs- Spaces: Tabs should have won.

2011-07-18 Thread Anders J. Munch

Thomas 'PointedEars' Lahn wrote:
> I am getting the idea here that you mean the right thing, but that you
> explain it wrong.

Feel free to write the much longer essay that explains it all unambiguously, I'm 
not going to.


regards, Anders


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


Re: Are the critiques in "All the things I hate about Python" valid?

2018-02-18 Thread Anders Wegge Keller
På Sat, 17 Feb 2018 15:05:34 +1100
Ben Finney  skrev:
> boB Stepp  writes:


> He blithely conflates “weakly typed” (Python objects are not weakly, but
> very strongly typed) 

 Python is more strongly typed than PHP, but that doesn't really say much.
However, compared to a language like C, there are big holes in the type
safety.

>>> alist = [1, 'two', ('three', four), 5*'#']

 That list is not only weakly typed, but rather untyped. There are no
safeguards in the language, that enforce that all elements in a list or
other container are in fact of the same type. Before type annotations and
mypy, I could not enforce that other than at runtime. 

 So claiming Python to have very strongly typed objects is a bit of a
strecth. PHP that many of us like to be smug about is equally strongly
typed. It just comes with a metric ton of inane type coersions that have
gone too far. However, we are happy to add an integer to a float without
having to make an explicit conversion every time, so ... Thread carefull and
all that.

-- 
//Wegge
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Are the critiques in "All the things I hate about Python" valid?

2018-02-18 Thread Anders Wegge Keller
På Sun, 18 Feb 2018 07:34:03 -0500
Richard Damon  skrev:

> Python is much stronger typed than PHP, because in PHP you can do things 
> like 1 + '2' and get 3, as string values will naturally convert 
> themselves to numbers, Python won't do this. Yes Python will freely 
> convert between numeric types, but I wouldn't say that Python claims to 
> be a language that focuses on numerics.

 Type coercion is not the same as weak typing. Let me stress that the
difference between languages having 1 + 1.23 as a valid construct and
languages having 1 + '1.23' as a valid construct, is merely a design
descision. PHP is fully aware that a string and an integer have different
types, and makes a implicit cast, rather than throw an error. 

-- 
//Wegge
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Are the critiques in "All the things I hate about Python" valid?

2018-02-18 Thread Anders Wegge Keller
På Mon, 19 Feb 2018 08:47:14 +1100
Tim Delaney  skrev:
> On 18 February 2018 at 22:55, Anders Wegge Keller  wrote:


> >  That list is not only weakly typed, but rather untyped. There are no
> > safeguards in the language, that enforce that all elements in a list or
> > other container are in fact of the same type. Before type annotations and
> > mypy, I could not enforce that other than at runtime.

> You couldn't have got the above much more wrong.
 
> As others have said, typing is about how the underlying memory is treated.

 And that is exactly my point. Python does not have a typed list. It have a
list that takes whatever is thrown into it.

 I'll skip the rest, as you totally missed the point.
-- 
//Wegge
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Are the critiques in "All the things I hate about Python" valid?

2018-02-19 Thread Anders Wegge Keller
På Mon, 19 Feb 2018 04:39:31 + (UTC)
Steven D'Aprano  skrev:
> On Mon, 19 Feb 2018 04:26:32 +0100, Anders Wegge Keller wrote:
> 
> > På Mon, 19 Feb 2018 08:47:14 +1100
> > Tim Delaney  skrev:  
> >> On 18 February 2018 at 22:55, Anders Wegge Keller 
> >> wrote:  
> > 
> >   
>  [...]  
> >   
> >> You couldn't have got the above much more wrong.  
> >
> >> As others have said, typing is about how the underlying memory is
> >> treated.  
> > 
> >  And that is exactly my point. Python does not have a typed list. It
> >  have a list that takes whatever is thrown into it.
> > 
> >  I'll skip the rest, as you totally missed the point.  
> 
> I think its actually you have totally missed the point. What you want is 
> a homogeneous list, a list which only accepts items of the same type. The 
> built-in list is not that data structure, but Python already has 
> something similar: see the array module.

 Given that I'm the one making a point about the unwarranted smugness, I
know that I'm not missing anything. Array is not even close to providing a
strongly typed container. For all of the yakking about other languages
weak, blah, BCPL, blah, I still wonder where that need to feel superior to
anything else comes from.  

 Python isn't particular strong typed. In fact, apart from asking an object
what type it is, types are not that important. It's the interface that
matters. I wonder why this is a sore point for Python developers?


-- 
//Wegge
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Are the critiques in "All the things I hate about Python" valid?

2018-02-19 Thread Anders Wegge Keller
På Mon, 19 Feb 2018 15:15:19 + (UTC)
Steven D'Aprano  skrev:
> On Mon, 19 Feb 2018 14:06:36 +0100, Anders Wegge Keller wrote:
> 
> > Array is not even close to providing a strongly typed container.  
> 
> That's a mighty powerful claim that goes against the documentation for 
> the array module. Can you back your claims up?
> 
> Here's an array and a list:

 Make me an array of tuples with two integers and a string, and we can talk.

-- 
//Wegge
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Are the critiques in "All the things I hate about Python" valid?

2018-02-20 Thread Anders Wegge Keller
På Tue, 20 Feb 2018 12:28:25 + (UTC)
Steven D'Aprano  skrev:
> On Mon, 19 Feb 2018 16:34:29 +0100, Anders Wegge Keller wrote:
> 
> > På Mon, 19 Feb 2018 15:15:19 + (UTC) Steven D'Aprano
> >  skrev:  
> >> On Mon, 19 Feb 2018 14:06:36 +0100, Anders Wegge Keller wrote:
> >>   
>  [...]  
> >> 
> >> That's a mighty powerful claim that goes against the documentation for
> >> the array module. Can you back your claims up?
> >> 
> >> Here's an array and a list:  
> > 
> >  Make me an array of tuples with two integers and a string, and we can
> >  talk.  
> 
> The array module's failure to support the specific type you want has no 
> bearing on whether or not Python is statically typed.

 You claimed Array could do what I requested, i.e. container type that
guaranteed only one type inside. Furthermore, you are misrepresenting C with
malice. 

 I don't care why you feel that a simple observation is a personal attack,
but I see you behave as a spoiled kid. I haven\t got the time for it, sop go
and pout in your corner. 

-- 
//Wegge
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python slang

2016-08-10 Thread Anders J. Munch

Lawrence D’Oliveiro:
>> [...] as much like C++ as
>> possible.
>
> Nevertheless, Python copied the C misfeature [...]

You segued a little too easily from C++ to C.  When talking language
evolution and inspirations, they are entirely different things.

- Anders

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


Re: Python Developer Survey: Python 3 usage overtakes Python 2 usage

2018-03-31 Thread Anders Wegge Keller
På Sat, 31 Mar 2018 11:58:39 -0400
Etienne Robillard  skrev:

> Are you trolling? Do you understand that a modern mobile device 
> typically require a Internet subscription and an additional subscription 
> for the smart phone?

 I think the question is why you equate python3 with the need for internet
connected tablets. That's quite the non sequitur. 

Consider this my +1 the the request of you to clarify what you mean.

-- 
//Wegge
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: want to export some of the packets from a big pacp file to another file.

2018-04-05 Thread Anders Wegge Keller
På Thu, 5 Apr 2018 08:06:10 -0700 (PDT)
supsw...@gmail.com skrev:
> Hi,
> 
> I am using dpkt python package to parse .pcap file and I am able to do
> successfully.
> 
> My requirement is to filter some of the traffic from the big .pcap file
> and to export the result to another file.
> 
> I don't know how to do this.

 What kind of filtering do you need? In many cases it would be faster and
more convenient to use wireshark or other similar tools as a pass-through
filter, rather than rolling your own. 

-- 
//Wegge
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: object types, mutable or not?

2018-05-17 Thread Anders Wegge Keller
På Wed, 16 May 2018 14:48:27 +0100
Paul Moore  skrev:

> C++ called that an "rvalue". And then went on to define things that
> could go on the left hand side of an assignment as "lvalues". And now
> we have two confusing concepts to explain - see what happens when you
> let a standards committee define your language? :-)

 I'm not sure the C++ committee has to bear the responsibility for those
terms. They are pretty well defined in the C world, so I think you need to
point the finger of accusation at either Brian or Dennis. 

-- 
//Wegge
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Unicode [was Re: Cult-like behaviour]

2018-07-16 Thread Anders Wegge Keller


> The buzzing noise you just heard was the joke whizzing past your head 
> *wink*

 I have twins aged four. They also like to yell "I cheated!", whenever they
are called out.

 In general, you need to get rid of tat teenage brat persona you practice.
The "ranting rick" charade was especially toe-curling.

-- 
//Wegge
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Unicode [was Re: Cult-like behaviour]

2018-07-16 Thread Anders Wegge Keller
På Mon, 16 Jul 2018 11:33:46 -0700
Jim Lee  skrev:

> Go right ahead.  I find it surprising that Stephen isn't banned, 
> considering the fact that he ridicules anyone he doesn't agree with.  
> But I guess he's one of the 'good 'ol boys', and so exempt from the code 
> of conduct.

Well said!

-- 
//Wegge
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Non-GUI, single processort inter process massaging - how?

2018-07-23 Thread Anders Wegge Keller
På Sat, 21 Jul 2018 09:07:23 +0100
Chris Green  skrev:

> So - what's the best approach to this?  I've done some searching and
> most/many of the solutions seem rather heavyweight for my needs. Am I
> overlooking something obvious or should I try rethinking the original
> requirement and look for another approach?

 What do you consider heavyweight? Number of dependencies, memory footprint,
amount of code or a fourth thing? Also, which platform will the code
eventually run on?

 If your update frequency is low enough that it wont kill the filesystem and
the amount of data is reasonably small, atomic writes to a file is easy to
work with:

  def atomic_write(filename, data):
handle, name = tempfile.mkstemp()
os.write(handle, data)
os.fsync(handle)
os.close(handle)
os.replace(tmpname, filename)

 The imports are trivial to deduce, so I removed the clutter. If you have
multiple filesystems, you may have to read into the details of calling
mkstemp.


 If you have an update frequency that will kill the filesystem (for instance
a RPi on a SD card), or have a larger data set where you only want to do
partial updates, the mmap module could be an option. It require some more
boilerplate. You will probably also have to consider a semaphore to
guarantee that the clients read a consistent result set.

-- 
//Wegge
-- 
https://mail.python.org/mailman/listinfo/python-list


PEP 394

2018-10-19 Thread Anders Wegge Keller
Short and simple: Do you expect PEP 394 to change status or
recommendation when official support for Python2 ends in 13½ months time, or
at least some time thereafter? 

For those that don't have the habit of memorizing PEPs, 394 is the one
stating 

* python2 will refer to some version of Python 2.x.
* python3 will refer to some version of Python 3.x.
* for the time being, all distributions should ensure that python, if
installed, refers to the same target as python2, unless the user
deliberately overrides this or a virtual environment is active.

-- 

//Wegge
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: logging output

2018-10-19 Thread Anders Wegge Keller
På Fri, 19 Oct 2018 08:05:28 -0700 (PDT)
Sharan Basappa  skrev:

...

> delimiter=r'\s"') #data_df = pd.read_csv("BGL_MERGED.log")
> logger.debug("data frame %s \n", data_df)

 Do this help?
 


-- 

//Wegge
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PEP 394

2018-10-20 Thread Anders Wegge Keller
På Sat, 20 Oct 2018 12:57:45 +1100
Ben Finney  skrev:
> Anders Wegge Keller  writes:
> 
> > Short and simple: Do you expect PEP 394 to change status  
> 
> The status of PEP 394 today is “Active”. What change of status would you
> expect in this Informational PEP?

 One possible change would be that it would become archived, ceased to be,
bereft of life, resting in peace or maybe even retired. 

 I don't have any particular status change I want to see; I merely ask
what other experienced python developers expect to happen.

-- 
//Wegge 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Recursive method in class

2019-09-30 Thread Anders Märak Leffler
What do you mean by transformed? This is probably your understanding
already, but a further consequence of when arguments are evaluated
plus what you said about data attributes is that the fib(self, n - 1)
call will follow the standard LEGB-lookup of whatever "fib" is, from
the point of view of the function object. As far as I know, there is
no transformation of these scopes - either when it comes to creating
the class, or creating the instances. (self is just the instance,
passed as an argument.)

Cf when you change a binding:

>>> def factorial(self, n):
... if not n:
... return 1
... else:
... return n * factorial(self, n - 1)
...
>>> Dummy = type("DummyObject", (object, ), {"factorial" : factorial})
>>> instance = Dummy()
>>> def factorial(self, n):
... print("Hello!")
... return 999
...
>>> instance.factorial(5)   # Where will the call go ("old" or "new" 
>>> factorial?)? Where will possible recursive calls go (and why)?
Hello!
4995

Oh, and as others have pointed out on this list - you/whoever runs the
system sending the mail might want to change the return address.
n...@gmail.com is somewhat consistently classed as spam.



//Anders

PS. We could further complicate this by adding a call to
self.factorial in the new function, but let's not go there. :)


On Mon, Sep 30, 2019 at 9:58 AM ast  wrote:
>
> Le 27/09/2019 à 14:26, Jan van den Broek a écrit :
> > On 2019-09-27, ast  wrote:
> >> Is it feasible to define a recursive method in a class ?
> >> (I don't need it, it's just a trial)
> >>
> >> Here are failing codes:
> >>
> >>
> >> class Test:
> >>   def fib(self, n):
> >>   if n < 2: return n
> >>   return fib(self, n-2) + fib(self, n-1)
> >self.fib(...)
> >
> > [Schnipp]
> >
>
> Yes you are right. I forgot that class methods
> don't see class attributes
>
> An other workaround:
>
>   def fib(self, n):
>   if n < 2: return n
>   return Test.fib(self, n-2) + Test.fib(self, n-1)
>
> It comes from https://www.pythonsheets.com/notes/python-object.html
>
>  >>> def fib(self, n):
> ... if n <= 2:
> ... return 1
> ... return fib(self, n-1) + fib(self, n-2)
> ...
>  >>> Fib = type('Fib', (object,), {'val': 10,
> ...   'fib': fib})
>  >>> f = Fib()
>  >>> f.val
> 10
>  >>> f.fib(f.val)
> 55
>
> So it means that when classes are constructed explicitely
> with type(name, bases, dict_), some methods are transformed
> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Speed ain't bad

2005-01-01 Thread Anders J. Munch
"Bulba!" <[EMAIL PROTECTED]> wrote:
>
> One of the posters inspired me to do profiling on my newbie script
> (pasted below). After measurements I have found that the speed
> of Python, at least in the area where my script works, is surprisingly
> high.

Pretty good code for someone who calls himself a newbie.

One line that puzzles me:
> sfile=open(sfpath,'rb')

You never use sfile again.
In any case, you should explicitly close all files that you open. Even
if there's an exception:

sfile = open(sfpath, 'rb')
try:

finally:
sfile.close()

>
> The only thing I'm missing in this picture is knowledge if my script
> could be further optimised (not that I actually need better
> performance, I'm just curious what possible solutions could be).
>
> Any takers among the experienced guys?

Basically the way to optimise these things is to cut down on anything
that does I/O: Use as few calls to os.path.is{dir,file}, os.stat, open
and such that you can get away with.

One way to do that is caching; e.g. storing names of known directories
in a set (sets.Set()) and checking that set before calling
os.path.isdir.  I haven't spotted any obvious opportunities for that
in your script, though.

Another way is the strategy of "it's easier to ask forgiveness than to
ask permission".
If you replace:
if(not os.path.isdir(zfdir)):
os.makedirs(zfdir)
with:
try:
os.makedirs(zfdir)
except EnvironmentError:
pass

then not only will your script become a micron more robust, but
assuming zfdir typically does not exist, you will have saved the call
to os.path.isdir.

- Anders


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


Re: Speed ain't bad

2005-01-04 Thread Anders J. Munch
"John Machin" <[EMAIL PROTECTED]> wrote:
> 1. Robustness: Both versions will "crash" (in the sense of an unhandled
> 2. Efficiency: I don't see the disk I/O inefficiency in calling

3. Don't itemise perceived flaws in other people's postings. It may
give off a hostile impression.

> 1. Robustness: Both versions will "crash" (in the sense of an unhandled
> exception) in the situation where zfdir exists but is not a directory.
> The revised version just crashes later than the OP's version :-(
> Trapping EnvironmentError seems not very useful -- the result will not
> distinguish (on Windows 2000 at least) between the 'existing dir' and
> 'existing non-directory' cases.

Good point; my version has room for improvement. But at least it fixes
the race condition between isdir and makedirs.

What I like about EnvironmentError is that it it's easier to use than
figuring out which one of IOError or OSError applies (and whether that
can be relied on, cross-platform).

> 2. Efficiency: I don't see the disk I/O inefficiency in calling
> os.path.isdir() before os.makedirs() -- if the relevant part of the
> filesystem wasn't already in memory, the isdir() call would make it
> so, and makedirs() would get a free ride, yes/no?

Perhaps. Looking stuff up in operating system tables and buffers takes
time too. And then there's network latency; how much local caching do
you get for an NFS mount or SMB share?

If you really want to know, measure.

- Anders


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


Reference counting and the use of PYTHONDUMPREFS

2014-01-18 Thread Anders Wegge Keller
 During the final test of a bit of embedded python, I wanted to see if
I had any hanging references. To my suprise, I ended up with a rather
large amount, after running combinerefs.py. And even with the
simplest[1] possible use of embedding, I end up with 13475 still-living
references. 

 If this is the expected case, then what are the possible benefit from
running a process with the PYTHONDUMPREFS ebvironment variable set? My
code would have to be hemorrhaging in a severe way, to show up on this
background. Am I missing something here?

 The system in question is a Fedora 19 Linux, using the distribution's
Python3 debug rpm. I've seen similar results with Python 2.6, just at
a lesser scale.

1:
#include 
#include 

int main (int argc, char **argv) {

  Py_Initialize();
  Py_Finalize();

  return EXIT_SUCCESS;
}

Compiled with:

gcc pyleak.c -o pyleak `/usr/bin/python3.3dm-config --cflags`  \
  `/usr/bin/python3.3dm-config --ldflags` 


-- 
/Wegge

Leder efter redundant peering af dk.*,linux.debian.*
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Separate Address number and name

2014-01-21 Thread Anders Wegge Keller
Shane Konings  writes:

> I have struggled with this for a while and know there must be a
> simple method to achieve this result.

 There are several. But without seeing the code you have already
written, it's har to help you improve it.

-- 
/Wegge

Leder efter redundant peering af dk.*,linux.debian.*
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Separate Address number and name

2014-01-21 Thread Anders Wegge Keller
Shane Konings  writes:

...

> The following is a sample of the data. There are hundreds of lines
> that need to have an automated process of splitting the strings into
> headings to be imported into excel with theses headings

> ID  Address  StreetNum  StreetName  SufType  Dir   City  Province  PostalCode
> 
> 
> 1 1067 Niagara Stone Rd, W, Niagara-On-The-Lake, ON L0S 1J0
> 2 4260 Mountainview Rd, Lincoln, ON L0R 1B2
> 3 25 Hunter Rd, Grimsby, E, ON L3M 4A3
> 4 1091 Hutchinson Rd, Haldimand, ON N0A 1K0
> 5 5172 Green Lane Rd, Lincoln, ON L0R 1B3
> 6 500 Glenridge Ave, East, St. Catharines, ON L2S 3A1
> 7 471 Foss Rd, Pelham, ON L0S 1C0
> 8 758 Niagara Stone Rd, Niagara-On-The-Lake, ON L0S 1J0
> 9 3836 Main St, North, Lincoln, ON L0R 1S0
> 101025 York Rd, W, Niagara-On-The-Lake, ON L0S 1P0

 The input doesn't look consistent to me. Is Dir supposed to be an
optional value? If that is the only optional, it can be worked
around. But if the missing direction (I'm guessing) is due to
malformed input data, you have a hell of a job in front of you.

 What do you want to do with incomplete or malformed data? Try to
parse it as a "best effort", or simply spew out an error message for
an operator to look at?

 In the latter case, I suggest a stepwise approach:

* Split input by ',' ->res0

* Split the first result by ' ' -> res

-> Id = res[0]
-> Address = res[1:]
-> StreetNum = res[1]
-> StreetName= res [2:]
-> SufType = res[-1]

* Check if res0[1] looks like a cardinal direction
 If so Dir = res0[1]
 Otherwise, croak or use the default direction. Insert an element in
 the list, so the remainder is shifted to match the following steps.

-> City = res0[2]

* Split res0[3] by ' ' -> respp

respp[0] -> Province
respp[1:] -> Postcode


 And put in som basic sanitation of the resulting values, before
committing them as a parsed result. Provinces and post codes, should
be easy enough to validate against a fixed list. 

-- 
/Wegge

Leder efter redundant peering af dk.*,linux.debian.*
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Off-topic] Requests author discusses MentalHealthError exception

2016-03-02 Thread Anders Wegge Keller
On Mon, 29 Feb 2016 23:29:43 +
Mark Lawrence  wrote:

> On 29/02/2016 22:40, Larry Martell wrote:

>> I think for the most part, the mental health industry is most
>> interested in pushing drugs and forcing people into some status quo.

> I am disgusted by your comments.  I'll keep my original reply in reserve.

 Actually, if you view it by raw numbers, where depression makes up the bulk
of the total number of mental problems, Larry's statement is true.

 Studies not performed by the industry shows that an un-medicated depression
ends on average half a day later than one that's treated with some sort
of SSRI. 

Disclaimer: I'm depressed myself, and I've taken an interest into the hows
and whys of SSRI medications.

-- 
//Wegge
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: sobering observation, python vs. perl

2016-03-19 Thread Anders J. Munch

Charles T. Smith:

I've really learned to love working with python, but it's too soon
to pack perl away.  I was amazed at how long a simple file search took
so I ran some statistics:


Write Python in pythonic style instead of translated-from-Perl style, and the 
tables are turned:


$ cat find-rel.py
| import sys
| def main():
| for fn in sys.argv[1:]:
| tn = None
| with open(fn, 'rt') as fd:
| for line in fd:
| if ' is ready' in line:
| tn = line.split(' is ready', 1)[0]
| elif 'release_req' in line:
| print tn
| main()


$ time python find-rel.py *.out
real0m0.647s
user0m0.616s
sys0m0.029s

$ time perl find-rel.pl *.out
real0m0.935s
user0m0.910s
sys0m0.023s

I don't have your log files and my quickly assembled test file doesn't actually 
contain the phrase 'release_req', so my results may be misleading. Perhaps 
you'll try it and post your results?


regards, Anders

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


Parsing and displaying C structs in a semi-intelligent way.

2015-07-17 Thread Anders Wegge Keller
 In my day job, we have a large code base of mostly identical projects, each
with their own customizations. The customizations can be a real pain
sometimes. Especially when debugging binary data. The interesting part of
the binary dumps are most often the stuff that are tweaked from project to
project. The prime suspect is a structure like this:

typedef struct
{
bytenext ;  /* Index to next wedge  */
byteflags ; /* ricd-control flags   */
wordalt [MAX_alt] ; /* Alternative wedges   */
...
} ConvResult ;

typedef struct
{
bytestate ; /* UCART_ (see cart.h)  */
wordheadcart ;  /* Cart number for header cart  */
ConvResult  conv ;
...
} cartUTable_t ;

 The actual structure with substructures are much larger. This structure
contains all the information used when sorting stuff[1]. For historical
reasons, the data is dumped to a binary file at the end of the items
life-cycle. We do have a debugging tool, that reads an in-house file format
specifying the members of the structure, and how to display them. However,
updating this description is error-prone, and just about as funny as waiting
for the Norwegian Blue to fly out over the fiords. So most often it's either
not done, or is unusable. 

 To clean up this mess, I've devised a cunning plan, involving a C-parser,
that can write a structure definition as XML. Reading this is simple enough,
and going from that to a format string for struct.unpack() is mostly
trivial. Except for the arrays of some C-type, that happens to be something
else than an array of char. Due to the normal use case[2] of dumping this
binary data, I need to get the parsed data munged into a form, that can be
put into a namedtuple as single member, even when I have an array of
(typical) six conv.alt values. I'm getting stuck with the limitations of
struct and namedtuple. While inheriting either of them to get the job done,
seem to be feasible, I still feel that I somehow should be able to do
something "list comprehension"-ish, to avoid going there. I just can't see
the light.

(Thank you for reading all the way to here!)


1. Luggage, parcels, shop replenishments ... In short: mostly rectangular
   things that has a barcode attached.

2. Random ordering, not displaying all members, and only a part of the
   arrays.

-- 
//Wegge
-- 
https://mail.python.org/mailman/listinfo/python-list


NaN comparisons - Call For Anecdotes

2014-07-08 Thread Anders J. Munch

Most people don't need to deal with NaN's in Python at all,
fortunately. They just don't appear in normal computation, because the
interpreter raises an exception instead.

It happens in my work I come across them quite a lot. I'm writing
software that talks to embedded applications that can contain NaN
values for a variety of reasons - never-initialised storage,
initialise-to-NaN, hardware failures etc.

So when my software reads these values in binary, unpack them using
the struct module, and goes to work. And NaN's are no different from
any other value, it's something to store, compare, display etc.

And that worked fine in my Python 2.4 apps.  Then I upgraded to 2.7
and it broke.  Because 2.7 goes out of it's way to ensure that NaN's
don't compare equal to themselves.

I discovered it when a sanity check told me that two functions,
to_binary and from_binary, weren't each other's inverse, as they were
intended to be.  Apparently,
bitPattern==to_binary(from_binary(bitPattern)) wasn't true for this
particular value of bitPattern.  Of course, the bit pattern in
question was the binary representation for a floating-point NaN.

Panic time! If I can't trust == to return True for (mathematically)
equal objects, that means that every single algorithm I had ever written
that explicitly or implicitly does .__eq__ or .__ne__ comparison was
suspect!

That meant I had 3 lines of code to review.  Every time there's a
comparison, if there was any chance that either value could be a
float NaN, I would have to change e.g.
   if x==y:
to
   if x==y or (isinstance(x, float) and isinstance(y, float) and
 math.isnan(x) and math.isnan(y)):
To make it bearable, I could wrap the pattern up in a function and
write
   if my_equal(x,y):
but I would still lose, because the standard library does == and !=
all over the place without calling my_equal.

In the end I came up with this hack: Every time I struct.unpack'd a
float, I check if it's a NaN, and if it is, then I replace it with a
reference to a single, shared, "canonical" NaN. That means that
container objects that skip __equal__ when comparing an object to
itself will work -- e.g. hash keys.

It's half a solution, of course: Any further computation with a NaN
value will change it to a different NaN object, so I still needed to
do explicit NaN-checks in various places.  I'm sure there are still
NaN-related bugs in my code, but right now it's "good enough" - I
haven't seen NaN-related bugs in a good while.

Now, all this bothers me.  Not that I had to do some work to get stuff
to work in an imperfect world.  No, what bothers me is that this
behaviour was explicitly and deliberately put in for no good reason.
The only reason is "standard says so". Not that there's any legal
requirement for Python to follow the IEEE-754 standard. Or for that
matter, for Python's spelling of IEEE-754 comparisons to be "==".

So I make this claim: float.__eq__ implementing IEEE-754 NaN
comparison rules creates real problems for developers. And it has
never, ever, helped anyone do anything.

"Never" is a strong claim, and easily disproven if false: Simply
provide a counterexample.  So that is my challenge: If you have a
program (a pre-existing and useful one, not something artificial
created for this challenge) that benefits from NaN!=NaN and that would
fail if x==x for all float objects x, then please come forward and
show it, and I'll buy you a beer the next time I'm at PyCon.

regards, Anders

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


Re: NaN comparisons - Call For Anecdotes

2014-07-08 Thread Anders J. Munch

Chris Angelico wrote:


Why *should* all NaNs be equal to each other? You said on the other
list that NaN==NaN was equivalent to (2+2)==(1+3), but that assumes
that NaN is a single "thing".


I don't actually care if all NaN bitpatterns are in the same equivalence group 
or if each bitpattern is its own equivalence group. I just want the == 
equivalence relation to be sound.



For hash keys, float object identity will successfully look them up:


Except you can't expect to rely on object identity in most interesting cases.

>>> x = float('nan')
>>> import struct
>>> y = struct.unpack('>> d[x] = "found"
>>> d[y]
Traceback (most recent call last):
File "", line 1, in 
KeyError: nan

and also:

>>> def f(): return float('inf')/float('inf')
>>> f() == f()
False
>>> f() is f()
False


But any time you compare floats for equality, you *already* have to
understand what you're doing (because of rounding and such), so I
don't see why the special case on NaN is significant, unless as
mentioned above, you want all NaNs to be equal, which doesn't make
sense.

Let me conjure up a simple example:

| class Monitor(Thread):
| def run(self):
| old = self.get_current_value()
| while not self.Terminated:
| new = self.get_current_value()
| if new != old:
| print(time.asctime(), "changed to", new)
| old = new
| time.sleep(1)

This is a completely generic change detection algorithm, and not a 
"floating-point algorithm" in any way: It will work on strings, lists, sets, 
anything that get_current_value returns, including non-NaN floats. You don't 
need to know anything about floating-point representation to write or use such 
an algorithm, why should you? It works on tuples, sets, lists, serial port 
handles, module objects, pretty much anything you can imagine -- except NaN floats.


regards, Anders

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


Re: NaN comparisons - Call For Anecdotes

2014-07-08 Thread Anders J. Munch


Ian Kelly wrote:

As far as I know nothing changed between 2.4 and 2.7 in this regard.
Python has always had NaN compare unequal to everything, per the
standard.

It might have been platform-specific in 2.4.


Okay, here's your problem: there isn't just one binary representation
for NaN.
I'm fully aware of that. Whether NaN's are one equivalence class or several is 
not the issue. What matters is the integrity of the equivalence relation.


Following the standard isn't a good reason itself? 


If a standard tells you to jump of a cliff...

regards, Anders

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


Re: NaN comparisons - Call For Anecdotes

2014-07-08 Thread Anders J. Munch

Steven D'Aprano wrote:
Oh, you've read the IEEE-754 standard, and that's what it says? "We're going 
to specify this behaviour for NANs just to annoy people" perhaps? 
I was referring to the deliberate choice to enforce IEEE-754 rules in Python. 
There is no force of law that requires Python to do so.


regards, Anders

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


Re: NaN comparisons - Call For Anecdotes

2014-07-08 Thread Anders J. Munch

Ethan Furman skrev:
What exception? Apparently your claims about NaN in Python are all wrong -- 
have you been using a custom interpreter?

>>> float('inf') - float('inf')
nan

If you deliberately try to manufacture NaN's, you can. I never said otherwise.

regards, Anders

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


Re: NaN comparisons - Call For Anecdotes

2014-07-08 Thread Anders J. Munch


Den 14-07-08 19:23, Skip Montanaro skrev:


In addition to what others have written, I will add one thing. There
are certainly situations where raising an exception is bad. Consider
all the people in the scientific computing community doing fancy
linear algebra sorts of things, often with missing data. They
generally want NaN propagated and not have some long running
calculation crash in the middle.


NaN!=NaN doesn't cause NaN's to propagate any more or any less. It simply causes 
a different branch of code to run, quite often the wrong one.


regards, Anders

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


Re: NaN comparisons - Call For Anecdotes

2014-07-08 Thread Anders J. Munch

I wrote:

Steven D'Aprano wrote:
Oh, you've read the IEEE-754 standard, and that's what it says? "We're going 
to specify this behaviour for NANs just to annoy people" perhaps? 
I was referring to the deliberate choice to enforce IEEE-754 rules in Python. 
There is no force of law that requires Python to do so.




And just to be clear, I didn't mean python-dev did this to annoy people either. 
I just meant that the choice made is not supported by any use case, so there's 
no upside to outweigh the problems it creates.


At least I've yet to hear any use case. So far I'm 0 beers in debt.

regards, Anders
--
https://mail.python.org/mailman/listinfo/python-list


Re: [Python-Dev] == on object tests identity in 3.x

2014-07-08 Thread Anders J. Munch

Steven D'Aprano wrote:


- Dropping reflexivity preserves the useful property that NANs compare
   unequal to everything.


Please present an example from real life where that turned out useful, and earn 
yourself a beer!

I've only experienced examples to the contrary.


- Keeping reflexivity for NANs would have implied some pretty nasty
   things, e.g. if log(-3) == log(-5), then -3 == -5.


>>> log(-3)
Traceback (most recent call last):
File "", line 1, in 
ValueError: math domain error

You were perhaps referring to the log functions in C and Fortran, not math.log?
The tradeoffs are different in those languages, so choices the IEEE-754 
committee made with C and Fortran in mind may be less relevant for Python.


regards, Anders

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


Re: NaN comparisons - Call For Anecdotes

2014-07-09 Thread Anders J. Munch

I wrote:

| class Monitor(Thread):
| def run(self):
| old = self.get_current_value()
| while not self.Terminated:
| new = self.get_current_value()
| if new != old:
| print(time.asctime(), "changed to", new)
| old = new
| time.sleep(1)



Huh, I don't know what happened to the identation here, I'l try again:

class Monitor(Thread):
def run(self):
old = self.get_current_value()
while not self.Terminated:
new = self.get_current_value()
if new != old:
print(time.asctime(), "changed to", new)
old = new
....time.sleep(1)

regards, Anders

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


Re: NaN comparisons - Call For Anecdotes

2014-07-09 Thread Anders J. Munch

Steven D'Aprano wrote:

It seems to me that the trivial work-around is:

* gather packed floats from some device, as ints
* process them *as ints* in some way which requires reflexivity
* unpack back into floats
* (maybe) much later perform numeric calculations on them


Although perhaps I don't understand your use-case.


Clearly you do not. floats are not ints. I have no idea how you imagine 
processing IEEE-754 floating-point values in int form.


My use case is: Working with IEEE-754 floating-point values. That means storing 
and retrieving them, serialising and transferring them, accepting them as user 
input, printing them, all the usual things you do with values.


And doing so in a way that does not require special handling in algorithms that 
are otherwise generic.
When the same algorithm is capable of dealing with ints, bytestrings, text 
string, tuples, list, dictionaries, time stamps, NoneType's, bools, 
floating-point floats and a thousand other things, then NaNs stand out as the 
values that have special algorithm-breaking magic.


I gave an example of such an algorithm in an earlier reply to Chris.

regards, Anders

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


Re: NaN comparisons - Call For Anecdotes

2014-07-09 Thread Anders J. Munch

Chris Angelico:

If you need to do bitwise comparisons, then the easiest way is to use
the bitpattern, converted to an integer. A 64-bit float becomes a
64-bit integer. It's then very simple to compare them, and reflexivity
is maintained. At what point do you actually need them to be floats?
What are you really doing with them?


What does one do with floats? Add, subtract, multipy, divide, display, input, 
store and retrieve to and from various formats.

All the usual stuff. Why would my use be different from anyone elses?

What you and Steven seem to be saying is that I should employ strategies to 
avoid NaNs ever being compared. I'll take that one step further and say that as 
long as NaN!=NaN, everyone should seek to avoid NaNs ever being compared.


regards, Anders

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


Re: NaN comparisons - Call For Anecdotes

2014-07-09 Thread Anders J. Munch

Steven D'Aprano wrote:

I assumed that you realised that the 64-bit(?) values you were receiving
in binary could be interpreted as ints. After all, you have to unpack
them from some bytes.



Since that's not what you're doing, I have no idea what it is.


Stop obsessing over how NaN's came to exist in my software. That's just context.
The argument is over how those NaNs should behave. Their provenance is not 
relevant.


I have no idea how you imagine
processing IEEE-754 floating-point values in int form.

Cast your 64-bit float into a 64-bit int.


I can construct a bijective mapping between any data structure and a subset of 
the natural numbers, but that has nothing to do with practical programming.

A "cast" value would be impossible to work with.




My use case is: Working with IEEE-754 floating-point values. That means
storing and retrieving them, serialising and transferring them,
accepting them as user input, printing them, all the usual things you do
with values.

But apparently not arithmetic?
Of course also arithmetic. I left it out of the list because then you would say 
"hah! if you're doing arithmetic then it's not a generic algorithm". Apparently 
I can't win, you are going to nitpick anything I write.


Ah, well there's your problem. NANs are special, as a signed zeroes and INFs. 
Does it distress you that x + x = x when x is an INF?

No.


When the same algorithm is capable of dealing with ints, bytestrings,
text string, tuples, list, dictionaries, time stamps, NoneType's, bools,
floating-point floats and a thousand other things,

   ^

Obviously not, or you wouldn't be complaining about the inability to
handle floats.


NaNs are not floating-point values. A floating-point value has a sign, an 
exponent and a mantissa.  They are "IEEE 754 floating point" values, though.



The hardware devices generating your float data... do they also generate
ints, bytestrings, text strings, tuples, lists, dicts, time stamps, None,
bools, and a thousand other things? If not, I wonder why you are
insisting that you have to handle a *specialised* data type using a
*generic* algorithm.
All the other types are also specialised, for their separate purpose. That 
doesn't make them non-reflexive.




I'm not unsympathetic to your problem, which is why I proposed two new
operators, === and !==, and a change to == and !=, in another thread.
Would == always doing an identity test before calling __eq__ solve your
problem? If not, what would it take to solve your problem?

It would not solve it. Two bitwise identical NaNs would still compare different.
What would solve the problem is making identical NaNs compare equal.

regards, Anders

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


Re: NaN comparisons - Call For Anecdotes

2014-07-09 Thread Anders J. Munch

Ethan Furman:
I would suggest you ask for this on the numerical mailing lists instead of 
here -- and you may not want to offer a beer to everyone that has an anecdote 
for NaN behavior being useful.
I don't have time to start this discussion over again on another mailing list. 
Don't anyone on those lists read python-list also?


regards, Anders

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


Re: NaN comparisons - Call For Anecdotes

2014-07-09 Thread Anders J. Munch

Joel Goldstick wrote:
I've been following along here, and it seems you haven't received the answer 
you want or need.


So far I received exactly the answer I was expecting.  0 examples of NaN!=NaN 
being beneficial.
I wasn't asking for help, I was making a point.  Whether that will lead to 
improvement of Python, well, I'm not too optimistic, but I feel the point was 
worth making regardless.


regards, Anders

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


Re: NaN comparisons - Call For Anecdotes

2014-07-14 Thread Anders J. Munch

alister wrote:

I don't have time to start this discussion over again on another mailing
list.
Don't anyone on those lists read python-list also?

they possibly do, but prefer to keep discussions to the proper forum


The semantics of the Python programming language is on-topic for python-list. 
This is about float.__eq__, not about numpy or SciPy.

Maybe they just don't like beer?

regards, Anders

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


Re: NaN comparisons - Call For Anecdotes

2014-07-15 Thread Anders J. Munch

Steven D'Aprano:

I'll give you the benefit of the doubt, and assume that when you first
posted you hadn't realised that the audience here does not have the
relevant experience, but by refusing to ask the question elsewhere, and
by making snide comments that "they don't like beer", that pretty much
gives the game away that you're looking to have your opinion confirmed
rather than looking for an honest answer.


I really did run out of time when I said I did: I spent the last 5 days running 
a chess tournament with 137 participants, with the tournament management 
software written in Python by yours truly. Which worked beautifully, Python is a 
great language. And I'm going to Iceland on vacation tomorrow, so I'm not going 
to start a new discussion of a different mailing list just now, maybe later. Not 
everyone is as prolific a writer as you are, Steven.


The talk about "the wrong list" would have carried more weight if you had 
started out by saying "wrong list", instead of going through every other 
argument first, before punting like that. By the way, which list is the 
appropriate one? The numpy and SciPy mailing lists are first and foremost about 
numpy and SciPy, I presume. Is there a general numerics-list somewhere also? I 
don't see any on https://mail.python.org/mailman/listinfo.


By the way, you guys seem to have overlooked the opportunity for arbitrage: 
*Anyone* can go to a numerical list, poll for examples, and come back and earn 
some beer :)


regards, Anders

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


Re: Python 3 is killing Python

2014-07-15 Thread Anders Wegge Keller
Kevin Walzer  writes:

> I can only think of two widely used languages in the last decade where
> there was this type of major break in binary compatibility: Perl and
> Visual Basic.

 Lua 5.1, 5.2 and 5.3 are all incompatible to some extent. It's
debatable how widely used Lua is as a stand-alone language, but the
usage is pretty widespread; it's just mostly concealed inside another
application.

-- 
/Wegge

Leder efter redundant peering af dk.*,linux.debian.*
-- 
https://mail.python.org/mailman/listinfo/python-list


Is there a tracker target for this mailing list?

2014-07-31 Thread Anders Wegge Keller
 My spam filter have an issue with the way mails are sent to this list. If a
mail sent to python-list is DKIM-signed, the DKIM-Signature header is kept
in the mail. Since the mangling happening during distribution to the list
changes one of the signed header fields, rather a lot of the mails to the
list ends up in Spam. 

 So where to report this issue?

-- 
//Wegge
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is there a tracker target for this mailing list?

2014-07-31 Thread Anders Wegge Keller
On Thu, 31 Jul 2014 14:57:36 -0400
Terry Reedy  wrote:

> On 7/31/2014 9:38 AM, Anders Wegge Keller wrote:
> >   My spam filter have an issue with the way mails are sent to this list.
> > If a mail sent to python-list is DKIM-signed, the DKIM-Signature header
> > is kept in the mail. Since the mangling happening during distribution to
> > the list changes one of the signed header fields, rather a lot of the
> > mails to the list ends up in Spam.
> >
> >   So where to report this issue?
> 
> All python.org list are run with 'mailman', www.list.org , which has 
> multiple lists about mailman.  I am assuming that the behavior you 
> describe is not specific to python-list.

 It is. The wikimedia/wikipedia/mediawiki lists I subscribe to, also use
Mailman. There are no problems with either wrong DKIM-signatures, nor wrong
spf checks.

-- 
//Wegge
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Global indent

2014-08-23 Thread Anders Wegge Keller
On Sun, 24 Aug 2014 00:56:11 +1000
Steven D'Aprano  wrote:

> Despite my comments, I don't actually have any objection to people who
> choose to use Emacs, or Vim, or edit their text files by poking the hard
> drive platter with a magnetised needle if they prefer :-) But I do think
> it's silly of them to claim that Emacs has no learning curve, or to fail to
> recognise how unfamiliar and different the UIs are compared to nearly
> everything else a computer user is likely to be familiar with in 2014.

 Really, they don't! At least not for the people, for whom they are
necessary tools. When I started in my present job, "remote access" was
a dial-up modem, that could do 2400 baud, if you were lucky[1]. With such a
shitty connection, a text-only editor is indisputably the right thing. 

 Curiously enough, even today the same lousy kind of connections prevail. We
still have a sizeable modem bank at my job. We still do our remote support
over a telnet/ssh session. And we still are unable to reliable get the 
connection speeds[2], that would make anything with a GUI remotely
pleasant. 

 So emacs and vim still have their niches. Those of us, who are old enough
to have started our first job in a glorified teletype, OR have to support
systems that are only reachable over RFC-1149 quality datalinks, belong
there. The rest of you would probably be better off with something nicer.

1. Meaning a real switched landline all the way from Denmark to Tokyo.
Ending up with two satellite up/down-links was a killer.

2. We have an installation in the Philippines, where we ended up installing a
   satellite uplink. It feels like we have doubled the connectivity of the
   entire Manilla area by doing so. And it's still painfully slow.

-- 
//Wegge
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: enumerate improvement proposal

2006-10-30 Thread Anders J. Munch
Ben Finney wrote:
> 
> >>> def obstinate_economist_enumerate(items):
> ... enum_iter = iter((i+1, x) for (i, x) in enumerate(items))
> ... return enum_iter

iter is redundant here.

def natural_enumerate_improvement(items, start=0):
 return ((i+start, x) for (i, x) in enumerate(items))

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


Re: QuoteSQL

2006-09-23 Thread Anders J. Munch
Lawrence D'Oliveiro wrote:
> Why doesn't MySQLdb provide a function like this:
> 
> def QuoteSQL(Str, DoWild) :
> """returns a MySQL string literal which evaluates to Str. Needed
> for those times when MySQLdb's automatic quoting isn't good enough."""

Presumably because you're expected to use placeholders.  When is that 
not good enough?

> elif Ch == "'" or Ch == "\"" or Ch == "\\" :
> Ch = "\\" + Ch

Always sad to see an SQL DBMS willfully violate the SQL standard.

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


Relative import first impressions

2006-09-23 Thread Anders J. Munch
Now 2.5 is out, and we have a syntax for explicit relative imports
(PEP 328, http://www.python.org/dev/peps/pep-0328/, in case anyone
wasn't paying attention).  The long-term plan is that the classical
import syntax becomes absolute import only, so that all imports are
explicitly one or the other.

You can only use relative import from within packages.  Trying to
import a top-level module relatively from within same directory,
produces the exception "ValueError: Relative importpath too deep".

There's a certain logic to that: You can just omit "from ." and do a
regular absolute import.  However, that spells bad news for modules
that are both contained within packages, and executed from the top
level as well.

Accessing the same module both from within a package and outside it
may seem like a bad idea, and in many ways, it is.  You may get a
double import of the same module with subtle, mysterious bugs to
follow, when e.g. you suddenly have two copies of the "same" class,
and isinstance(obj,mymodule.Cls) fails unexpectedly.

But it's quite common all the same: The
if __name__ == "__main__":
idiom is often used, even within packages.  But that is currently
incompatible with using relative imports.  It seems to me that unless
we rethink the main idiom competely (which may not be a bad idea by
the way, for the reasons given above), relative imports at the top
level will need to be allowed.

Another addition I'd like to see it the "import .foo" form.  Currently
only "from"-imports have a relative form.  The argument against is
that "import X" binds the name X, and it's not clear which name the
relative import binds.

I move that it's blindingly obvious: "import .foo" binds "foo",
equivalent to "from . import foo".  Did anyone really expect the name
".foo" to be bound?

It's not a big deal though, as you only need to type "from ." once per
module anyway.  Using another improvement in 2.5, you can now write:

from . import (
 this,
 that,
 )

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


Re: QuoteSQL

2006-09-24 Thread Anders J. Munch
Robert Kern wrote:
> Anders J. Munch wrote:
> 
>> Always sad to see an SQL DBMS willfully violate the SQL standard.
> 
> You must be a constantly depressed person, then.  :-)

Nah, I just look the other way most of the time *g*

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


Re: QuoteSQL

2006-09-24 Thread Anders J. Munch
Lawrence D'Oliveiro wrote:
>>> elif Ch == "'" or Ch == "\"" or Ch == "\\" :
>>> Ch = "\\" + Ch
>> Always sad to see an SQL DBMS willfully violate the SQL standard.
> 
> Why is that a violation of SQL?

Taking another look, I might be wrong: Your code uses double quotes, and 
since SQL uses single quotes for string literals, it just might be a 
compatible extension.

Otherwise I would have taken note of the backslash escapes.  E.g. '\\' 
is a two-character SQL string literal.

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


Re: merits of Lisp vs Python

2006-12-20 Thread Anders J. Munch
jayessay wrote:
  > Please note: GC is not part of CL's definition.  It is likely not part
> of any Lisp's definition (for reasons that should be obvious), and for
> the same reasons likely not part of any language's definition.  

Really?  So how do you write a portable program in CL, that is to run 
for unbounded lengths of time?

- Anders

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


Re: merits of Lisp vs Python

2006-12-20 Thread Anders J. Munch
Rob Thorpe wrote:
 > Anders J. Munch wrote:
 >> Really?  So how do you write a portable program in CL, that is to
 >> run for unbounded lengths of time?
 >
 > You can't.
 >
 > The thing about the spec not defining GC is almost a bit of humour.
 > No-one would use an implementation with no GC.
 >
 > The issue with specifying it is: How would you do it?  The memory
 > used by a program is an aspect of the language implementation and
 > the system the program is running on, so how can it be defined in a
 > useful way?

Let u(t) be the actual memory used by the program at time t.
Let r(t) be the size of reachable memory at time t.

Require that u(t) is a member of O(t -> max{t'<=t: r(t')})

There. That wasn't so hard, was it?

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


Re: merits of Lisp vs Python

2006-12-21 Thread Anders J. Munch
Rob Thorpe wrote:
> Anders J. Munch wrote:
>> Let u(t) be the actual memory used by the program at time t.
>> Let r(t) be the size of reachable memory at time t.
>>
>> Require that u(t) is a member of O(t -> max{t'<=t: r(t')})
>>
>> There. That wasn't so hard, was it?
> 
> That's quite a clever definition actually.
> But, let's say I have a lisp machine.  It has an unusual architecture,
> it's made entirely of SRAM cells of ~9bits.  Sometimes these cells are
> used as storage, sometimes their contents represent logic circuits and
> the routing between them is configured to form them into a processor.
> Please tell me what reachable memory is ;).  (The above processor is
> not science fiction, it could easily be done with FPGAs)

Reachable memory is the set of interpreter objects (conses, closures, scopes, 
atoms and what have you) reachable from from some appropriately defined root 
set.  It can be unambiguously defined with respect to a virtual machine, with 
no 
regard to how actual implementations represent these things.

For actual memory use, a simple byte count would do fine.  If code and data are 
intermingled, just use the combined size of both of them.

If you're worried about comparing incompatible units, don't be: apples and 
oranges compare just fine under big-Oh.

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


Re: Where can I suggest an enchantment for Python Zip lib?

2007-06-10 Thread Anders J. Munch
durumdara wrote:
> Only one way I have to control this: if I modify the ZipFile module.

Since you already have the desired feature implemented, why don't you submit a 
patch.

See http://www.python.org/patches/

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


Re: Python's "only one way to do it" philosophy isn't good?

2007-06-12 Thread Anders J. Munch
Paul Rubin wrote:
> Steven D'Aprano <[EMAIL PROTECTED]> writes:
>>> Not tail calls, in general, no.
>> Sorry, how does that work? You're suggesting that there is an algorithm
>> which the compiler could follow to optimize away tail-recursion, but human
>> beings can't follow the same algorithm?
>>
>> Now I'm confused.
> 
> The usual compiler method is to translate the code into
> continuation-passing style and thereby gain tail-recursion
> optimization automagically.  

There's no need to go into CPS just to optimise tail-recursion.  After all, 
compilers were optimising tail-calls decades before Appel's work on SML/NJ.

Converting tail-recursion to iteration is trivial, and perfectly reasonable for 
a human to do by hand.  You add an outer "while True"-loop, the recursive call 
becomes a tuple assignment, and other code paths end with a break out of the 
loop.  Completely mechanical and the resulting code doesn't even look that bad.

Like Steven said, tail-call optimisation is not necessary as you can always 
hand-optimise it yourself.

- Anders

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


Re: Python's "only one way to do it" philosophy isn't good?

2007-06-13 Thread Anders J. Munch
Neil Cerutti wrote:
> On 2007-06-12, Anders J. Munch <[EMAIL PROTECTED]> wrote:
>> Converting tail-recursion to iteration is trivial, and
>> perfectly reasonable for a human to do by hand.  
> 
> For simple recursive tail calls, yeah, it can be. Translating a
> tail-recursive Factorial function into a while loop is easy. But
> tail-call optimization technically works for any tail-call,
> including mutual recursion, and non-recursive tail-calls. You
> can't reasonably hand-optimize away the stack frame for all
> tail-calls.

I may have misunderstood, I thought we were talking about tail recursion only. 
The general tail-call optimisation, where all leaf calls become jumps and the 
called function usurps the current stack frame, is a different ballgame 
entirely.  There's no pure-Python transformation for that, but that still 
doesn't mean you need CPS.

General tail-call optimisation is of course completely out-of-bounds for 
Python, 
because it ruins tracebacks.  Unlike tail recursion, which could use recursion 
counters.

- Anders

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


Re: Python's "only one way to do it" philosophy isn't good?

2007-06-13 Thread Anders J. Munch
Alexander Schmolck wrote:
> "Anders J. Munch" <[EMAIL PROTECTED]> writes:
> 
>> Like Steven said, tail-call optimisation is not necessary as you can always
>> hand-optimise it yourself.
> 
> Care to demonstrate on some code written in CPS (a compiler or parser, say)?

I meant tail recursion, not tail-call, sorry, that was just my fingers trying 
to 
save typing.

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


  1   2   >