[no subject]

2012-07-04 Thread levi nie

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


Re: a problem about "print"

2012-07-04 Thread levi nie
Hi,Harrison.
Your method is cool.
But i doubt this, if bList and aList just are attached to the same List
when i write bList=aList,but why the output of the following two code are
different?

code1:
aList=[1,2,3,4,5,6,7,8,9,10]
bList=aList
bList=str(bList)
print aList
print aList[2]

code2:
aList=[1,2,3,4,5,6,7,8,9,10]
aList=str(aList)
print aList
print aList[2]

i'm puzzled now.

2012/7/4 Harrison Morgan 

>
>
> On Wed, Jul 4, 2012 at 12:38 AM, levi nie  wrote:
>
>> that's good,thanks.
>> new problem.
>> when i write
>> bList=aList
>> del bList[2]
>> bList and aList both change,how can i make aList not changed?
>>
>>>
>>
> Lists are mutable. That means that when you do bList = aList, you're just
> creating another reference to aList. They both point to the same list, just
> using different names. You should read up a bit on immutable vs. mutable
> objects. Here's something that I found that might explain it a bit better.
> http://henry.precheur.org/python/copy_list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a problem about "print"

2012-07-04 Thread Chris Angelico
On Wed, Jul 4, 2012 at 5:28 PM, levi nie  wrote:
> aList=str(aList)
> print aList
> print aList[2]

The str() function takes pretty much anything and returns a string.
When you subscript a string, you get characters. It's not a list of
numbers any more.

(Technically str is a class, not a function, but that distinction
doesn't matter.)

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


Re: a problem about "print"

2012-07-04 Thread Matteo Boscolo

in the code2

aList=[1,2,3,4,5,6,7,8,9,10]
aList=str(aList) #<--- here you convert the list in a string

print aList
print aList[2] #<-- here you are printing the third caracter of the 
string '[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]'  not the list '[1, 2, 3, 4, 5, 
6, 7, 8, 9, 10]'


regards
Matteo



Il 04/07/2012 09:28, levi nie ha scritto:

Hi,Harrison.
Your method is cool.
But i doubt this, if bList and aList just are attached to the same 
List when i write bList=aList,but why the output of the following two 
code are different?


code1:
aList=[1,2,3,4,5,6,7,8,9,10]
bList=aList
bList=str(bList)
print aList
print aList[2]

code2:
aList=[1,2,3,4,5,6,7,8,9,10]
aList=str(aList)
print aList
print aList[2]

i'm puzzled now.

2012/7/4 Harrison Morgan >




On Wed, Jul 4, 2012 at 12:38 AM, levi nie mailto:levinie...@gmail.com>> wrote:

that's good,thanks.
new problem.
when i write
bList=aList
del bList[2]
bList and aList both change,how can i make aList not changed?



Lists are mutable. That means that when you do bList = aList,
you're just creating another reference to aList. They both point
to the same list, just using different names. You should read up a
bit on immutable vs. mutable objects. Here's something that I
found that might explain it a bit better.
http://henry.precheur.org/python/copy_list







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


Re: when "normal" parallel computations in CPython will be implemented at last?

2012-07-04 Thread Tim Roberts
John Nagle  wrote:
>
>It would be "un-Pythonic" to have real concurrency in Python.
>You wouldn't be able to patch code running in one thread from
>another thread.  Some of the dynamic features of Python
>would break.   If you want fine-grained concurrency, you need
>controlled isolation between concurrent tasks, so they interact
>only at well-defined points.  That's un-Pythonic.

I disagree.  The situation in Python is no different than the situation in
other programming languages.  If you have shared state, you protect it with
some kind of lock.  After all, you don't patch code on a byte-by-byte basis
-- you just change function bindings.  That can be done atomically.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: code review

2012-07-04 Thread alex23
On Jul 4, 3:39 pm, "Littlefield, Tyler"  wrote:
> I basically just stopped after a while. It got into a my language is
> better than your language, so I didn't see much constructive info.

To be fair, it's more "my vision of the language is better than
yours" :) But yes, it should've been forked into a separate thread
ages okay.

It did get me wondering, though, if there's much in the way of support
for code review in repository sites like github? Being able to
aggregate comments around the actual code itself could be really
handy.

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


Re: code review

2012-07-04 Thread rusi
On Jul 4, 11:17 am, alex23  wrote:
> On Jul 4, 3:39 pm, "Littlefield, Tyler"  wrote:
>
> > I basically just stopped after a while. It got into a my language is
> > better than your language, so I didn't see much constructive info.
>
> To be fair, it's more "my vision of the language is better than
> yours" :) But yes, it should've been forked into a separate thread
> ages okay.

A program is a product of a person's creativity as is a programming
language.
They have an analogous relation as say a sculpture to chisels.
This thread is a good example of how longwindedness of a discussion
correlates with its uselessness.
However the reverse error is more insidious: programs are made by
humans and should be critiqued, whereas programming languages (in
particular python) is sacrosanct and cannot be questioned.

Too often I find that responders on this list treat as personal
affront anyone who questions python whereas the most appropriate
response would be: Nice idea but too invasive for serious
consideration.

[I am saying this in general and not for this thread:Whats wrong with
a < b < c is quite beyond me!]

>
> It did get me wondering, though, if there's much in the way of support
> for code review in repository sites like github? Being able to
> aggregate comments around the actual code itself could be really
> handy.

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


Re: a problem about "print"

2012-07-04 Thread levi nie
Yes,you are right.

2012/7/4 Chris Angelico 

> On Wed, Jul 4, 2012 at 5:28 PM, levi nie  wrote:
> > aList=str(aList)
> > print aList
> > print aList[2]
>
> The str() function takes pretty much anything and returns a string.
> When you subscript a string, you get characters. It's not a list of
> numbers any more.
>
> (Technically str is a class, not a function, but that distinction
> doesn't matter.)
>
> ChrisA
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a problem about "print"

2012-07-04 Thread levi nie
Yes,you're right.
I got it now.I mistaked that aList also had be changed in code1 before.
Thanks a lot.

2012/7/4 Matteo Boscolo 

>  in the code2
>
> aList=[1,2,3,4,5,6,7,8,9,10]
> aList=str(aList) #<--- here you convert the list in a string
>
>  print aList
> print aList[2] #<-- here you are printing the third caracter of the string
> '[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]'  not the list '[1, 2, 3, 4, 5, 6, 7, 8,
> 9, 10]'
>
> regards
> Matteo
>
>
>
> Il 04/07/2012 09:28, levi nie ha scritto:
>
> Hi,Harrison.
> Your method is cool.
> But i doubt this, if bList and aList just are attached to the same List
> when i write bList=aList,but why the output of the following two code are
> different?
>
>  code1:
>  aList=[1,2,3,4,5,6,7,8,9,10]
> bList=aList
> bList=str(bList)
> print aList
> print aList[2]
>
>  code2:
>  aList=[1,2,3,4,5,6,7,8,9,10]
> aList=str(aList)
> print aList
> print aList[2]
>
>  i'm puzzled now.
>
> 2012/7/4 Harrison Morgan 
>
>>
>>
>> On Wed, Jul 4, 2012 at 12:38 AM, levi nie  wrote:
>>
>>> that's good,thanks.
>>> new problem.
>>> when i write
>>> bList=aList
>>> del bList[2]
>>> bList and aList both change,how can i make aList not changed?
>>>

>>>
>>  Lists are mutable. That means that when you do bList = aList, you're
>> just creating another reference to aList. They both point to the same list,
>> just using different names. You should read up a bit on immutable vs.
>> mutable objects. Here's something that I found that might explain it a bit
>> better. http://henry.precheur.org/python/copy_list
>>
>
>
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a problem about "print"

2012-07-04 Thread Mark Lawrence
@Matteo, @Levi, please don't top post it makes following a thread very 
difficult, no other comments, TIA.


On 04/07/2012 08:51, Matteo Boscolo wrote:

in the code2

aList=[1,2,3,4,5,6,7,8,9,10]
aList=str(aList) #<--- here you convert the list in a string

print aList
print aList[2] #<-- here you are printing the third caracter of the
string '[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]'  not the list '[1, 2, 3, 4, 5,
6, 7, 8, 9, 10]'

regards
Matteo



Il 04/07/2012 09:28, levi nie ha scritto:

Hi,Harrison.
Your method is cool.
But i doubt this, if bList and aList just are attached to the same
List when i write bList=aList,but why the output of the following two
code are different?

code1:
aList=[1,2,3,4,5,6,7,8,9,10]
bList=aList
bList=str(bList)
print aList
print aList[2]

code2:
aList=[1,2,3,4,5,6,7,8,9,10]
aList=str(aList)
print aList
print aList[2]

i'm puzzled now.

2012/7/4 Harrison Morgan mailto:harrison.mor...@gmail.com>>



On Wed, Jul 4, 2012 at 12:38 AM, levi nie mailto:levinie...@gmail.com>> wrote:

that's good,thanks.
new problem.
when i write
bList=aList
del bList[2]
bList and aList both change,how can i make aList not changed?



Lists are mutable. That means that when you do bList = aList,
you're just creating another reference to aList. They both point
to the same list, just using different names. You should read up a
bit on immutable vs. mutable objects. Here's something that I
found that might explain it a bit better.
http://henry.precheur.org/python/copy_list













--
Cheers.

Mark Lawrence.



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


Re: code review

2012-07-04 Thread Mark Lawrence

On 03/07/2012 22:54, Chris Angelico wrote:

On Wed, Jul 4, 2012 at 6:13 AM, Dave Angel  wrote:

On 07/03/2012 12:05 PM, Mark Lawrence wrote:

If I go to the moon I will weigh 2st 10lb (if my sums are correct :)
but the equivalent Frenchman will still be 86kg. I hereby put this
forward as proof that the metric system is rubbish and we should
revert back to imperial goodies.



86 kg is not a weight, it's a mass.  So it doesn't depend on the local
gravity situation.


Indeed it is, as he says. But I believe he may be right in that
'stone' is a unit of weight. Hard to be sure, though, given that it's
not an SI unit (for instance, the Wikipedia article text refers to
weight, but its picture shows a man measuring mass).

ChrisA



Stone is a unit of weight (Brits know important things like this).  And 
with the consistency that the English language is reknowned for the 
plural is, yes you've guessed it, stone :)


--
Cheers.

Mark Lawrence.



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


Using a CMS for small site?

2012-07-04 Thread Gilles
Hello

Someone I know with no computer knowledge has a studio appartment to
rent in Paris and spent four months building a small site in Joomla to
find short-time renters.

The site is just...
- a few web pages that include text (in four languages) and pictures
displayed in a Flash slide show
- a calendar to show availability
- a form to send e-mail with anti-SPAM support
- (ASAP) online payment

Out of curiosity, are there CMS/frameworks in Python that can do this?
Django? Other?

Is a full-fledged CMS even needed for something like that?

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


Re: code review

2012-07-04 Thread Paul Rudin
Mark Lawrence  writes:

> On 03/07/2012 03:25, John O'Hagan wrote:
>> On Tue, 3 Jul 2012 11:22:55 +1000
>>
>> I agree to some extent, but as a counter-example, when I was a child there
>> a subject called "Weights and Measures" which is now redundant because of the
>> Metric system. I don't miss hogsheads and fathoms at all.
>>
>> John
>>
>
> I weigh 13st 8lb - does this make me redundant?

It might mean that you have some redundant weight :)
-- 
http://mail.python.org/mailman/listinfo/python-list


adding a simulation mode

2012-07-04 Thread andrea crotti
I'm writing a program which has to interact with many external
resources, at least:
- mysql database
- perforce
- shared mounts
- files on disk

And the logic is quite complex, because there are many possible paths to
follow depending on some other parameters.
This program even needs to run on many virtual machines at the same time
so the interaction is another thing I need to check...

Now I successfully managed to mock the database with sqlalchemy and only
the fields I actually need, but I now would like to simulate also
everything else.

I would like for example that if I simulate I can pass a fake database,
a fake configuration and get the log of what exactly would happen.  But
I'm not sure how to implement it now..  One possibility would be to have
a global variable (PRETEND_ONLY = False) that if set should be checked
before every potentially system-dependent command.

For example

copytree(src, dest) becomes:
if not PRETEND_ONLY:
copytree(src, dest)

But I don't like it too much because I would have to add a lot of
garbage around..

Another way is maybe to set the sys.excepthook to something that catchs
all the exceptions that would be thrown by these comands, but I'm not
sure is a good idea either..

Any suggestion?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using a CMS for small site?

2012-07-04 Thread Roy Smith
In article ,
 Gilles  wrote:

> Hello
> 
> Someone I know with no computer knowledge has a studio appartment to
> rent in Paris and spent four months building a small site in Joomla to
> find short-time renters.
> 
> The site is just...
> - a few web pages that include text (in four languages) and pictures
> displayed in a Flash slide show
> - a calendar to show availability
> - a form to send e-mail with anti-SPAM support
> - (ASAP) online payment
> 
> Out of curiosity, are there CMS/frameworks in Python that can do this?
> Django? Other?

You probably want to look at https://www.django-cms.org/.  It's not 
something that a person with "no computer knowledge" could set up, but 
once it's set up, that person could use it to build pages.

But, to be honest, for somebody who really doesn't know anything, some 
much more pre-canned solution like WordPress might be what they're 
looking for.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: code review

2012-07-04 Thread levi nie
2012/7/4 Paul Rudin 

> Mark Lawrence  writes:
>
> > On 03/07/2012 03:25, John O'Hagan wrote:
> >> On Tue, 3 Jul 2012 11:22:55 +1000
> >>
> >> I agree to some extent, but as a counter-example, when I was a child
> there
> >> a subject called "Weights and Measures" which is now redundant because
> of the
>

Just a Test.I didn't familiar about maillist.

> >> Metric system. I don't miss hogsheads and fathoms at all.
> >>
> >> J
>
>>
> >
> > I weigh 13st 8lb - does this make me redundant?
>
> It might mean that you have some redundant weight :)
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


locals().update(...)

2012-07-04 Thread eisoab


I expected this to work:


def f(**args):
locals().update(args)
print locals()
print a

d=dict(a=1)

f(**d)

but:
> global name 'a' is not defined


Where is my mistake?

This does work:

globals().update({'a':1})

print a

1

-E

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


Re: locals().update(...)

2012-07-04 Thread Christian Heimes
Am 04.07.2012 13:56, schrieb eis...@gmail.com:
> I expected this to work:

It doesn't work and that's documented:

http://docs.python.org/library/functions.html?highlight=locals#locals

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


Re: adding a simulation mode

2012-07-04 Thread Steven D'Aprano
On Wed, 04 Jul 2012 10:42:56 +0100, andrea crotti wrote:

> I'm writing a program which has to interact with many external
> resources, at least:
> - mysql database
> - perforce
> - shared mounts
> - files on disk
> 
> And the logic is quite complex, because there are many possible paths to
> follow depending on some other parameters. This program even needs to
> run on many virtual machines at the same time so the interaction is
> another thing I need to check...
> 
> Now I successfully managed to mock the database with sqlalchemy and only
> the fields I actually need, but I now would like to simulate also
> everything else.
> 
> I would like for example that if I simulate I can pass a fake database,
> a fake configuration and get the log of what exactly would happen.  But
> I'm not sure how to implement it now..  One possibility would be to have
> a global variable (PRETEND_ONLY = False) that if set should be checked
> before every potentially system-dependent command.

I think a better way would be to use a mock database, etc. For each thing 
which you want to simulate, create a class that has the same interface 
but a simulated implementation.

Then, have your code accept the thing as an argument.

E.g. instead of having a hard-coded database connection, allow the 
database connection to be set (perhaps as an argument, perhaps as a 
config option, etc.).

There are libraries to help with mocks, e.g.:

http://garybernhardt.github.com/python-mock-comparison/
 

> For example
> 
> copytree(src, dest) becomes:
> if not PRETEND_ONLY:
> copytree(src, dest)

Ewww :(

Mocking the file system is probably the hardest part, because you 
generally don't have a "FileSystem" object available to be replaced. In 
effect, your program has one giant global variable, the file system. 
Worse, it's not even a named variable, it's hard-coded everywhere you use 
it.

I don't know of any good solution for that. I've often thought about it, 
but don't have an answer.

I suppose you could monkey-patch a bunch of stuff:

if ONLY_PRETEND:
 open = my_mock_open
 copytree = my_mock_copytree
 # etc. 
main()  # run your application



but that would also be painful.


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


Question about weakref

2012-07-04 Thread Frank Millman

Hi all

I have a situation where I thought using weakrefs would save me a bit of 
effort.


I have a basic publish/subscribe scenario. The publisher maintains a 
list of listener objects, and has a method whereby a listener can 
subscribe to the list by passing in 'self', whereupon it gets added to 
the list.


When the publisher has something to say, it calls a pre-defined method 
on each of the listeners. Simple, but it works.


The listeners are fairly transient, so when they go out of scope, I need 
to remove them from the list maintained by the publisher. Instead of 
keeping track of all of them and removing them explicitly, I thought of 
using weakrefs and let them be removed automatically.


It almost works. Here is an example -

import weakref

class A:  # the publisher class
def __init__(self):
self.array = []
def add_b(self, b):
self.array.append(weakref.ref(b, self.del_b))
def del_b(self, b):
self.array.remove(b)
def chk_b(self, ref):
for b in self.array:
b().hallo(ref)

class B:  # the listener class
def __init__(self, a, name):
self.name = name
a.add_b(self)
def hallo(self, ref):
print(self.name, 'hallo from', ref)
def __del__(self):
print('%s deleted' % self.name)

a = A()
x = B(a, 'test x')
y = B(a, 'test y')
z = B(a, 'test z')
a.chk_b(1)
del x
a.chk_b(2)
del y
a.chk_b(3)
del z
a.chk_b(4)
print(a.array)

The output is as expected -

test x hallo from 1
test y hallo from 1
test z hallo from 1
test x deleted
test y hallo from 2
test z hallo from 2
test y deleted
test z hallo from 3
test z deleted
[]

Then I tried weakref.proxy.

I changed
self.array.append(weakref.ref(b, self.del_b))
to
self.array.append(weakref.proxy(b, self.del_b))
and
b().hallo(ref)
to
b.hallo(ref)

I got the same result.

Then I varied the order of deletion - instead of x, then y, then z, I 
tried x, then z, then y.


Now I get the following traceback -

test x hallo from 1
test y hallo from 1
test z hallo from 1
test x deleted
test y hallo from 2
test z hallo from 2
Exception ReferenceError: 'weakly-referenced object no longer exists' in 

method A.del_b of <__main__.A object at 0x00A8A750>> ignored
test z deleted
test y hallo from 3
Traceback (most recent call last):
  File "F:\junk\weaklist.py", line 70, in 
a.chk_b(3)
  File "F:\junk\weaklist.py", line 51, in chk_b
b.hallo(ref)
ReferenceError: weakly-referenced object no longer exists
test y deleted

If I go back to using weakref.ref, but with the new deletion order, it 
works.


So now I am confused.

1. Why do I get the traceback?

2. Can I rely on using weakref.ref, or does that also have some problem 
that has just not appeared yet?


Any advice will be appreciated.

BTW, I am using python 3.2.2.

Thanks

Frank Millman

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


Re: adding a simulation mode

2012-07-04 Thread andrea crotti
2012/7/4 Steven D'Aprano :
>
> Then, have your code accept the thing as an argument.
>
> E.g. instead of having a hard-coded database connection, allow the
> database connection to be set (perhaps as an argument, perhaps as a
> config option, etc.).
>
> There are libraries to help with mocks, e.g.:
>
> http://garybernhardt.github.com/python-mock-comparison/

Ah yes this part is already done, I pass an object to the entry point
of the program which represents the database connection, which looks
like this:

class MockMysqlEngine(MySqlEngine):
# TODO: make the engine more generic would avoid this dirty hack
def __init__(self, *args, **kwargs):
# self.engine =
create_engine('sqlite:home/andrea/testdb.sqlite', echo=True)
self.engine = create_engine('sqlite://', echo=True)
self.meta = MetaData(bind=self.engine)
self.session_maker = sessionmaker(bind=self.engine)


Now I populate statically the schema and populate with some test data
too, but I'm also implementing a weay to just pass some CSV files so
that other people can easily write some test cases with some other
possible database configurations.

(And I use mock for a few other things)


>
>
>> For example
>>
>> copytree(src, dest) becomes:
>> if not PRETEND_ONLY:
>> copytree(src, dest)
>
> Ewww :(
>
> Mocking the file system is probably the hardest part, because you
> generally don't have a "FileSystem" object available to be replaced. In
> effect, your program has one giant global variable, the file system.
> Worse, it's not even a named variable, it's hard-coded everywhere you use
> it.
>
> I don't know of any good solution for that. I've often thought about it,
> but don't have an answer.
>
> I suppose you could monkey-patch a bunch of stuff:
>
> if ONLY_PRETEND:
>  open = my_mock_open
>  copytree = my_mock_copytree
>  # etc.
> main()  # run your application
>
>
>
> but that would also be painful.
>

Yes there is no easy solution apparently..  But I'm also playing
around with vagrant and virtual machine generations, suppose I'm able
to really control what will be on the machine at time X, creating it
on demand with what I need, it might be a good way to solve my
problems (a bit overkill and slow maybe though).

I'll try the sys.excepthook trick first, any error should give me an
exception, so if I catch them all I think it might work already..
-- 
http://mail.python.org/mailman/listinfo/python-list


PyPyODBC 0.6 released! (A Pure Python ODBC module)

2012-07-04 Thread 江文
PyPyODBC - A Pure Python ctypes ODBC module

Changes in version 0.6:
Added Cursor.commit() and Cursor.rollback(). It is now possible to use
only a cursor in your code instead of keeping track of a connection
and a cursor.

Added readonly keyword to connect. If set to True, SQLSetConnectAttr
SQL_ATTR_ACCESS_MODE is set to SQL_MODE_READ_ONLY. This may provide
better locking semantics or speed for some drivers.

Features
-Pure Python, compatible with PyPy (tested on Win32)
-Almost totally same usage as pyodbc

You can simply try pypyodbc in your existing pyodbc powered script
with the following changes:

   #import pyodbc<-- Comment out
the original pyodbc importing line
   import pypyodbc as pyodbc # Let pypyodbc "pretend" the pyodbc
   pyodbc.connect(...)  # This is pypyodbc
pretending pyodbc! They have same APIs!
...


Homepage:http://code.google.com/p/pypyodbc/

Demo Script:

http://code.google.com/p/pypyodbc/source/browse/trunk/pypyodbc/test.py
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: adding a simulation mode

2012-07-04 Thread andrea crotti
> Yes there is no easy solution apparently..  But I'm also playing
> around with vagrant and virtual machine generations, suppose I'm able
> to really control what will be on the machine at time X, creating it
> on demand with what I need, it might be a good way to solve my
> problems (a bit overkill and slow maybe though).
>
> I'll try the sys.excepthook trick first, any error should give me an
> exception, so if I catch them all I think it might work already..


I actually thought that the sys.excepthook would be easy but it's not
so trivial apparently:
This simple sample never reaches the print("here"), because even if
the exception is catched it still quits with return code=1.

I also tried to catch the signal but same result, how do I make it
continue and just don't complain?

The other option if of course to do a big try/except, but I would
prefer the excepthook solution..


import sys
from shutil import copy

def my_except_hook(etype, value, tb):
print("got an exception of type", etype)


if __name__ == '__main__':
sys.excepthook = my_except_hook
copy('sdflsdk')
print("here")
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using a CMS for small site?

2012-07-04 Thread Gilles
On Wed, 04 Jul 2012 06:28:09 -0400, Roy Smith  wrote:
>You probably want to look at https://www.django-cms.org/.  It's not 
>something that a person with "no computer knowledge" could set up, but 
>once it's set up, that person could use it to build pages.
>
>But, to be honest, for somebody who really doesn't know anything, some 
>much more pre-canned solution like WordPress might be what they're 
>looking for.

Thanks for the input. Considering that contents won't change, I was
wondering if a full-fledged CMS was even necessary.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using a CMS for small site?

2012-07-04 Thread Roy Smith
In article <7fk8v7pijp359t62clgj5g4n3d4acva...@4ax.com>,
 Gilles  wrote:

> On Wed, 04 Jul 2012 06:28:09 -0400, Roy Smith  wrote:
> >You probably want to look at https://www.django-cms.org/.  It's not 
> >something that a person with "no computer knowledge" could set up, but 
> >once it's set up, that person could use it to build pages.
> >
> >But, to be honest, for somebody who really doesn't know anything, some 
> >much more pre-canned solution like WordPress might be what they're 
> >looking for.
> 
> Thanks for the input. Considering that contents won't change, I was
> wondering if a full-fledged CMS was even necessary.

If the content is truly never going to change, there's nothing to 
prevent you from creating some static html files with your favorite text 
editor.

This is really getting quite far afield for a Python group.  There are 
better forums for these kinds of questions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: adding a simulation mode

2012-07-04 Thread Mike C. Fletcher

On 12-07-04 05:42 AM, andrea crotti wrote:
...

copytree(src, dest) becomes:
if not PRETEND_ONLY:
 copytree(src, dest)

import globalsub, unittest

class MyTest( unittest.TestCase ):
def setUp( self ):
globalsub.subs( shutil.copytree )
def tearDown( self ):
globalsub.restore( shutil.copytree )

You can also pass a function to subs like so:

def setUp( self ):
self.copied_trees = []
def fake_copytree( src, dest ):
assert os.path.exists( src )
self.copied_trees.append( (src, dest ))
return dest # or whatever the thing should return
globalsub.subs( shutil.copytree, fake_copytree )

$ pip install globalsub

HTH,
Mike

--

  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://www.vrplumber.com
  http://blog.vrplumber.com

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


Re: adding a simulation mode

2012-07-04 Thread Devin Jeanpierre
For what it's worth, this is the reason that Allen Short wrote Exocet.

> This way, you can test your code without having to resort to sys.modules
> hackery, and you can better factor your applications by separating
> configuration and environment concerns from the rest of your code.

See:

- http://washort.twistedmatrix.com/2011/01/introducing-exocet.html
- http://washort.twistedmatrix.com/2011/03/exocet-second-look.html

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


Re: code review

2012-07-04 Thread Mark Lawrence

On 04/07/2012 10:29, Paul Rudin wrote:

Mark Lawrence  writes:


On 03/07/2012 03:25, John O'Hagan wrote:

On Tue, 3 Jul 2012 11:22:55 +1000

I agree to some extent, but as a counter-example, when I was a child there
a subject called "Weights and Measures" which is now redundant because of the
Metric system. I don't miss hogsheads and fathoms at all.

John



I weigh 13st 8lb - does this make me redundant?


It might mean that you have some redundant weight :)



True indeed, although my beer free diet of the last 10 days (yes, 10 
whole days) has at least got it down from 14 stone 2 pounds.


--
Cheers.

Mark Lawrence.



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


Re: adding a simulation mode

2012-07-04 Thread Paul Rubin
andrea crotti  writes:
> copytree(src, dest) becomes:
> if not PRETEND_ONLY:
> copytree(src, dest)
>
> But I don't like it too much because I would have to add a lot of
> garbage around..

I've had good results writing the module under test in the style of a
java applet, i.e. one of its args is a class instance representing the
"outside world", and ALL interaction that you might want to simulate is
done through this object:

   def your_prog(parent):
  conn = parent.db.make_connection(...)
  blah = parent.copytree(...)

Then you make "real" and "mock" versions of the external interface, and
pass in an appropriate instance.
-- 
http://mail.python.org/mailman/listinfo/python-list


2 + 2 = 5

2012-07-04 Thread Paul Rubin
I just came across this (https://gist.github.com/1208215):

import sys
import ctypes
pyint_p = ctypes.POINTER(ctypes.c_byte*sys.getsizeof(5))
five = ctypes.cast(id(5), pyint_p)
print(2 + 2 == 5) # False
five.contents[five.contents[:].index(5)] = 4
print(2 + 2 == 5) # True (must be sufficiently large values of 2 there...)

Heh.  The author is apparently anonymous, I guess for good reason.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 2 + 2 = 5

2012-07-04 Thread Stefan Behnel
Paul Rubin, 04.07.2012 21:37:
> I just came across this (https://gist.github.com/1208215):
> 
> import sys
> import ctypes
> pyint_p = ctypes.POINTER(ctypes.c_byte*sys.getsizeof(5))
> five = ctypes.cast(id(5), pyint_p)
> print(2 + 2 == 5) # False
> five.contents[five.contents[:].index(5)] = 4
> print(2 + 2 == 5) # True (must be sufficiently large values of 2 there...)
> 
> Heh.  The author is apparently anonymous, I guess for good reason.

That's not portable, though. ;)

Stefan

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


import class from string

2012-07-04 Thread Mariano DAngelo
Hi I'm trying to create a class from a string 
This is my code, but is not working

'myshop.models.base'
module_name, class_name = model.rsplit(".", 1)
module = importlib.import_module(module_name)
class_ = getattr(module, class_name)()


Anyone know what I'm doing wrong or another way?

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


Re: 2 + 2 = 5

2012-07-04 Thread Michael Ross

Am 04.07.2012, 21:37 Uhr, schrieb Paul Rubin :


I just came across this (https://gist.github.com/1208215):

import sys
import ctypes
pyint_p = ctypes.POINTER(ctypes.c_byte*sys.getsizeof(5))
five = ctypes.cast(id(5), pyint_p)
print(2 + 2 == 5) # False
five.contents[five.contents[:].index(5)] = 4
print(2 + 2 == 5) # True (must be sufficiently large values of 2  
there...)


Heh.  The author is apparently anonymous, I guess for good reason.



Neat.

Playing with it, i'm wondering:


This:

import sys
import ctypes
pyint_p = ctypes.POINTER(ctypes.c_byte*sys.getsizeof(5))
five = ctypes.cast(id(5), pyint_p)
five.contents[five.contents[:].index(5)] = 4

print ( 2 + 2 == 5 )
print 5
print 5 - 2

put into a script and run prints:

True
4
3

while entered at the python prompt it prints:

True
4
2

??


Regards,
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: 2 + 2 = 5

2012-07-04 Thread Mark Lawrence

On 04/07/2012 20:37, Paul Rubin wrote:

I just came across this (https://gist.github.com/1208215):

 import sys
 import ctypes
 pyint_p = ctypes.POINTER(ctypes.c_byte*sys.getsizeof(5))
 five = ctypes.cast(id(5), pyint_p)
 print(2 + 2 == 5) # False
 five.contents[five.contents[:].index(5)] = 4
 print(2 + 2 == 5) # True (must be sufficiently large values of 2 there...)

Heh.  The author is apparently anonymous, I guess for good reason.



The author got confused trying to switch from imperial to metric numbers 
or vice versa?


--
Cheers.

Mark Lawrence.



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


Re: Using a CMS for small site?

2012-07-04 Thread Gilles
On Wed, 04 Jul 2012 11:21:42 -0400, Roy Smith  wrote:
>This is really getting quite far afield for a Python group.  There are 
>better forums for these kinds of questions.

Probably. I'll keep that in mind while checking Python web frameworks.
Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 2 + 2 = 5

2012-07-04 Thread Thomas Jollans
On 07/04/2012 09:37 PM, Paul Rubin wrote:
> I just came across this (https://gist.github.com/1208215):
> 
> import sys
> import ctypes
> pyint_p = ctypes.POINTER(ctypes.c_byte*sys.getsizeof(5))
> five = ctypes.cast(id(5), pyint_p)
> print(2 + 2 == 5) # False
> five.contents[five.contents[:].index(5)] = 4
> print(2 + 2 == 5) # True (must be sufficiently large values of 2 there...)
> 
> Heh.  The author is apparently anonymous, I guess for good reason.
> 

I'm reminded of the swap(a,b) function I wrote a couple of years back.

http://blog.jollybox.de/archives/62-python-swap
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: locals().update(...)

2012-07-04 Thread Dave Angel
On 07/04/2012 07:56 AM, eis...@gmail.com wrote:
> I expected this to work:
>
>
> def f(**args):
> locals().update(args)
> print locals()
> print a
>
> d=dict(a=1)
>
> f(**d)
>
> but:
>> global name 'a' is not defined
> Where is my mistake?

Chris has given you the place where it's documented that it generally
won't work.  I'll try to explain why, at least for local variables
inside functions, and for CPython implementation.

The generated byte code for a function does *not* look up each symbol by
name during execution.  The compiler builds  a list of known local
symbol names, and gives them each an index (a small positive integer). 
At run time that list is fixed in size and meaning;  no new locals can
be added.  The locals() function just creates a dictionary that
approximates what the semantics of the symbols are.  But changes to that
dictionary have no effect on the running function.

That's one reason that copying a global value to a local symbol inside a
function can make that function run faster.  Globals always require a
dictionary lookup, while function locals are just an integer offset away.


> This does work:
>
> globals().update({'a':1})
>
> print a
>
> 1
>
> -E
>

As i said above, the rules are different for globals, and they are even
if you use locals() to access them.  However, i'd consider it prudent
never to assume you can write to the dictionary constructed by either
the locals() or the globals() functions.

-- 

DaveA

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


Re: import class from string

2012-07-04 Thread Steven D'Aprano
On Wed, 04 Jul 2012 13:27:29 -0700, Mariano DAngelo wrote:

> Hi I'm trying to create a class from a string This is my code, but
> is not working
> 
> 'myshop.models.base'
> module_name, class_name = model.rsplit(".", 1) 
> module = importlib.import_module(module_name) 
> class_ = getattr(module, class_name)()
> 
> 
> Anyone know what I'm doing wrong

What version of Python are you using?

What result do you expect?

What result do you actually get?

When asking for help, please take the time to create a short, self-
contained, correct example that anyone can actually run:

http://sscce.org/

In the above, you have a bare string that does nothing; a name "model" 
that is undefined; and what looks like a module that isn't imported 
(importlib). We have no idea of what problem *you* see, because we can't 
run your code and you don't show us the error.

But the general idea is correct, at least in Python 3.2:

import importlib
model = 'unittest.suite.BaseTestSuite'
module_name, class_name = model.rsplit(".", 1)
module = importlib.import_module(module_name)
class_ = getattr(module, class_name)

At the end of which, class_ is the expected BaseTestSuite class.


I suspect that your error is that after you get the class object using 
getattr, you then *call* the class object but give no arguments, and the 
class requires arguments.

You say:
class_ = getattr(module, class_name)()  # note the extra () brackets

I say:
class_ = getattr(module, class_name)


Either that or you have a bug in your module and it can't be imported. Or 
you have misspelled the module name, or the class. Or forgotten to import 
importlib. Or are shadowing it with your own module. Who knows? Without 
seeing the error, I'm just guessing.



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


Re: import class from string

2012-07-04 Thread Thomas Jollans
On 07/04/2012 10:27 PM, Mariano DAngelo wrote:
> Hi I'm trying to create a class from a string 
> This is my code, but is not working

It would be helpful if you posted an error message. Then, we could know
what's actually going on.


> 'myshop.models.base'
> module_name, class_name = model.rsplit(".", 1)
> module = importlib.import_module(module_name)
> class_ = getattr(module, class_name)()

..^^

These brackets may be causing problems?

In principle, you're doing the right thing. This works for me:

Python 3.2.3 (default, May  3 2012, 15:51:42)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import importlib
>>> objname = 'os.path.join'
>>> module_name, member_name = objname.rsplit('.', 1)
>>> module = importlib.import_module(module_name)
>>> member = getattr(module, member_name)
>>> member

>>>

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


Re: locals().update(...)

2012-07-04 Thread Steven D'Aprano
On Wed, 04 Jul 2012 18:48:08 -0400, Dave Angel wrote:

> As i said above, the rules are different for globals, and they are even
> if you use locals() to access them.  However, i'd consider it prudent
> never to assume you can write to the dictionary constructed by either
> the locals() or the globals() functions.

globals() is implicitly documented as being writable: "This is always the 
dictionary of the current module..." -- unless you have a module with a 
read-only dict, that is writable.

http://docs.python.org/release/3.2/library/functions.html#globals

There are tricks to getting read-only namespaces, but you can 
legitimately expect to write to globals().


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


Discussion on some Code Issues

2012-07-04 Thread subhabangalore
Dear Group,

I am Sri Subhabrata Banerjee trying to write from Gurgaon, India to discuss 
some coding issues. If any one of this learned room can shower some light I 
would be helpful enough. 

I got to code a bunch of documents  which are combined together. 
Like, 

1)A Mumbai-bound aircraft with 99 passengers on board was struck by lightning 
on Tuesday evening that led to complete communication failure in mid-air and 
forced the pilot to make an emergency landing.
2) The discovery of a new sub-atomic particle that is key to understanding how 
the universe is built has an intrinsic Indian connection.
3) A bomb explosion outside a shopping mall here on Tuesday left no one 
injured, but Nigerian authorities put security agencies on high alert fearing 
more such attacks in the city.

The task is to separate the documents on the fly and to parse each of the 
documents with a definite set of rules. 

Now, the way I am processing is: 
I am clubbing all the documents together, as,

A Mumbai-bound aircraft with 99 passengers on board was struck by lightning on 
Tuesday evening that led to complete communication failure in mid-air and 
forced the pilot to make an emergency landing.The discovery of a new sub-atomic 
particle that is key to understanding how the universe is built has an 
intrinsic Indian connection. A bomb explosion outside a shopping mall here on 
Tuesday left no one injured, but Nigerian authorities put security agencies on 
high alert fearing more such attacks in the city.

But they are separated by a tag set, like, 
A Mumbai-bound aircraft with 99 passengers on board was struck by lightning on 
Tuesday evening that led to complete communication failure in mid-air and 
forced the pilot to make an emergency landing.$
The discovery of a new sub-atomic particle that is key to understanding how the 
universe is built has an intrinsic Indian connection.$
A bomb explosion outside a shopping mall here on Tuesday left no one injured, 
but Nigerian authorities put security agencies on high alert fearing more such 
attacks in the city.

To detect the document boundaries, I am splitting them into a bag of words and 
using a simple for loop as, 
for i in range(len(bag_words)):
if bag_words[i]=="$":
print (bag_words[i],i)

There is no issue. I am segmenting it nicely. I am using annotated corpus so 
applying parse rules. 

The confusion comes next, 

As per my problem statement the size of the file (of documents combined 
together) won’t increase on the fly. So, just to support all kinds of 
combinations I am appending in a list the “I” values, taking its length, and 
using slice. Works perfect. Question is, is there a smarter way to achieve 
this, and a curious question if the documents are on the fly with no 
preprocessed tag set like “$” how may I do it? From a bunch without EOF isn’t 
it a classification problem? 

There is no question on parsing it seems I am achieving it independent of 
length of the document. 

If any one in the group can suggest how I am dealing with the problem and which 
portions should be improved and how?

Thanking You in Advance,

Best Regards,
Subhabrata Banerjee. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Discussion on some Code Issues

2012-07-04 Thread Steven D'Aprano
On Wed, 04 Jul 2012 16:21:46 -0700, subhabangalore wrote:

[...]
> I got to code a bunch of documents  which are combined together.
[...]
> The task is to separate the documents on the fly and to parse each of
> the documents with a definite set of rules.
> 
> Now, the way I am processing is:
> I am clubbing all the documents together, as,
[...]
> But they are separated by a tag set
[...] 
> To detect the document boundaries,

Let me see if I understand your problem.

You have a bunch of documents. You stick them all together into one 
enormous lump. And then you try to detect the boundaries between one file 
and the next within the enormous lump.

Why not just process each file separately? A simple for loop over the 
list of files, before consolidating them into one giant file, will avoid 
all the difficulty of trying to detect boundaries within files.

Instead of:

merge(output_filename,  list_of_files)
for word in parse(output_filename):
if boundary_detected: do_something()
process(word)

Do this instead:

for filename in  list_of_files:
do_something()
for word in parse(filename):
process(word)


> I am splitting them into a bag of
> words and using a simple for loop as, 
> for i in range(len(bag_words)):
> if bag_words[i]=="$":
> print (bag_words[i],i)


What happens if a file already has a $ in it?


> There is no issue. I am segmenting it nicely. I am using annotated
> corpus so applying parse rules.
> 
> The confusion comes next,
> 
> As per my problem statement the size of the file (of documents combined
> together) won’t increase on the fly. So, just to support all kinds of
> combinations I am appending in a list the “I” values, taking its length,
> and using slice. Works perfect.

I don't understand this. What sort of combinations do you think you need 
to support? What are "I" values, and why are they important?



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


Re: Discussion on some Code Issues

2012-07-04 Thread Rick Johnson
On Jul 4, 6:21 pm, subhabangal...@gmail.com wrote:
> [...]
> To detect the document boundaries, I am splitting them into a bag
> of words and using a simple for loop as,
>
> for i in range(len(bag_words)):
>         if bag_words[i]=="$":
>             print (bag_words[i],i)

Ignoring that you are attacking the problem incorrectly: that is very
poor method of splitting a string since especially the Python gods
have given you *power* over string objects. But you are going to have
an even greater problem if the string contains a "$" char that you DID
NOT insert :-O. You'd be wise to use a sep that is not likely to be in
the file data. For example: "" or "". But even that
approach is naive! Why not streamline the entire process and pass a
list of file paths to a custom parser object instead?

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


Help using Tix and tix.balloon in tkinter.ttk Gui on Py 3.2.3, Mac OS X 10.6.8

2012-07-04 Thread Greg Edwards
Hi,

I'm trying to get Tix installed and working, in order to use Tix.balloon in
the first instance.

I'm using Python 3.2.3 on Mac OS X 10.6.8, installed from direct package
download from Python.org. Have also installed Py 2.7.3, and the native Mac
Py 2.6.1 and 2.5.4 are all working fine as well and not tromping on each
other.

Building a variety of Gui's under 2.7.3 and 3.2.3 with tkinter, ttk and all
going well. I'm recreating a pile of Gui's I have had for years under plain
Tcl/Tk (on Linux and Irix).

I can't get Tix working at all, doesn't seem to be supplied with any of the
Python dists. Example:

~/lang/python/tkinter/devpanel $ py3
Python 3.2.3 (v3.2.3:3d0686d90f55, Apr 10 2012, 11:25:50)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
~/.pythonstartup
>>> import tkinter
>>> import tkinter.ttk
>>> import tkinter.tix
>>> root = tkinter.tix.Tk()
Traceback (most recent call last):
  File "", line 1, in 
  File
"/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/tkinter/tix.py",
line 225, in __init__
self.tk.eval('package require Tix')
_tkinter.TclError: can't find package Tix

My Python is still elementary, I may be importing and invoking Tix badly.
I've searched the Python, Tkinter, Tix sites for a few hours, searched my
Mac for tixlib files, no luck. Looks like you can build Tix from source and
install, but web posts indicate this is very hard and I don't see any
useful traffic on that in the last 2 or 3 years, never a good sign.

Any pointers appreciated ! Hope I don't get flamed, I see this group has
some epic flame wars.

Cheers,

-- 
Greg Edwards,
Port Jackson Bioinformatics
gedwar...@gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using a CMS for small site?

2012-07-04 Thread alex23
On Jul 5, 1:21 am, Roy Smith  wrote:
> If the content is truly never going to change, there's nothing to
> prevent you from creating some static html files with your favorite text
> editor.
>
> This is really getting quite far afield for a Python group.  There are
> better forums for these kinds of questions.

Not necessarily! There are several static site generators written in
Python :)

One that I see being updating a lot is Nikola: http://nikola.ralsina.com.ar/
-- 
http://mail.python.org/mailman/listinfo/python-list


simpler increment of time values?

2012-07-04 Thread Vlastimil Brom
Hi all,
I'd like to ask about the possibilities to do some basic manipulation
on timestamps - such as incrementing a given time (hour.minute -
string) by some minutes.
Very basic notion of "time" is assumed, i.e. dateless,
timezone-unaware, DST-less etc.
I first thought, it would be possible to just add a timedelta to a
time object, but, it doesn't seem to be the case.

The code I came up with (using time and datetime modules) seems rather
convoluted and I would like to ask about some possible more
straightforward alternatives I missed.
The equivalent function (lacking validation) without the (date)time
libraries seems simple enough (for this limited and individual task).
Although it is probably mostly throw-away code, which seems to do what
I need, I'd be interested in better/more elegant... solutions.

# # #
import time
import datetime
import re

print re.sub(r"^0","", (datetime.datetime(*list(time.strptime("8.45",
"%H.%M"))[:6]) + datetime.timedelta(minutes=30)).strftime("%H.%M"))
# 9.15

# # # # # # # # #

def add_minutes(hour_min_str, separator=".", minutes_to_add=0):
h, m = [int(s) for s in hour_min_str.split(separator)]
sum_minutes = h * 60 + m + minutes_to_add
h, m = divmod(sum_minutes, 60)
h = h % 24
return "%s%s%s" % (h, separator, m)

print add_minutes(hour_min_str="8.45", separator='.', minutes_to_add=30)
# 9.15

# # # # # # # # #

Is it true, that timedelta cannot be used with dateless time values?
(Is there some other possibility than the current one, where strptime
actually infers 1. 1. 1900?)
Is there some simpler way to adapt the incompatible output of strptime
as the input of datetime?
Is it possible to get one-digit hours formatted without the leading zero?

Thanks in advance for any suggestions or remarks;
   regards,
  Vlastimil Brom
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 2 + 2 = 5

2012-07-04 Thread Evan Driscoll
On 7/4/2012 14:37, Paul Rubin wrote:
> I just came across this (https://gist.github.com/1208215):
> 
> import sys
> import ctypes
> pyint_p = ctypes.POINTER(ctypes.c_byte*sys.getsizeof(5))
> five = ctypes.cast(id(5), pyint_p)
> print(2 + 2 == 5) # False
> five.contents[five.contents[:].index(5)] = 4
> print(2 + 2 == 5) # True (must be sufficiently large values of 2 there...)
> 
> Heh.  The author is apparently anonymous, I guess for good reason.

Probably just nostalgic for old Fortran, which, supposedly, allowed you
to change the values of literals by passing them to a function by
reference and then modifying the value.

Evan




signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simpler increment of time values?

2012-07-04 Thread Chris Angelico
On Thu, Jul 5, 2012 at 10:29 AM, Vlastimil Brom
 wrote:
> I'd like to ask about the possibilities to do some basic manipulation
> on timestamps - such as incrementing a given time (hour.minute -
> string) by some minutes.
> Very basic notion of "time" is assumed, i.e. dateless,
> timezone-unaware, DST-less etc.

My first suggestion would be to work with Unix times (that is, store
your time as "seconds since 1970", also called a time_t). That's
forced to be on UTC (but ignoring leap seconds) so you don't have to
worry about timezones or DST, and incrementing by X minutes is simply
adding X*60 to it. It makes your job a lot easier!

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


Re: 2 + 2 = 5

2012-07-04 Thread Cameron Simpson
On 04Jul2012 19:39, Evan Driscoll  wrote:
| On 7/4/2012 14:37, Paul Rubin wrote:
| > I just came across this (https://gist.github.com/1208215):
| > 
| > import sys
| > import ctypes
| > pyint_p = ctypes.POINTER(ctypes.c_byte*sys.getsizeof(5))
| > five = ctypes.cast(id(5), pyint_p)
| > print(2 + 2 == 5) # False
| > five.contents[five.contents[:].index(5)] = 4
| > print(2 + 2 == 5) # True (must be sufficiently large values of 2 
there...)
| > 
| > Heh.  The author is apparently anonymous, I guess for good reason.
| 
| Probably just nostalgic for old Fortran, which, supposedly, allowed you
| to change the values of literals by passing them to a function by
| reference and then modifying the value.

Yeah, I was thinking that too. Because all parameters were pass-by-reference
in early fortran IIRC. You could, for example, set pi to 3.
-- 
Cameron Simpson 

If I have seen farther than others, it is because I was standing on the
shoulders of giants.- Isaac Newton

If I have not seen as far as others, it is because giants were standing on my
shoulders.  - Hal Abelson

In computer science, we stand on each other's feet. - Brian K. Reed
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simpler increment of time values?

2012-07-04 Thread Mark Lawrence

On 05/07/2012 01:29, Vlastimil Brom wrote:

Hi all,
I'd like to ask about the possibilities to do some basic manipulation
on timestamps - such as incrementing a given time (hour.minute -
string) by some minutes.
Very basic notion of "time" is assumed, i.e. dateless,
timezone-unaware, DST-less etc.
I first thought, it would be possible to just add a timedelta to a
time object, but, it doesn't seem to be the case.

The code I came up with (using time and datetime modules) seems rather
convoluted and I would like to ask about some possible more
straightforward alternatives I missed.
The equivalent function (lacking validation) without the (date)time
libraries seems simple enough (for this limited and individual task).
Although it is probably mostly throw-away code, which seems to do what
I need, I'd be interested in better/more elegant... solutions.

# # #
import time
import datetime
import re

print re.sub(r"^0","", (datetime.datetime(*list(time.strptime("8.45",
"%H.%M"))[:6]) + datetime.timedelta(minutes=30)).strftime("%H.%M"))
# 9.15

# # # # # # # # #

def add_minutes(hour_min_str, separator=".", minutes_to_add=0):
 h, m = [int(s) for s in hour_min_str.split(separator)]
 sum_minutes = h * 60 + m + minutes_to_add
 h, m = divmod(sum_minutes, 60)
 h = h % 24
 return "%s%s%s" % (h, separator, m)

print add_minutes(hour_min_str="8.45", separator='.', minutes_to_add=30)
# 9.15

# # # # # # # # #

Is it true, that timedelta cannot be used with dateless time values?
(Is there some other possibility than the current one, where strptime
actually infers 1. 1. 1900?)
Is there some simpler way to adapt the incompatible output of strptime
as the input of datetime?
Is it possible to get one-digit hours formatted without the leading zero?

Thanks in advance for any suggestions or remarks;
regards,
   Vlastimil Brom



from dateutil.relativedelta import relativedelta should simplify things 
for you


google and ye shall find :)

--
Cheers.

Mark Lawrence.



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


how to interact with Windows cmd?

2012-07-04 Thread self.python
what I want to do is
1.open cmd
2.waiting for user's typing
3.when I type "dir"
4.print the result of "dir"
5.then I type some other commands, printing the result until I type
'exit'

I used
p=subprocess.Popen('cmd',stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
p=communicate('dir')

it shows the first result but the problem is
1. it's too long so the cmd split the result with "more?", so result
is not perfect
2. after this, I typed like "cd .." but I/O is already closed so I
can't do another things..

Is there any good way?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Discussion on some Code Issues

2012-07-04 Thread subhabangalore
On Thursday, July 5, 2012 4:51:46 AM UTC+5:30, (unknown) wrote:
> Dear Group,
> 
> I am Sri Subhabrata Banerjee trying to write from Gurgaon, India to discuss 
> some coding issues. If any one of this learned room can shower some light I 
> would be helpful enough. 
> 
> I got to code a bunch of documents  which are combined together. 
> Like, 
> 
> 1)A Mumbai-bound aircraft with 99 passengers on board was struck by lightning 
> on Tuesday evening that led to complete communication failure in mid-air and 
> forced the pilot to make an emergency landing.
> 2) The discovery of a new sub-atomic particle that is key to understanding 
> how the universe is built has an intrinsic Indian connection.
> 3) A bomb explosion outside a shopping mall here on Tuesday left no one 
> injured, but Nigerian authorities put security agencies on high alert fearing 
> more such attacks in the city.
> 
> The task is to separate the documents on the fly and to parse each of the 
> documents with a definite set of rules. 
> 
> Now, the way I am processing is: 
> I am clubbing all the documents together, as,
> 
> A Mumbai-bound aircraft with 99 passengers on board was struck by lightning 
> on Tuesday evening that led to complete communication failure in mid-air and 
> forced the pilot to make an emergency landing.The discovery of a new 
> sub-atomic particle that is key to understanding how the universe is built 
> has an intrinsic Indian connection. A bomb explosion outside a shopping mall 
> here on Tuesday left no one injured, but Nigerian authorities put security 
> agencies on high alert fearing more such attacks in the city.
> 
> But they are separated by a tag set, like, 
> A Mumbai-bound aircraft with 99 passengers on board was struck by lightning 
> on Tuesday evening that led to complete communication failure in mid-air and 
> forced the pilot to make an emergency landing.$
> The discovery of a new sub-atomic particle that is key to understanding how 
> the universe is built has an intrinsic Indian connection.$
> A bomb explosion outside a shopping mall here on Tuesday left no one injured, 
> but Nigerian authorities put security agencies on high alert fearing more 
> such attacks in the city.
> 
> To detect the document boundaries, I am splitting them into a bag of words 
> and using a simple for loop as, 
> for i in range(len(bag_words)):
> if bag_words[i]=="$":
> print (bag_words[i],i)
> 
> There is no issue. I am segmenting it nicely. I am using annotated corpus so 
> applying parse rules. 
> 
> The confusion comes next, 
> 
> As per my problem statement the size of the file (of documents combined 
> together) won’t increase on the fly. So, just to support all kinds of 
> combinations I am appending in a list the “I” values, taking its length, and 
> using slice. Works perfect. Question is, is there a smarter way to achieve 
> this, and a curious question if the documents are on the fly with no 
> preprocessed tag set like “$” how may I do it? From a bunch without EOF isn’t 
> it a classification problem? 
> 
> There is no question on parsing it seems I am achieving it independent of 
> length of the document. 
> 
> If any one in the group can suggest how I am dealing with the problem and 
> which portions should be improved and how?
> 
> Thanking You in Advance,
> 
> Best Regards,
> Subhabrata Banerjee.


Hi Steven, It is nice to see your post. They are nice and I learnt so many 
things from you. "I" is for index of the loop.
Now my clarification I thought to do "import os" and process files in a loop 
but that is not my problem statement. I have to make a big lump of text and 
detect one chunk. Looping over the line number of file I am not using because I 
may not be able to take the slices-this I need. I thought to give re.findall a 
try but that is not giving me the slices. Slice spreads here. The power issue 
of string! I would definitely give it a try. Happy Day Ahead Regards, 
Subhabrata Banerjee.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 2 + 2 = 5

2012-07-04 Thread Terry Reedy

On 7/4/2012 4:37 PM, Michael Ross wrote:

Am 04.07.2012, 21:37 Uhr, schrieb Paul Rubin :


I just came across this (https://gist.github.com/1208215):

import sys
import ctypes
pyint_p = ctypes.POINTER(ctypes.c_byte*sys.getsizeof(5))
five = ctypes.cast(id(5), pyint_p)
print(2 + 2 == 5) # False
five.contents[five.contents[:].index(5)] = 4
print(2 + 2 == 5) # True (must be sufficiently large values of 2
there...)

Heh.  The author is apparently anonymous, I guess for good reason.



Neat.

Playing with it, i'm wondering:


This:

 import sys
 import ctypes
 pyint_p = ctypes.POINTER(ctypes.c_byte*sys.getsizeof(5))
 five = ctypes.cast(id(5), pyint_p)
 five.contents[five.contents[:].index(5)] = 4

 print ( 2 + 2 == 5 )
 print 5
 print 5 - 2

put into a script and run prints:

 True
 4
 3


The compile-time optimizer computed the contant 5-2 in C.


while entered at the python prompt it prints:

 True
 4
 2


It must not run for interactive input with the undisclosed version you 
are running.


If I run the script in 3.3 Idle, I get the same output you got. If I 
then enter '5-2' interactively, I still get 3. Maybe the constant folder 
is always on now.


--
Terry Jan Reedy



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


Help: PYMALLOC_DBUG and PIL

2012-07-04 Thread tom z
Hi~ all,
I encounter a odd problem, when i compile Python with PYMALLOC_DEBUG, the
PIL module can't work fine, it always make core-dump like this

[Switching to Thread 182897301792 (LWP 16102)]
0x004df264 in PyObject_Malloc (nbytes=64) at Objects/obmalloc.c:804
804 if ((pool->freeblock = *(block **)bp) != NULL) {
Current language:  auto; currently c
(gdb) bt
#0  0x004df264 in PyObject_Malloc (nbytes=64) at
Objects/obmalloc.c:804
#1  0x004dfb97 in _PyObject_DebugMallocApi (id=109 'm', nbytes=32)
at Objects/obmalloc.c:1461
#2  0x004dfd22 in _PyObject_DebugReallocApi (api=109 'm', p=0x0,
nbytes=32) at Objects/obmalloc.c:1523
#3  0x004dfac0 in _PyMem_DebugRealloc (p=0x0, nbytes=32) at
Objects/obmalloc.c:1416
#4  0x004c68d9 in list_resize (self=0x2a988409b8, newsize=1) at
Objects/listobject.c:62
#5  0x004c6f63 in app1 (self=0x2a988409b8, v=0x2a958cea90) at
Objects/listobject.c:277
#6  0x004c6fdd in PyList_Append (op=0x2a988409b8,
newitem=0x2a958cea90) at Objects/listobject.c:289
#7  0x00558c7f in symtable_add_def (st=0x2a99a4ca68,
name=0x2a958cea90, flag=4) at Python/symtable.c:910
#8  0x0055a953 in symtable_visit_params (st=0x2a99a4ca68,
args=0x924380, toplevel=1) at Python/symtable.c:1318
#9  0x0055aaa7 in symtable_visit_arguments (st=0x2a99a4ca68,
a=0x9243c8) at Python/symtable.c:1365
#10 0x00558f3d in symtable_visit_stmt (st=0x2a99a4ca68, s=0x9244d0)
at Python/symtable.c:1012
#11 0x0055919e in symtable_visit_stmt (st=0x2a99a4ca68, s=0x924500)
at Python/symtable.c:1029
#12 0x005574d7 in PySymtable_Build (mod=0x931798,
filename=0x7fbfffa2c0
"../lib/python2.7/site-packages/PIL/BmpImagePlugin.py",
future=0x2a9883aae0) at Python/symtable.c:240
#13 0x00531f14 in PyAST_Compile (mod=0x931798,
filename=0x7fbfffa2c0
"../lib/python2.7/site-packages/PIL/BmpImagePlugin.py", flags=0x7fbfff9020,
arena=0x8eedd0) at Python/compile.c:282
#14 0x00545967 in parse_source_module (
pathname=0x7fbfffa2c0
"../lib/python2.7/site-packages/PIL/BmpImagePlugin.py", fp=0x91a060) at
Python/import.c:843
#15 0x00545e75 in load_source_module (name=0x7fbfffb3e0
"PIL.BmpImagePlugin",
pathname=0x7fbfffa2c0
"../lib/python2.7/site-packages/PIL/BmpImagePlugin.py", fp=0x91a060) at
Python/import.c:1027

i've no idea about this, someone could get me help~

---
thanks a lot
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simpler increment of time values?

2012-07-04 Thread Jason Friedman
> Hi all,
> I'd like to ask about the possibilities to do some basic manipulation
> on timestamps - such as incrementing a given time (hour.minute -
> string) by some minutes.
> Very basic notion of "time" is assumed, i.e. dateless,
> timezone-unaware, DST-less etc.
> I first thought, it would be possible to just add a timedelta to a
> time object, but, it doesn't seem to be the case.
>
> The code I came up with (using time and datetime modules) seems rather
> convoluted and I would like to ask about some possible more
> straightforward alternatives I missed.
> The equivalent function (lacking validation) without the (date)time
> libraries seems simple enough (for this limited and individual task).
> Although it is probably mostly throw-away code, which seems to do what
> I need, I'd be interested in better/more elegant... solutions.

I have some thoughts on a solution, but first, what is 12:45 plus 12
hours?  What is 12:45 minus 13 hours?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simpler increment of time values?

2012-07-04 Thread Devin Jeanpierre
On Thu, Jul 5, 2012 at 12:57 AM, Jason Friedman  wrote:
> I have some thoughts on a solution, but first, what is 12:45 plus 12
> hours?  What is 12:45 minus 13 hours?

Is there anything unusual that can happen for a notion of time that is
dateless, timezone-unaware, and DST-free?

I would imagine that under these constraints the answers are always
0:45 and 23:45 respectively. Although I guess it doesn't hurt to check.

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


Re: 2 + 2 = 5

2012-07-04 Thread Steven D'Aprano
On Wed, 04 Jul 2012 23:38:17 -0400, Terry Reedy wrote:

> If I run the script in 3.3 Idle, I get the same output you got. If I
> then enter '5-2' interactively, I still get 3. Maybe the constant folder
> is always on now.

Yes, I believe constant folding is always on, since Python 2.4 if I 
remember correctly. Somebody who cares more than me can possibly check 
the "What's New" documents :)


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