How to use "while" within the command in -c option of python?

2012-10-12 Thread Herman
 python -c "import os; while True: print('hello')"
 File "", line 1
 import os; while True: print('hello')
  ^
SyntaxError: invalid syntax
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to use "while" within the command in -c option of python?

2012-10-12 Thread Herman
I was just trying to do in a shell to quickly monitor a file. Imagine
instead of printing hello, it is "os.system("cat somefile")", etc.
Look like it works if i press an enter after the "import xxx". Thanks.

On Fri, Oct 12, 2012 at 5:29 PM, Dave Angel  wrote:
> On 10/12/2012 06:51 PM, Herman wrote:
>>  python -c "import os; while True: print('hello')"
>>  File "", line 1
>>  import os; while True: print('hello')
>>   ^
>> SyntaxError: invalid syntax
> See the recent thread:
>"for-loop on cmd-line"
>
> The problem has nothing to do with the command line, it's caused by
> trying to use a keyword 'while' somewhere other than the beginning of
> the statement.
>
> I'll ask you the same question I had:  why do you bother?  What's wrong
> with making a separate file for the source code?
>
> But as for solutions, first question is what OS you're running on.  If
> not Windows, you can probably use \n at appropriate points.
>
> If that's not good enough, what about simply running the script instead
> of a batch file?
>
> If that's not good enough, how about merging the two languages, with a
> trick like starting the python code with rem = """  followed by the
> shell script?
>
> There are many others, but we cannot choose without knowing your other
> constraints.
>
>
>
> --
>
> DaveA
>
-- 
http://mail.python.org/mailman/listinfo/python-list


logging with logging.config.fileConfig

2012-02-19 Thread Herman
I tried to use file to config my logger and I got a weird situation
that each message is outputted twice...
Here is my scenario:
python: 2.6

file abc_logging.conf:

[loggers]
keys=root,abc

[handlers]
keys=consoleHandler

[formatters]
keys=detailFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_abc]
level=DEBUG
handlers=consoleHandler
qualname=abc

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=detailFormatter
args=(sys.stdout,)

[formatter_detailFormatter]
format=%(asctime)-15s %(levelname)s: %(filename)s:%(lineno)s: %(message)s
datefmt=%Y-%m-%d %H:%M:%S


Then in my program, i config the file with this:

SCRIPT_DIR = os.path.dirname(os.path.realpath(sys.argv[0]))
logging.config.fileConfig(SCRIPT_DIR + os.path.sep + 'abc_logging.conf')
LOG = logging.getLogger('abc')


I tried to print out the logger handlers with this:
 print("*"*10)
 print("number of handlers: %s" % len(LOG.handlers))
 print(LOG.handlers)
 LOG.debug(sql)

But there is no suspicious behavior:

**
number of handlers: 1
[]
2012-02-19 12:21:56 DEBUG: abc.py:88: SELECT ...
2012-02-19 12:21:56 DEBUG: abc.py:88: SELECT ...
-- 
http://mail.python.org/mailman/listinfo/python-list


How to break long method name into more than one line?

2012-03-11 Thread Herman
I am trying to stick to the rule described in the TDD book that, each
test method name consists of the method name to be tested, inputs and
the expected outputs. It takes up a lot of space and my company has a
rule of limiting 79 characters (or 80) per line. I found that
def abcdeef\
dddaaa(self):
pass

does not work, but
def \
abcsajfoijfiawifoiwejfoi(self):
pass

works. Is this the only way to do it?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to break long method name into more than one line?

2012-03-14 Thread Herman
I followed the rule because it was a very good advice. For example,
def test_plus_1Plus1_2(self):
If this test fails, you immediately know that it's testing the "plus"
method, with 1  and 1 as the arguments, and expect to return 2.
Sticking this rule also means your test cases are small enough, so you
clearly know what you are testing on. Most of the time, the method
name is what you first see when your test fails. Another alternative
is to put meaningful string in each of the assert, which is probably
not practical. You are right, only people who really follow the TDD
method know the good things about it. This naming rule served me very
well.

Tests method should have meaningful name, and the advice by the book
is a meaningful one. I said it's the TDD book because I forgot the
exact title. It's actually called Test Driven: TDD and Acceptance TDD
for Java Developers. I thought it should be popular enough that most
people learned TDD may have heard it also used this naming advice, but
look like i was wrong.

> *The* TDD book? There's only one? Surely not.
>
> That rule sounds utterly impractical. I can't think of anything to
> recommend it. Like any other function, method or class, tests should have
> meaningful names, but reading the name alone should not necessarily tell
> you *everything* about the function.
>
> We have "len", not "len_sequence_or_mapping_int", and similarly it is
> perfectly reasonable to have "test_len_empty" rather than
> "test_len_emptylist_emptystr_emptyunicode_emptydict_emptyset_emptytuple_zero".
>
> I expect that naming rule was invented by either people who have heard of
> test driven development, but never actually done it, or by people so
> anally-retentive that if they make seven short car trips over an hour,
> they check the tyre pressure, oil and water seven times because "the
> manual says to check before *every* trip".
>
> No offence.
>
> My advice is to moderate the naming convention of your tests with a good
> dose of common sense and aim for names which are readable rather than
> names that contain everything including the kitchen sink. Imagine you are
> in a technical meeting with some of your fellow programmers, and need to
> ask for help with a failing test. Imagine saying the name of the test
> aloud in a sentence. Does it add clarity to the discussion, or obfuscate
> it?
>
> People's short term memory can only hold so much (allegedly "seven plus
> or minus two"), and if the name itself hits that limit, you leave nothing
> left for the rest of the sentence.
>
> http://en.wikipedia.org/wiki/The_Magical_Number_Seven,_Plus_or_Minus_Two
>
> Names should be practically, rather than conforming to some naming rule
> that hurts readability and obfuscates the tests.
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


How to properly override the default factory of defaultdict?

2016-02-14 Thread Herman
I want to pass in the key to the default_factory of defaultdict and I found
that defaultdict somehow can intercept my call to dict.__getitem__(self,
key), so my class's __getitem__ have to catch a TypeError instead instead
of KeyError. The following class is my code:

class DefaultDictWithEnhancedFactory(defaultdict):
"""Just like the standard python collections.dict,
but the default_factory takes the missing key as argument.

Args:
default_factory: A function that takes the missing key as the
argument
and return a value for the missing key.
*a: arguments passing to the defaultdict constructor
**kw: keyword arguments passing to the defaultdict constructor
"""
def __init__(self, default_factory, *a, **kw):
defaultdict.__init__(self, default_factory, *a, **kw)

def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
# Normally, you would expect this line to be
# called for missing keys...
return self.default_factory(key)
except TypeError as ex:
# However, this is actually getting called
# because for some reason, defaultdict still
# intercepts the __getitem__ call and raises:
# TypeError: () takes exactly 1 argument (0 given)
# So we have to catch that instead...
if "lambda" in str(ex):
return self.default_factory(key)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to properly override the default factory of defaultdict?

2016-02-18 Thread Herman
d = dictutil.DefaultDictWithEnhancedFactory(lambda k: k)
self.assertEqual("apple", d['apple'])

From: Ben Finney 
>
> you are using the inheritance hierarchy but thwarting it by not using
> ‘super’. Instead::
>
> super().__init__(self, default_factory, *a, **kw)
>
> and::
>
> super().__getitem__(self, key)
> --
>  \   "Those who will not reason, are bigots, those who cannot, are |
>   `\fools, and those who dare not, are slaves." —“Lord” George |
> _o__)Gordon Noel Byron |
> Ben Finney

super does not work for defaultdict. I am using python 2.7. If I use
super(defaultdict, self).__init__(default_factory, *a, **kw), I get the
error:

super(defaultdict, self).__init__(default_factory, *a, **kw)
TypeError: 'function' object is not iterable

My use case is:
d = dictutil.DefaultDictWithEnhancedFactory(lambda k: k)
self.assertEqual("apple", d['apple'])


> From: Chris Angelico 
>
> Save yourself a lot of trouble, and just override __missing__:
>
> class DefaultDictWithEnhancedFactory(collections.defaultdict):
> def __missing__(self, key):
> return self.default_factory(key)
>
> ChrisA
>
This works! Thanks.

From: "Steven D'Aprano" 
> > I want to pass in the key to the default_factory of defaultdict
>
> Just use a regular dict and define __missing__:
>
> class MyDefaultDict(dict):
> def __missing__(self, key):
> return "We gotcha key %r right here!" % key
>
>
> If you want a per-instance __missing__, do something like this:
>
>
> class MyDefaultDict(dict):
> def __init__(self, factory):
> self._factory = factory
> def __missing__(self, key):
> return self._factory(self, key)
>
>
> d = MyDefaultDict(lambda self, key: ...)
>
>
> --
> Steve
>
Look like inheriting from defaultdict is easier. I don't even  have to
override the constructor as suggested by Chris Angelico above. Thanks.
-- 
https://mail.python.org/mailman/listinfo/python-list


What is the difference between "new Class()" and "Class()"?

2011-11-20 Thread Herman
What is so special about the "new" operator?
-- 
http://mail.python.org/mailman/listinfo/python-list


How can I wait for all the threads I spawn for 5 minutes

2007-08-31 Thread herman
Hi,

In my python program, I would to like to spwan 5 threads, for the them
for 5 minutes maximum and the continue. Here is my script:

threads = []

for j in range(5):
t = MyThread()
threads.append(t)

for t in threads:
t.join(60*5)
print "thread join\n"

# wait for 5 minutes for all the threads to complete ,
and
# then continue

But this code ends up waiting 5 minutes for **each** thread.  that is
not what I want. I just want to wait for 5 minutes for all threads.
how can I do that?

And after 5 minutes, i want to kill off all the threads I spawn
earlier, how can I do that in python.

Thank you for any help.

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


how can I find out the process ids with a process name

2007-09-02 Thread herman
Hi,

I would like to find out all the process id with the process name
'emacs'.

In the shell, i can do this:

$ ps -ef |grep emacs
root 20731  8690  0 12:37 pts/200:00:09 emacs-snapshot-gtk
root  25649 25357  0 13:55 pts/900:00:05 emacs-snapshot-gtk rtp.c
root  26319 23926  0 14:06 pts/700:00:04 emacs-snapshot-gtk
stressTestVideo.py
root  26985 1  0 14:15 ?00:00:01 /usr/bin/emacs-snapshot-
gtk
root 27472 21066  0 14:23 pts/500:00:00 grep emacs


and I can see the process id is 20731, 25649, etc, etc.

But now I would like to do the programmically in my python script.
I know I can use ' os.system(cmd)' to execute the command 'ps -ef |
grep emacs', but how
can I pipe the output of my 'ps -ef | grep emacs' to my python script
and then run a regression expression with it to get the process Ids?

Thank you.

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


install py2exe in vista

2008-06-21 Thread Herman
 I want to install it in
vista,
but i get this message in the process:
could not create... py2exe-py2.5

I press 'OK', then..
could not set key value python 2.5 py2exe-0.6.8

I press 'OK' again, then...
could not set key value
c:\Python25\Removepy2exe.exe" -u "c:\python25\py2exe-wininst.log

The installation goes on and do something, run some postinstall script.

I thought it should be ok, but i fail even creating a simple hello word exe.
I get this message after i run python setup.py install:
running install
running build
running install_egg_info
Writing c:\Python25\Lib\site-packages\UNKNOWN-0.0.0-py2.5-egg-info

No output is created.

Can I anyone help me with this?  
  
--
http://mail.python.org/mailman/listinfo/python-list

Re: Where is the correct round() method? Use math.ceil

2008-07-27 Thread Herman
>
> Where is the correct round() method?
> Hello,
>
> I need a round function that _always_ rounds to the higher integer if
> the argument is equidistant between two integers. In Python 3.0, this
> is not the advertised behavior of the built-in function round() as
> seen below:
>
> >>> round(0.5)
> 0
> >>> round(1.5)
> 2
> >>> round(2.5)
> 2
>
>
> I would think this is a common need, but I cannot find a function in
> the Python library to do it. I wrote my own, but did I miss such a
> method in my search of the Python library?
>
> Thanks


Use ceil in the math module:
import math
math.ceil(number)
--
http://mail.python.org/mailman/listinfo/python-list

Re: learning python

2013-05-06 Thread Michael Herman
realpython.com - just launched

On Sun, May 5, 2013 at 9:08 AM, leonardo selmi  wrote:
> hi guys
>
> i need to find a good book to learn python with exercises and solutions, any
> suggestions?
>
> thanks!
>
> best regards
>
> leonardo
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to: Setuptools

2013-05-28 Thread Michael Herman
I have a great video on how to setup Easy_Install via setuptools as
well as pip - http://www.youtube.com/watch?v=MIHYflJwyLk

On Mon, May 27, 2013 at 6:32 PM, ray  wrote:
>
> I would like to use easy_install, but can't figure out how to install it.
>
> I have 64-bit Python 2.7.5 on Windows 7.
>
> Following the instructions on https://pypi.python.org/pypi/setuptools, it
> says:
> Download ez_setup.py and run it; it will download the appropriate .egg
> file and install it for you. (Currently, the provided .exe installer does
> not support 64-bit versions of Python for Windows, due to a distutils
> installer compatibility issue
>
> Being new to Python, I don't know what it means to "run it".  I am not
> sure what I am looking at when I open it as the first line is "#!python".
>
> Looking down into the content of ez_setup.py, I find:
> 'setuptools-0.6c10-py2.6.egg':
> but there is no entry
> 'setuptools-0.6c10-py2.7.egg':
>
> Searching for it, I found a version at:
> https://pypi.python.org/packages/2.7/s/setuptools/
>
> This appeared to be a linux version, the first line is:
> #!/bin/sh
> and the content seems to be encoded.
>
> There is an exe at https://pypi.python.org/pypi/setuptools, but the
> instructions on the page state the .exe won't work for 64-bit installs.
>
> Ray
>
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2013-06-14 Thread Michael Herman
Hi there -

Yes, as others have said, this is not an easy project. That said, it
can be down. I'd use a combination of DataNitro, to connect with
Excel, and Scrapy, to easily scrap and crawl the sites. I'm adept at
both and would be happy to help you with this. Email me at
mich...@mherman.org for help.

Best,

Michael

On Thu, Jun 13, 2013 at 12:28 PM,  wrote:
>
> Hi, I'm new to Python. Would someone be able to write me and/or to show me
> how to write a simple program that:
>
> 1-follows a hyperlink from MS Excel to the internet (one of many links
> like this, http://www.zipdatamaps.com/76180, for e.g.) and then,
>
> 2-copies some data (a population number, e.g. 54195) and then,
>
> 3-pastes that data back into the same MS Excel spreadsheet, into the
> adjacent cell.
>
> ... and that’s it... row after row of hyperlinks all in one column...
>
> Please, please help me my wrist is starting to hurt a lot. You would have
> my greatest appreciation for your help!
>
> thank you, Buford
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Numerical representation

2011-03-04 Thread Jon Herman
Hello all,

I am new to the Python language and writing a Runge-Kutta-Fellberg 7(8)
integrator in Python, which requires an extreme numerical precision for my
particular application. Unfortunately, I can not seem to attain it.
The interesting part is if I take my exact code and translate it to Matlab
code (so I use the exact same process and numbers), I get a far superior
precision (the one I am expecting, in fact). This leads me to think I need
to call a certain command in my Python script in order to make sure no
truncation errors are building up over my integration.

Has anyone had similar problems? Is there a difference between how Matlab
and Python store numbers, and if so how do I make Python more accurate?

I know there is a lot of packages out there, but this in fact overwhelmed me
a little bit and seems to prevent me from finding the answer to my question,
so I'm hoping someone with more experience will be able to enlighten me!

Best regards,

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


Re: Numerical representation

2011-03-04 Thread Jon Herman
Actually, I import numpy in my code for array creation...in the
documentation I did not manage to find anything that would solve this
precision problem I mentioned however. If you're familiar with it, would you
happen to know what capability of numpy might solve my problem?



On Fri, Mar 4, 2011 at 4:49 PM, Santoso Wijaya wrote:

> Have you taken a look at numpy? [1] It was written for exactly this kind of
> usage.
>
> ~/santa
>
> [1] http://numpy.scipy.org/
>
>
> On Fri, Mar 4, 2011 at 2:32 PM, Jon Herman  wrote:
>
>> Hello all,
>>
>> I am new to the Python language and writing a Runge-Kutta-Fellberg 7(8)
>> integrator in Python, which requires an extreme numerical precision for my
>> particular application. Unfortunately, I can not seem to attain it.
>> The interesting part is if I take my exact code and translate it to Matlab
>> code (so I use the exact same process and numbers), I get a far superior
>> precision (the one I am expecting, in fact). This leads me to think I need
>> to call a certain command in my Python script in order to make sure no
>> truncation errors are building up over my integration.
>>
>> Has anyone had similar problems? Is there a difference between how Matlab
>> and Python store numbers, and if so how do I make Python more accurate?
>>
>> I know there is a lot of packages out there, but this in fact overwhelmed
>> me a little bit and seems to prevent me from finding the answer to my
>> question, so I'm hoping someone with more experience will be able to
>> enlighten me!
>>
>> Best regards,
>>
>> Jon
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Numerical representation

2011-03-07 Thread Jon Herman
I'm starting to run out of ideas of what to do...I've imported the true
division (I'm using Python 2.7) to make sure I wasn't accidentally using any
integers but the results remain identical, so it's not a division problem.
I've copied the loop I'm running below, is there any mathematical operation
I am making here that may have an accuracy problem? Thanks for any advice
you can give!

Xold=X
told=t

if abs(dt) > abs(tf-t):
dt = tf-t

k[:,0]=F(mu, Xold, told)

for n in range(1,13):
nn=n-1
Xtemp1=zeros(neq)
for j in range(nn):
Xtemp1 = Xtemp1 + b[n,j] * k[:,j]
Xtemp1
X=Xold+ dt * Xtemp1
t=told+a[n]*dt
k[:,n]=F(mu, X, 0)

Xtemp2=zeros(neq)
for l in range(13):
Xtemp2=Xtemp2+c[l]*k[:,l]



X=Xold + dt * Xtemp2
t=told+dt

Xstore=vstack((Xstore,X))
tstore=vstack((tstore,t))

if abs(tf-t)< 1e-14:
print('At tf')
    break




On Fri, Mar 4, 2011 at 6:46 PM, Jon Herman  wrote:

> Actually, I import numpy in my code for array creation...in the
> documentation I did not manage to find anything that would solve this
> precision problem I mentioned however. If you're familiar with it, would you
> happen to know what capability of numpy might solve my problem?
>
>
>
>
> On Fri, Mar 4, 2011 at 4:49 PM, Santoso Wijaya 
> wrote:
>
>> Have you taken a look at numpy? [1] It was written for exactly this kind
>> of usage.
>>
>> ~/santa
>>
>> [1] http://numpy.scipy.org/
>>
>>
>> On Fri, Mar 4, 2011 at 2:32 PM, Jon Herman  wrote:
>>
>>> Hello all,
>>>
>>> I am new to the Python language and writing a Runge-Kutta-Fellberg 7(8)
>>> integrator in Python, which requires an extreme numerical precision for my
>>> particular application. Unfortunately, I can not seem to attain it.
>>> The interesting part is if I take my exact code and translate it to
>>> Matlab code (so I use the exact same process and numbers), I get a far
>>> superior precision (the one I am expecting, in fact). This leads me to think
>>> I need to call a certain command in my Python script in order to make sure
>>> no truncation errors are building up over my integration.
>>>
>>> Has anyone had similar problems? Is there a difference between how Matlab
>>> and Python store numbers, and if so how do I make Python more accurate?
>>>
>>> I know there is a lot of packages out there, but this in fact overwhelmed
>>> me a little bit and seems to prevent me from finding the answer to my
>>> question, so I'm hoping someone with more experience will be able to
>>> enlighten me!
>>>
>>> Best regards,
>>>
>>> Jon
>>>
>>> --
>>> http://mail.python.org/mailman/listinfo/python-list
>>>
>>>
>>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Numerical representation

2011-03-07 Thread Jon Herman
Sorry Robert, I'd missed your post when I just made my last one. The output
I am getting in Python looks as follows:

array([  9.91565050e-01,   1.55680112e-05,  -1.53258602e-05,
-5.75847623e-05,  -9.64290960e-03,  -8.26333458e-08])

This is the final state vector, consisting of 6 states (postion and
velocity), although this isn't really relevant right now.

In MATLAB, using the same process for the RKF78, I get the following output:

Xend =

  Columns 1 through 3

9.915755153307796e-0013.592556838089922e-016
-1.523933534321440e-005

  Columns 4 through 6

   -7.175069559491303e-015   -9.624755221500220e-003
1.289789641929434e-017

As you can see, the results are close but there is a big difference in
precision (the 2nd, 4th and 6th entries are supposed to be zero under the
intial and final conditions I am running).
See also the post I just made where you can see the Python code I am using
(MATLAB code is identical but translated)

This is for a fixed timestep in both Python and Matlab. If I let the code
run with an identical method for timestep correction (based on a tolerance),
Python will use a timestep approximately 10^5 SMALLER than Matlab uses. So
I'm really sure it's not a representation issue, but actually a precision
issue.

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


Re: Numerical representation

2011-03-07 Thread Jon Herman
And for the sake of completeness, the derivative function I am calling from
my integrator (this is the 3 body problem in astrodynamics):

def F(mu, X, ti):

r1= pow((pow(X[0]+mu,2)+pow(X[1],2)+pow(X[2],2)),0.5)
r2= pow((pow(X[0]+mu-1,2)+pow(X[1],2)+pow(X[2],2)),0.5)

Ax= X[0]+2*X[4]-(1-mu)*(X[0]+mu)/r1**3-mu*(X[0]-(1-mu))/r2**3
Ay= X[1]-2*X[3]-(1-mu)*X[1]/r1**3-mu*X[1]/r2**3
Az= -(1-mu)*X[2]/r1**3-mu*X[2]/r2**3

XDelta=array([X[3], X[4], X[5], Ax, Ay, Az])

return XDelta




On Mon, Mar 7, 2011 at 11:50 AM, Jon Herman  wrote:

> Sorry Robert, I'd missed your post when I just made my last one. The output
> I am getting in Python looks as follows:
>
> array([  9.91565050e-01,   1.55680112e-05,  -1.53258602e-05,
> -5.75847623e-05,  -9.64290960e-03,  -8.26333458e-08])
>
> This is the final state vector, consisting of 6 states (postion and
> velocity), although this isn't really relevant right now.
>
> In MATLAB, using the same process for the RKF78, I get the following
> output:
>
> Xend =
>
>   Columns 1 through 3
>
> 9.915755153307796e-0013.592556838089922e-016
> -1.523933534321440e-005
>
>   Columns 4 through 6
>
>-7.175069559491303e-015   -9.624755221500220e-003
> 1.289789641929434e-017
>
> As you can see, the results are close but there is a big difference in
> precision (the 2nd, 4th and 6th entries are supposed to be zero under the
> intial and final conditions I am running).
> See also the post I just made where you can see the Python code I am using
> (MATLAB code is identical but translated)
>
> This is for a fixed timestep in both Python and Matlab. If I let the code
> run with an identical method for timestep correction (based on a tolerance),
> Python will use a timestep approximately 10^5 SMALLER than Matlab uses. So
> I'm really sure it's not a representation issue, but actually a precision
> issue.
>
> Thanks for any advice!
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Numerical representation

2011-03-07 Thread Jon Herman
And for the sake of additional completeness (I'm sorry I didn't think of all
this in one go): my derivative function in Python produces results that
agree with MATLAB to order e-16 (machine precision), so the error is
definitely building up in my integrator.



On Mon, Mar 7, 2011 at 11:59 AM, Jon Herman  wrote:

> And for the sake of completeness, the derivative function I am calling from
> my integrator (this is the 3 body problem in astrodynamics):
>
> def F(mu, X, ti):
>
> r1= pow((pow(X[0]+mu,2)+pow(X[1],2)+pow(X[2],2)),0.5)
> r2= pow((pow(X[0]+mu-1,2)+pow(X[1],2)+pow(X[2],2)),0.5)
>
> Ax= X[0]+2*X[4]-(1-mu)*(X[0]+mu)/r1**3-mu*(X[0]-(1-mu))/r2**3
> Ay= X[1]-2*X[3]-(1-mu)*X[1]/r1**3-mu*X[1]/r2**3
> Az= -(1-mu)*X[2]/r1**3-mu*X[2]/r2**3
>
> XDelta=array([X[3], X[4], X[5], Ax, Ay, Az])
>
> return XDelta
>
>
>
>
>
> On Mon, Mar 7, 2011 at 11:50 AM, Jon Herman  wrote:
>
>> Sorry Robert, I'd missed your post when I just made my last one. The
>> output I am getting in Python looks as follows:
>>
>> array([  9.91565050e-01,   1.55680112e-05,  -1.53258602e-05,
>> -5.75847623e-05,  -9.64290960e-03,  -8.26333458e-08])
>>
>> This is the final state vector, consisting of 6 states (postion and
>> velocity), although this isn't really relevant right now.
>>
>> In MATLAB, using the same process for the RKF78, I get the following
>> output:
>>
>> Xend =
>>
>>   Columns 1 through 3
>>
>> 9.915755153307796e-0013.592556838089922e-016
>> -1.523933534321440e-005
>>
>>   Columns 4 through 6
>>
>>-7.175069559491303e-015   -9.624755221500220e-003
>> 1.289789641929434e-017
>>
>> As you can see, the results are close but there is a big difference in
>> precision (the 2nd, 4th and 6th entries are supposed to be zero under the
>> intial and final conditions I am running).
>> See also the post I just made where you can see the Python code I am using
>> (MATLAB code is identical but translated)
>>
>> This is for a fixed timestep in both Python and Matlab. If I let the code
>> run with an identical method for timestep correction (based on a tolerance),
>> Python will use a timestep approximately 10^5 SMALLER than Matlab uses. So
>> I'm really sure it's not a representation issue, but actually a precision
>> issue.
>>
>> Thanks for any advice!
>>
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Numerical representation

2011-03-07 Thread Jon Herman
It really is exactly the same process, but sure. Below is my Matlab
translation of the python code I posted earlier, it functions at the
increased accuracy I've shown above.

   k(:,1)=feval(deq, ti, x, mu);

 for n = 2:1:13
nn=n-1;
Xtemp1 = 0.0;
for j = 1:1:nn
Xtemp1 = Xtemp1 + beta(n,j) * k(:,j);
end
x=xwrk+ dt * Xtemp1;
ti=twrk+alph(n)*dt;
k(:,n)=feval(deq, ti, x, mu);
 end

  Xtemp2=0.0;
for l  = 1:1:13
Xtemp2=Xtemp2+ch(l)*k(:,l);
end


x=xwrk + dt * Xtemp2;
t=twrk+dt;




On Mon, Mar 7, 2011 at 1:50 PM, Chris Rebert  wrote:

> >>> On Fri, Mar 4, 2011 at 2:32 PM, Jon Herman 
> wrote:
> >>>>
> >>>> I am new to the Python language and writing a Runge-Kutta-Fellberg
> 7(8)
> >>>> integrator in Python, which requires an extreme numerical precision
> for my
> >>>> particular application. Unfortunately, I can not seem to attain it.
> >>>> The interesting part is if I take my exact code and translate it to
> >>>> Matlab code (so I use the exact same process and numbers), I get a far
> >>>> superior precision (the one I am expecting, in fact). This leads me to
> think
> >>>> I need to call a certain command in my Python script in order to make
> sure
> >>>> no truncation errors are building up over my integration.
> >>>>
> >>>> Has anyone had similar problems? Is there a difference between how
> >>>> Matlab and Python store numbers, and if so how do I make Python more
> >>>> accurate?
> >>>>
> 
> On Mon, Mar 7, 2011 at 10:36 AM, Jon Herman  wrote:
> > I'm starting to run out of ideas of what to do...I've imported the true
> > division (I'm using Python 2.7) to make sure I wasn't accidentally using
> any
> > integers but the results remain identical, so it's not a division
> problem.
> > I've copied the loop I'm running below, is there any mathematical
> operation
> > I am making here that may have an accuracy problem? Thanks for any advice
> > you can give!
> >
> 
>
> Since the problem is quite possibly due to an imperfection in the
> translation process, I think also posting your MATLAB integrator code
> for comparison would be advisable.
>
> Cheers,
> Chris
> --
> Please avoid top-posting:
> http://en.wikipedia.org/wiki/Top-posting
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Numerical representation

2011-03-07 Thread Jon Herman
Thanks Terry! Of course, speed is not my main concern at this point and I'm
more worried about precision...would you have some input on this discussion?
:)

Jon



On Mon, Mar 7, 2011 at 2:35 PM, Terry Reedy  wrote:

> On 3/7/2011 1:59 PM, Jon Herman wrote:
>
>> And for the sake of completeness, the derivative function I am calling
>> from my integrator (this is the 3 body problem in astrodynamics):
>>
>> def F(mu, X, ti):
>>
>> r1= pow((pow(X[0]+mu,2)+pow(X[1],2)+pow(X[2],2)),0.5)
>>
>
>x0 = X[0]; x1 = X[1]; x2 = X[2]
>r1 = sqrt((x0+mu)**2) + x1*x1 + x2*x2)
>etc...
> might be faster. Certainly, repeated lookups of pow is slow
> and above is easier to read.
>
>  r2= pow((pow(X[0]+mu-1,2)+pow(X[1],2)+pow(X[2],2)),0.5)
>>
>> Ax= X[0]+2*X[4]-(1-mu)*(X[0]+mu)/r1**3-mu*(X[0]-(1-mu))/r2**3
>> Ay= X[1]-2*X[3]-(1-mu)*X[1]/r1**3-mu*X[1]/r2**3
>> Az= -(1-mu)*X[2]/r1**3-mu*X[2]/r2**3
>>
>> XDelta=array([X[3], X[4], X[5], Ax, Ay, Az])
>>
>> return XDelta
>> \
>>
>
>
> --
> Terry Jan Reedy
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Numerical representation

2011-03-08 Thread Jon Herman
Thanks all for the input, the remark about printing intermediate steps was a
very good one (and so obvious I can't believe it took me this long to get
there...)

The error was in my loop where I multiply by the "b" or "beta" coefficients.
The range for this loop (marked by j) is set up properly in Matlab (1 to nn)
but in Python running this over range(nn) drops the values of the column
'nn'. That means the coefficients were all wrong. This quickly became
apparent as I was printing a number of internal values.

Thank you for the assistance, I apologize for asking your time for such a
beginner's oversight...I'll be fluent in Python some day ;-)



On Mon, Mar 7, 2011 at 5:34 PM, Robert Kern  wrote:

> On 3/7/11 2:52 PM, Jon Herman wrote:
>
>> It really is exactly the same process, but sure. Below is my Matlab
>> translation
>> of the python code I posted earlier, it functions at the increased
>> accuracy I've
>> shown above.
>>
>>k(:,1)=feval(deq, ti, x, mu);
>>
>>  for n = 2:1:13
>> nn=n-1;
>> Xtemp1 = 0.0;
>> for j = 1:1:nn
>> Xtemp1 = Xtemp1 + beta(n,j) * k(:,j);
>> end
>> x=xwrk+ dt * Xtemp1;
>> ti=twrk+alph(n)*dt;
>> k(:,n)=feval(deq, ti, x, mu);
>>  end
>>
>>   Xtemp2=0.0;
>> for l  = 1:1:13
>> Xtemp2=Xtemp2+ch(l)*k(:,l);
>> end
>>
>>
>> x=xwrk + dt * Xtemp2;
>> t=twrk+dt;
>>
>
> You may want to try printing out values in both implementations to see
> where they start to diverge.
>
> --
> Robert Kern
>
> "I have come to believe that the whole world is an enigma, a harmless
> enigma
>  that is made terrible by our own mad attempt to interpret it as though it
> had
>  an underlying truth."
>  -- Umberto Eco
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Reading/Writing files

2011-03-18 Thread Jon Herman
Hello all,

I am pretty new to Python and am trying to write data to a file. However, I
seem to be misunderstanding how to do so. For starters, I'm not even sure
where Python is looking for these files or storing them. The directories I
have added to my PYTHONPATH variable (where I import modules from
succesfully) does not appear to be it.

So my question is: How do I tell Python where to look for opening files, and
where to store new files?

Thanks,

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


Re: Reading/Writing files

2011-03-18 Thread Jon Herman
Jack,

thanks.

Alright, so what I did is create a file called hello.txt with a single line
of text in there. I then did the following:

f="fulldirectory\hello.txt" (where fulldirectory is of course the actual
full directory on my computer)
open("f", "w")

And I get the following error: IOError: [Errno 13] Permission denied: 'f'
If I open to read, I get: IOError: [Errno 2] No such file or directory: 'f'

Can anyone explain to me why this happens?




On Fri, Mar 18, 2011 at 3:50 PM, Jack Trades wrote:

>
> On Fri, Mar 18, 2011 at 4:33 PM, Jon Herman  wrote:
>
>> Hello all,
>>
>> I am pretty new to Python and am trying to write data to a file. However,
>> I seem to be misunderstanding how to do so. For starters, I'm not even sure
>> where Python is looking for these files or storing them. The directories I
>> have added to my PYTHONPATH variable (where I import modules from
>> succesfully) does not appear to be it.
>>
>> So my question is: How do I tell Python where to look for opening files,
>> and where to store new files?
>>
>> Thanks,
>>
>> Jon
>>
>>
> By default Python will read and write files from the directory that your
> program is run from.  This cannot always be relied upon though (for instance
> if your program was imported as a module from another program).
>
> To find out what directory your program is currently in use os.getcwd().
> Here's an example I just ran...
>
> >>> import os
> >>> os.getcwd()
> '/media/DATA/code/lispy/liSpy'
>
> The folder that is returned from os.getcwd() is the folder that "open" will
> use.  You can specify another folder by giving the full path.
>
> open("/full/path/to/file.txt", "w")
>
> PYTHONPATH is for importing modules, which is a separate concern.
>
> --
> Jack Trades
> Pointless Programming Blog <http://pointlessprogramming.wordpress.com>
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading/Writing files

2011-03-18 Thread Jon Herman
Folks,

thanks for the many responses! Specifying the full file name (and not using
parentheses when inappropriate, thanks Jack :)) I am now happily
reading/writing files.

My next question: what is the best way for me to write an array I generated
to a file?
And what is the best way for me to load that array again, the next time I
start up my computer?

Basically I am doing very large computations and want to store the results.

Thanks a lot guys!

Jon




On Fri, Mar 18, 2011 at 4:18 PM, Dan Stromberg  wrote:

>
> Are you on windows?
>
> You probably should use / as your directory separator in Python, not \.  In
> Python, and most other programming languages, \ starts an escape sequence,
> so to introduce a literal \, you either need to prefix your string with r
> (r"\foo\bar") or double your backslashes ("\\foo\\bar").
>
> / works fine on windows, and doesn't require escaping ("/foo/bar").
>
> On Fri, Mar 18, 2011 at 2:56 PM, Jon Herman  wrote:
>
>> Jack,
>>
>> thanks.
>>
>> Alright, so what I did is create a file called hello.txt with a single
>> line of text in there. I then did the following:
>>
>> f="fulldirectory\hello.txt" (where fulldirectory is of course the actual
>> full directory on my computer)
>> open("f", "w")
>>
>> And I get the following error: IOError: [Errno 13] Permission denied: 'f'
>> If I open to read, I get: IOError: [Errno 2] No such file or directory:
>> 'f'
>>
>> Can anyone explain to me why this happens?
>>
>>
>>
>>
>>
>> On Fri, Mar 18, 2011 at 3:50 PM, Jack Trades 
>> wrote:
>>
>>>
>>> On Fri, Mar 18, 2011 at 4:33 PM, Jon Herman wrote:
>>>
>>>> Hello all,
>>>>
>>>> I am pretty new to Python and am trying to write data to a file.
>>>> However, I seem to be misunderstanding how to do so. For starters, I'm not
>>>> even sure where Python is looking for these files or storing them. The
>>>> directories I have added to my PYTHONPATH variable (where I import modules
>>>> from succesfully) does not appear to be it.
>>>>
>>>> So my question is: How do I tell Python where to look for opening files,
>>>> and where to store new files?
>>>>
>>>> Thanks,
>>>>
>>>> Jon
>>>>
>>>>
>>> By default Python will read and write files from the directory that your
>>> program is run from.  This cannot always be relied upon though (for instance
>>> if your program was imported as a module from another program).
>>>
>>> To find out what directory your program is currently in use os.getcwd().
>>> Here's an example I just ran...
>>>
>>> >>> import os
>>> >>> os.getcwd()
>>> '/media/DATA/code/lispy/liSpy'
>>>
>>> The folder that is returned from os.getcwd() is the folder that "open"
>>> will use.  You can specify another folder by giving the full path.
>>>
>>> open("/full/path/to/file.txt", "w")
>>>
>>> PYTHONPATH is for importing modules, which is a separate concern.
>>>
>>> --
>>> Jack Trades
>>> Pointless Programming Blog <http://pointlessprogramming.wordpress.com>
>>>
>>>
>>
>> --
>>
>> http://mail.python.org/mailman/listinfo/python-list
>>
>>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading/Writing files

2011-03-18 Thread Jon Herman
Wow, Jack, that is one awesome and simple module...thank you so much! I am
happily storing and accessing all the arrays I could ever want :)

Thanks to all for the quick assistance!




On Fri, Mar 18, 2011 at 4:24 PM, Jack Trades wrote:

>
> On Fri, Mar 18, 2011 at 5:21 PM, Jon Herman  wrote:
>
>> Folks,
>>
>> thanks for the many responses! Specifying the full file name (and not
>> using parentheses when inappropriate, thanks Jack :)) I am now happily
>> reading/writing files.
>>
>> My next question: what is the best way for me to write an array I
>> generated to a file?
>> And what is the best way for me to load that array again, the next time I
>> start up my computer?
>>
>> Basically I am doing very large computations and want to store the
>> results.
>>
>> Thanks a lot guys!
>>
>> Jon
>>
>>
> To save a data structure like an array (called a list in Python), you can
> use the pickle module.  Here's the documentation on pickle.
>
> http://docs.python.org/library/pickle.html
>
> http://www.developertutorials.com/tutorials/python/python-persistence-management-050405-1306/
>
>
>
> --
> Jack Trades
> Pointless Programming Blog <http://pointlessprogramming.wordpress.com>
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Accessing Self Inside Decorator with parameters

2017-12-14 Thread Brian Herman
I would like to access the instance variable of a class using a decorator
with arguments:
I used to do with with a decorator without arguments:

def decorator(method):
""" This method is a decorator to get a security token each time you
have a service call. """
def wrapper(self, *args, **kw):
self.call_this()
result = method(self, *args, **kw)

return result
return wrapper

class test1:
def call_this(self):
print("this works")
@decorator
def preform_action(self):
print("test")

However when I add the arguments decorator I cannot access the self of the
object that calls the decorator.

def decorator_with_arguments(arg1, arg2):
def decorator(self, method):
""" This method is a decorator to get a security token each time
you have a service call. """
def wrapper(self, *args, **kw):
self.call_this()
result = method(self, *args, **kw)

return result
return wrapper

class test2:
def call_this(self):
print("this does not")
@decorator_with_arguments(1,2)
def preform_action(self):
    print("test")

Is there any way to do this pythonically?
-- 


Thanks,
Brian Herman
kompile.org <http://www.kompile.org>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python CGI Script

2005-10-02 Thread Ivan Herman
Efrat,

I am afraid a CGI script is never *executed* by the browser. Instead, it sends
the URL to a server, expects the server to execute the script, and display the
server's response. If you just put a file name then (it seems, I never even
tried that) Firefox uses the local file store as a 'server' in that respect.

If you want to test a CGI script on your own machine, you should run a web
server on your own machine. That server should also be set up in a way that it
recognizes a '.py' file as a CGI script to be executed by Python (not all
servers may recognize the #!  trick...).

This may look scary, but it is not that bad. Apache has a number of precompiled
binary versions that you can install on your machine; you can also use servers
like W3C's jigsaw (this relies on Java) or others. These are all free and easy
to install and, well, manageable to configure. Actually, in case you run on a
MacOS X by any chance, Apache is already installed afaik...

I hope this helps

Ivan


 Original Message 
From: Efrat Regev <[EMAIL PROTECTED]>
To:
Subject: Python CGI Script
Date: 30/9/2005 12:50

> Hello,
> 
> I'm a data-structures course TA trying to write a python CGI script
> for automatically compiling and testing students' projects.
> Unfortunately, I've run into some questions while writing this, which I
> couldn't solve with the various (and helpful) python-CGI documentation.
> (It's possible that I'm posting to the wrong group; if so, I'd
> appreciate suggestions for the appropriate group.)
> 
> 
> 1. In my HTML page, I have the following:
> 
>  enctype="multipart/form-data">
> ...
> 
> 
> In the above, submission_processor.py is the python CGI script. I
> didn't write a URL in the action field, since I'm first testing
> everyting on a local machine (running FC4). The first line of
> submission_processor.py is
> 
> #!/usr/bin/python
> 
> and I've done
> 
> chmod +x submission_processor.py
> 
> When I hit the "submit" button, my browser (Firefox on FC4) doesn't
> run the script; it asks me whether it should open
> submission_processor.py or save it to disk. I couldn't figure out why.
> 
> 2. My HTML page has the option for an instructor to list the various
> submissions and scores. Obviously, this should be inaccessible to
> students. The instructor has a password for doing this, therefore.
> Suppose I place the password inside a python script, and give this
> script only +x permission for others. Is this  adequate as far as security?
> 
> 
> Thanks in advance for answering these questions.
> 
> 
>  Efrat
-- 
http://mail.python.org/mailman/listinfo/python-list


PIL question: keeping metadata

2005-06-29 Thread Ivan Herman
A question on using the PIL library. If I take a jpg file then, say, resize it 
and save it
somewhere else, all metadata that is part of the jpg file is lost. This is a 
pity: digital
cameras routinely add metainformation, so does, for example, Photoshop.

Is there any way of keeping this info in PIL? Alternatively, is there a simple 
image
processing package that does it?

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


Python Weekend Challenge - $$

2013-08-30 Thread Michael Herman
https://gist.github.com/mjhea0/6390724

Check it out!:)

Have a great labor day weekend.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Automate deployment of Python application from multiple VCS repositories

2015-04-08 Thread Michael Herman
Hi Ben,

I would start with Fabric. -> http://www.fabfile.org/. It's "low-level",
but super straightforward.

Here's a blog post on how to setup deployment ->
https://realpython.com/blog/python/kickstarting-flask-on-ubuntu-setup-and-deployment/

On Tue, Apr 7, 2015 at 7:24 PM, Ben Finney 
wrote:

> Howdy all,
>
> What tools are available to automate deployment of a Python application
> comprising many discrete modules, spread across different code bases in
> different VCS repositories?
>
> My idea is to have a single definition (itself under VCS control) that
> specifies VCS locations and branches, a hierarchy into which all the
> modules fit, and a deployment host.
>
> host foo:
> repo ‘spam-common ’, branch ‘trunk’, at ‘./common/’
> repo ‘beans ’, branch ‘version 6.1’, at ‘./’
> repo ‘sausage ’, branch ‘trunk’, at ‘./third-party/sausage/’
>
> host bar:
> repo ‘spam-common ’, branch ‘maint’, at ‘./common/’
> repo ‘beans ’, branch ‘version 7.0’, at ‘./’
> repo ‘eggs ’, branch ‘master’, at ‘./third-party/eggs/’
> repo ‘toast ’, branch ‘trunk’, at ‘./third-party/eggs/toast/’
> repo ‘sausage ’, branch ‘version 1.4’, at
> ‘./third-party/sausage/’
>
> The deployment tool, when told which host specification to use, then
> gathers the code by exporting it from its disparate branches, fits it
> into the directory hierarchy, and deploys that to the specified host.
>
> The goal is to be able to have multiple host specifications, each of
> which needs a different set of code repositories (and often different
> branches within those repositories) to be built into the deployed
> application.
>
> What frameworks are there to do this for Python code?
>
> --
>  \   “Know what I hate most? Rhetorical questions.” —Henry N. Camp |
>   `\   |
> _o__)  |
> Ben Finney
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python on windows

2013-02-16 Thread Michael Herman
http://www.youtube.com/watch?v=dFnuK9dlWdk

On Sat, Feb 16, 2013 at 1:40 PM, babatunde akerele wrote:

> hello, i'm having problem coding and running python on my pc...i just
> started learning python last month in codeacademy.com but i've not
> been able to code offline 'cos i don't knw how to go abt installing
> the compiler and all that. Any help please?
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: request of information

2013-02-17 Thread Michael Herman
There's a syntax error at line 1 of circle.py. Try running circle.py,
you'll get more information about the error -
http://docs.python.org/2/tutorial/errors.html

If you can't figure it out, post your code for circle.py.

On Sun, Feb 17, 2013 at 10:47 AM, leonardo selmi  wrote:

>
> >
> >
> >
> >
> >> gentlemen:
> >>
> >> i am reading a book about python and now i am blocked, i can't store
> functions in modules: i have a mac and am using version 2.7.3, i have
> created a function and want to save it as a file using "idle", i have saved
>  it with .py , when i try to import the module i get an error:
> traceback(most recent call last) file
> >> "", line 1, in 
> >> import circle
> >> file "circle.py", line 1
> >> syntax error: invalid syntax
> >>
> >> can you kindly help me?
> >> thanks!
> >>
> >> best regards
> >
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Quick IDE Question

2013-02-17 Thread Michael Herman
Yup - check out this post -
http://www.chris-granger.com/2012/05/21/the-future-is-specific/

There's a Flask example

On Sun, Feb 17, 2013 at 4:56 PM, Andrew Berg wrote:

> On 2013.02.17 18:38, Claira wrote:
> > Ok, thanks brilliant people! I can't really keep up with the
> > conversation about where I should ask since I check my email once a
> > week, though the quick question I had was that I heard lighttable.com
> >  was an innovative IDE, and since I'm preparing
> > for the future, I just wanted to know if light table supports python.
> > Thanks!!
> I remember reading on the Kickstarter page that it will since it raised
> a certain amount of money.
> --
> CPython 3.3.0 | Windows NT 6.2.9200.16461 / FreeBSD 9.1-RELEASE
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Import Json web data source to xls or csv

2013-02-19 Thread Michael Herman
First - you can use Python in Excel. http://www.python-excel.org/ or
https://www.datanitro.com/

Updated code:

import json
import urllib
import csv

url = "http://bitcoincharts.com/t/markets.json";
response = urllib.urlopen(url);
data = json.loads(response.read())

f = open("bitcoin.csv","wb")
c = csv.writer(f)

# write headers
c.writerow(["Currency","Symbol","Bid", "Ask", "Volume"])


for d in data:

c.writerow([str(d["currency"]),str(d["symbol"]),str(d["bid"]),str(d["ask"]),str(d["currency_volume"])])



On Tue, Feb 19, 2013 at 3:48 PM, io  wrote:

> Hi,
>
> i'm new to python and programming with it and so for json format.
> I have my excel 2010 program with vba that does the following :
>
> - read the data flow from http://bitcoincharts.com/t/markets.json
> - elaborate it and puts it in excel 2010 for further calculations
>
> What i'm willing to do is the same using Linux (xubuntu) and libreoffice.
>
> I thought learning python would be a smart idea for dealing with json
> format as it has a json library/module.
>
> How do i manage to read the data source from http://bitcoincharts.com/t/
> markets.json  and then place it in different cell of a new or existing
> xls worksheet?
>
> I'm trying some code with SPE but i can't sort the problem and i'm
> receiving many errors.
>
> I just need currency, symbol, bid, ask, volume
> This is the source code i was trying to use :
>
>
> import json
> import csv
> import urllib
>
> url = "http://bitcoincharts.com/t/markets.json";
> response = urllib.urlopen(url);
> data = json.loads(response.read())
>
> f = csv.writer(open('file.csv', 'wb+'))
> # use encode to convert non-ASCII characters
> for item in data:
> values = [ x.encode('utf8') for x in item['0'].values() ]
> f.writerow([item['currency'], item['high']] + values)
>
>
>
> Thanks for any help :-)
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Crate is a new kind of Python package index

2013-02-20 Thread Michael Herman
It's really just a supplement to PyPI. I use it quite a bit. I wish they
would collaborate with PyPi or have an open API.

http://www.saltycrane.com/blog/2012/10/how-use-pip-crateio/

On Wed, Feb 20, 2013 at 6:12 AM, Mark Lawrence 
wrote:
>
> Today was the first I've heard about it, can anyone shed any light as
documentation appears to be rather sparse?
>
> https://crate.io/
>
> --
> Cheers.
>
> Mark Lawrence
>
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Import Json web data source to xls or csv

2013-02-20 Thread Michael Herman
Looks like you got it figured out. The indentation error probably occurred
from the copy and paste job into the email.

If you're interested in getting up to speed quickly on Python and Python
Web Development, I have a kickstarter going - http://kck.st/VQj8hq

The $25 pledge will give you access to both courses - learning Python
syntax and Python web development

Let me know if you have any questions. Thanks!

On Tue, Feb 19, 2013 at 11:13 PM, io  wrote:

> Hi Michael (name of my son) and thanks for the big help.
>
> I'm starting to love python sintax (did they call it python for the slim
> it is compared to other languages?)
>
> Your code didn't work immediatley as it was givin an indentation error
> that i sorted out quickly fixing the last two lines.
>
> It worked like a charm!  :-)
>
> About your suggestions, i tried datanitro but that it only for excel and
> seems to not work under linux on playonlinux (as no linux support is
> given)
>
> I haven't tried the other solution you suggested, i will give it a try as
> soon as possible.
>
> What i'm trying to do is find a new programming language that can
> integrate with softwares like libre office cal or openoffice cal or excel
> as i had my prg working on windows and vba didn't have any issues, but
> now that i moved and try to do all on linux vba isn't 100 percent working
> and many system calls cannot be done.
>
> Do you know any place where i can start learning seriously python on the
> web?
>
>
> Last question : how can i set a condition in order to exclude from
> importing those rows that have both bid and ask values = none?
> I'll try to figure it out in the meantime but i'm a noob so any help will
> be appreciated.
>
> I actually started using SPE and have winpdb installed on my linux box.
>
> Thanks again for all the help.
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Import Question

2013-02-20 Thread Michael Herman
you can check each import as it varies in loading time: time python -c
"import [name of module]"

example: time python -c "import flask"

On Wed, Feb 20, 2013 at 12:53 PM, eli m  wrote:

> How long does it take for the program to import something? I am asking
> this because i have like 7 imports at the beginning of my program and i am
> thinking thats the reason why it is slow to start up. Thanks in advance.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python scheduler

2013-02-20 Thread Michael Herman
You could simply put a time delay in your program at the end of the loop
before it starts again-

import time
# sleep for 1 minute
time.sleep(60)

On Wed, Feb 20, 2013 at 8:04 PM, Rita  wrote:

> Hello,
>
>
> Here is what I am trying to do. (Currently, I am doing this in cron but i
> need much more granularity). I am trying to run program every 20 secs and
> loop forever. I have several of these types of processes, some should run
> every 5 mins, 10 secs, 20 secs, 1 min and so forth. I was wondering what is
> the best way to do this?
>
>
> Also, would Greenlet do something I am asking for?
>
>
>
> --
> --- Get your facts first, then you can distort them as you please.--
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Urllib's urlopen and urlretrieve

2013-02-21 Thread Michael Herman
Are you just trying to get the html? If so, you can use this code-

*import urllib*
*
*
*# fetch the and download a webpage, nameing it test.html*
*urllib.urlretrieve("http://www.web2py.com/";, filename="test.html")*


I recommend using the requests library, as it's easier to use and more
powerful:

*import requests*

*# retrive the webpage
r = requests.get("http://www.web2py.com/";)*

*# write the content to test_request.html
with open("test_requests.html", "wb") as code:
*

*code.write(r.content)*


If you want to get up to speed quickly on internet programming, I have a
course I am developing. It's on kickstarter - http://kck.st/VQj8hq. The
first section of the book dives into web fundamentals and internet
programming.


On Thu, Feb 21, 2013 at 4:12 AM,  wrote:

> I only just started Python and given that I know nothing about network
> programming or internet programming of any kind really, I thought it would
> be interesting to try write something that could create an archive of a
> website for myself. With this I started trying to use the urllib library,
> however I am having a problem understanding why certain things wont work
> with the urllib.urlretrieve and urllib.urlopen then reading.
>
> Why is it that when using urllib.urlopen then reading or
> urllib.urlretrieve, does it only give me parts of the sites, loosing the
> formatting, images, etc...? How can I get around this?
>
> Lastly, while its a bit off topic, I lack a good understanding of network
> programming as a whole. From making programs communicate or to simply
> extract data from URL's, I don't know where to even begin, which has lead
> me to learning python to better understand it hopefully then carry it over
> to other languages I know. Can anyone give me some advice on where to begin
> learning this information? Even if its in another language.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pypi changelog api

2013-02-21 Thread Michael Herman
I'd love to see https://crate.io/ set up an API or at the very least an RSS
feed for tracking changes. I've emailed the author about this. I think if
enough people do, an RSS feed would be easy to setup.


On Thu, Feb 21, 2013 at 5:33 AM, Philipp Hagemeister wrote:

> Hi Gregg,
>
> to get a smaller response, you can simply pass in a timestamp, like this:
>
> >>> client = xmlrpclib.ServerProxy('http://pypi.python.org/pypi')
> >>> import time
> >>> client.changelog(int(time.time() - 600))
> [['vs.bootstrap.plonetheme', '1.0.1', 1361451748, 'update description,
> classifiers'], ['numericalunits', '1.11', 1361451759, 'new release'],
> ['numericalunits', '1.11', 1361451760, 'add source file
> numericalunits-1.11.tar.gz'], ['autobahn_rce', '0.6.0', 1361451798,
> 'remove'], ['vs.bootstrap.plonetheme', '1.0.1', 1361451816, 'update
> description, classifiers'], ['vs.bootstrap.plonetheme', '1.0.1',
> 1361451882, 'update description, classifiers'], ['autobahn_rce',
> '0.5.9', 1361451956, 'new release'], ['autobahn_rce', '0.5.9',
> 1361451971, 'add source file autobahn_rce-0.5.9.tar.gz']]
>
> I don't think there's way to get older chunks of the changelog though.
> What would you need those for?
>
> If you need the entire changelog, just download it once (it's not that
> large, barely 40MB). Here it is, up until 1361452402 (now):
>
> http://phihag.de/2013/pypi-changelog-2013-02-20.json.bz2
>
> What I'd like is a real-time push service of changelog entries, but I'm
> not certain that would be scalable.
>
> Cheers,
>
> Philipp
>
>
> On 02/18/2013 02:16 AM, Gregg Caines wrote:
> > Hey all,
> >
> > I'm trying to write a script that tracks changes on pypi, and I've come
> across the xmlrpc interface, specifically the 'changelog' api.  It's
> definitely what I'm looking for, but I get an absolutely massive xml
> response from it at once and I was hoping there might be either some way to
> "page" through it with mulitple requests, or a different-but-similar API.
> >
> > Thanks in advance,
> > Gregg
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pypi changelog api

2013-02-21 Thread Michael Herman
Oh - and I haven't tried this site, but you may be able to set something up
on there to email when the changelog is updated.

http://www.changedetection.com/

On Thu, Feb 21, 2013 at 5:52 AM, Michael Herman  wrote:

> I'd love to see https://crate.io/ set up an API or at the very least an
> RSS feed for tracking changes. I've emailed the author about this. I think
> if enough people do, an RSS feed would be easy to setup.
>
>
> On Thu, Feb 21, 2013 at 5:33 AM, Philipp Hagemeister wrote:
>
>> Hi Gregg,
>>
>> to get a smaller response, you can simply pass in a timestamp, like this:
>>
>> >>> client = xmlrpclib.ServerProxy('http://pypi.python.org/pypi')
>> >>> import time
>> >>> client.changelog(int(time.time() - 600))
>> [['vs.bootstrap.plonetheme', '1.0.1', 1361451748, 'update description,
>> classifiers'], ['numericalunits', '1.11', 1361451759, 'new release'],
>> ['numericalunits', '1.11', 1361451760, 'add source file
>> numericalunits-1.11.tar.gz'], ['autobahn_rce', '0.6.0', 1361451798,
>> 'remove'], ['vs.bootstrap.plonetheme', '1.0.1', 1361451816, 'update
>> description, classifiers'], ['vs.bootstrap.plonetheme', '1.0.1',
>> 1361451882, 'update description, classifiers'], ['autobahn_rce',
>> '0.5.9', 1361451956, 'new release'], ['autobahn_rce', '0.5.9',
>> 1361451971, 'add source file autobahn_rce-0.5.9.tar.gz']]
>>
>> I don't think there's way to get older chunks of the changelog though.
>> What would you need those for?
>>
>> If you need the entire changelog, just download it once (it's not that
>> large, barely 40MB). Here it is, up until 1361452402 (now):
>>
>> http://phihag.de/2013/pypi-changelog-2013-02-20.json.bz2
>>
>> What I'd like is a real-time push service of changelog entries, but I'm
>> not certain that would be scalable.
>>
>> Cheers,
>>
>> Philipp
>>
>>
>> On 02/18/2013 02:16 AM, Gregg Caines wrote:
>> > Hey all,
>> >
>> > I'm trying to write a script that tracks changes on pypi, and I've come
>> across the xmlrpc interface, specifically the 'changelog' api.  It's
>> definitely what I'm looking for, but I get an absolutely massive xml
>> response from it at once and I was hoping there might be either some way to
>> "page" through it with mulitple requests, or a different-but-similar API.
>> >
>> > Thanks in advance,
>> > Gregg
>>
>>
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pypi changelog api

2013-02-21 Thread Michael Herman
totally agree. if you just had a listener setup you could just have a
simple trigger-action setup.

On Thu, Feb 21, 2013 at 6:07 AM, Philipp Hagemeister wrote:

> On 02/21/2013 02:58 PM, Michael Herman wrote:
> > Oh - and I haven't tried this site, but you may be able to set something
> up
> > on there to email when the changelog is updated.
> >
> > http://www.changedetection.com/
> They just query the whole page - I could do that myself, easily. But the
> problem is that that would mean lots of load on PyPi (if you query every
> minute or so) and outdated packages (if you query less often than that).
> Keeping a connection that PyPi would push to seems to be much cleaner.
>
> - Philipp
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pypi changelog api

2013-02-21 Thread Michael Herman
yeah, i just checked github, i thought a buddy of mine had submitted an
issue

not sure how they get their updates.

this is an interesting project - https://github.com/kencochrane/pypi-mirrors

On Thu, Feb 21, 2013 at 6:04 AM, Philipp Hagemeister wrote:

> Just FYI, PyPi already has an RSS feed:
> https://pypi.python.org/pypi?:action=rss
>
> And instead of mailing the author, you should probably open an issue (or
> better yet, a pull request) at https://github.com/crateio/crate.web/issues
>
> For that matter - how does crate.io update their PyPi mirror?
>
> Cheers,
>
> Philipp
>
>
> On 02/21/2013 02:52 PM, Michael Herman wrote:
> > I'd love to see https://crate.io/ set up an API or at the very least an
> RSS
> > feed for tracking changes. I've emailed the author about this. I think if
> > enough people do, an RSS feed would be easy to setup.
> >
> >
> > On Thu, Feb 21, 2013 at 5:33 AM, Philipp Hagemeister  >wrote:
> >
> >> Hi Gregg,
> >>
> >> to get a smaller response, you can simply pass in a timestamp, like
> this:
> >>
> >>>>> client = xmlrpclib.ServerProxy('http://pypi.python.org/pypi')
> >>>>> import time
> >>>>> client.changelog(int(time.time() - 600))
> >> [['vs.bootstrap.plonetheme', '1.0.1', 1361451748, 'update description,
> >> classifiers'], ['numericalunits', '1.11', 1361451759, 'new release'],
> >> ['numericalunits', '1.11', 1361451760, 'add source file
> >> numericalunits-1.11.tar.gz'], ['autobahn_rce', '0.6.0', 1361451798,
> >> 'remove'], ['vs.bootstrap.plonetheme', '1.0.1', 1361451816, 'update
> >> description, classifiers'], ['vs.bootstrap.plonetheme', '1.0.1',
> >> 1361451882, 'update description, classifiers'], ['autobahn_rce',
> >> '0.5.9', 1361451956, 'new release'], ['autobahn_rce', '0.5.9',
> >> 1361451971, 'add source file autobahn_rce-0.5.9.tar.gz']]
> >>
> >> I don't think there's way to get older chunks of the changelog though.
> >> What would you need those for?
> >>
> >> If you need the entire changelog, just download it once (it's not that
> >> large, barely 40MB). Here it is, up until 1361452402 (now):
> >>
> >> http://phihag.de/2013/pypi-changelog-2013-02-20.json.bz2
> >>
> >> What I'd like is a real-time push service of changelog entries, but I'm
> >> not certain that would be scalable.
> >>
> >> Cheers,
> >>
> >> Philipp
> >>
> >>
> >> On 02/18/2013 02:16 AM, Gregg Caines wrote:
> >>> Hey all,
> >>>
> >>> I'm trying to write a script that tracks changes on pypi, and I've come
> >> across the xmlrpc interface, specifically the 'changelog' api.  It's
> >> definitely what I'm looking for, but I get an absolutely massive xml
> >> response from it at once and I was hoping there might be either some
> way to
> >> "page" through it with mulitple requests, or a different-but-similar
> API.
> >>>
> >>> Thanks in advance,
> >>> Gregg
> >>
> >>
> >>
> >> --
> >> http://mail.python.org/mailman/listinfo/python-list
> >>
> >>
> >
>
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What am I doing wrong installing Python 2.7.3?

2013-02-21 Thread Michael Herman
I assume you have admin privileges on your computer, correct?


On Thu, Feb 21, 2013 at 6:39 AM, Etherus wrote:

> I have downloaded the windows installer for a 32 bit installation of
> python 2.7.3 but it tells me that:
>
> The feature you are trying to use is on a network resource that is
> unavailable.
>
> Click OK to try again, or enter an alternative path to a folder containing
> the installation package python 2.7.1 msi in the box below.
>
> When I click OK I get:
>
> The path C:\...\downloads\python -2.7.1 msi cannot be found. Verify that
> you have access to this location and try again or try to find the
> installation package python 2.7.1.msi in a folder from which you can
> install the product Python 2.7.1.
>
>
> (what is it with the 2.7.1? rather than 2.7.3 also?)
>
> By very grateful if someone could steer me in the right direction.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python in web development

2013-03-03 Thread Michael Herman
If Python is your personal choice, then it's the *best* for you. If
you are literally just going to be processing an HTML form, then CGI
is your best bet. However, if you think this functionally will grow,
then it's worth learning a web framework.

I would go with a micro framework. bottle.py is a perfect starting
point. I am a huge Flask fan, but it's a little higher level. I have
tutorials here for Flask -
http://www.youtube.com/playlist?list=PLLjmbh6XPGK5pM1QJ8I1ccdGiCTHa1IC8

Also, check out realpythonfortheweb.com for more tutorials.

Good luck! :)

On Sun, Mar 3, 2013 at 6:18 AM, Sarbjit singh  wrote:
>
> Hello All,
>
> I have been using Python as a scripting language for my office tasks. Now
> I have been thinking of using (and learning as well) for web development.
> For my tasks, I need to perform some tasks and report on the web. Now I have
> no experience of web development with Python. So, I want to conform first
> whether Python is best for web development. Python is my personal choice for
> my automation works and I want to extend it for web development.
>
> REQUIREMENT:
> I need to develop a html form which would take user input and perform some
> operations (generate intermediate files) and report result on web.
>
> >> Some guys in my organization are using Perl for this purpose and thus I
> >> could get the setup for free.But I want to learn and use Python as
> >> substitute for Perl. (PHP could also be an option. I have worked on PHP 
> >> once
> >> for handling the form data.)
>
> So my questions are:-
>
> 1. Can I use Python (I want to use personally :)) over PHP/Perl?
>
> 2. If Yes, I want to know the modules that I should learn for achieving my
> requirement. I searched internet and found Python provides CGI, Django etc.
>
> I don't much about Django/CGI, please suggest which module I should learn
> and use.
>
> Thanks
> Sarbjit
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help..

2013-05-02 Thread Michael Herman
the problem is in your code: http://screencast.com/t/haF1NY5RvpMv



On Thu, May 2, 2013 at 7:30 AM, Robert Kern  wrote:
>
> On 2013-05-02 15:20, leonardo wrote:
>>
>> on codecademy there is an interactive box where you type your code, it is a 
>> kind of exercise program to practice. but i don't understand what is wrong. 
>> this is the website address of that if you want to give a look:
>>
>> http://www.codecademy.com/courses/python-beginner-P5YtY/1/3?curriculum_id=4f89dab3d78889000396
>
>
> I think the problem is in the codecademy interface (or your use of it) rather 
> than the Python code. You will probably get better help in the codecademy 
> forums or help documentation:
>
>   http://www.codecademy.com/forums/python-beginner-P5YtY/1
>   http://help.codecademy.com/
>
> --
> Robert Kern
>
> "I have come to believe that the whole world is an enigma, a harmless enigma
>  that is made terrible by our own mad attempt to interpret it as though it had
>  an underlying truth."
>   -- Umberto Eco
>
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using XML w/ Python...

2005-12-11 Thread Ivan Herman
Look at the standard python library reference

http://docs.python.org/lib/dom-example.html

the handleSlide function almost does what you want, except that you should use
'parse' and not 'parseString'.



 Original Message 
From: "Jay" <[EMAIL PROTECTED]>
To:
Subject: Re:Using XML w/ Python...
Date: 11/12/2005 09:33

> Yes i know, i did check out a couple but i could never understand it.
> They were confusing for me and i wasnt hoping for a full typed
> tutorial, just like some help with excactly wat im trying to do, not
> the whole module... but watever, Thx alot for the feedbak.
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: suppress pyc generation

2005-12-25 Thread Ivan Herman
There is a simple, though slightly ugly trick: if the directory where the python
module resides, is not writable to the python process, the python runtime will
silently ignore .pyc generation (as far as I know). It is not elegant, but it
works...

Ivan

 Original Message 
From: "Eddy Ilg" <[EMAIL PROTECTED]>
To:
Subject: suppress pyc generation
Date: 25/12/2005 14:01

> Hi,
> 
> I would like to suppress .pyc generation or have the .pyc generation in a
> speical seperate root (I found something about PYCROOT). Has this been
> implemented yet? Is there an environment variable or a command line switch
> that suppresses .pyc generation?
> 
> Eddy
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: suppress pyc generation

2005-12-25 Thread Ivan Herman
There is a simple, though slightly ugly trick: if the directory where the python
module resides, is not writable to the python process, the python runtime will
silently ignore .pyc generation (as far as I know). It is not elegant, but it
works...

Ivan

 Original Message 
From: "Eddy Ilg" <[EMAIL PROTECTED]>
To:
Subject: suppress pyc generation
Date: 25/12/2005 14:01

> Hi,
> 
> I would like to suppress .pyc generation or have the .pyc generation in a
> speical seperate root (I found something about PYCROOT). Has this been
> implemented yet? Is there an environment variable or a command line switch
> that suppresses .pyc generation?
> 
> Eddy
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyXML: SAX vs. DOM

2006-01-21 Thread Ivan Herman
 Original Message 
From: Matthias Kaeppler <[EMAIL PROTECTED]>
To:
Subject: Re:PyXML: SAX vs. DOM
Date: 20/1/2006 21:26

> Oh and:
> Where can I find an API reference for PyXML? Am I supposed to /guess/
> which methods and attributes e.g. Sax2 supplies? :D
> 
> Thanks again,
> Matthias


Matthias,

your question is valid, and I just tell you how *I* do it...

- the core of the methods in DOM are described by the W3C recommendations. I
think the most relevant ones are:

  http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/
  http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html

where you can find all objects and methods that are defined by DOM Level 2 and,
as far as I could see, all properly implemented by PyXML.

The only caveat is that DOM2 defines the interface in abstract (more exactly, in
IDL), and one has to know (or guess) how those are mapped onto Python. Having
said that, by looking at the PyXML documentation:

  http://pyxml.sourceforge.net/topics/howto/

mainly

  http://pyxml.sourceforge.net/topics/howto/section-DOM.html

one can do a very good educated guess so it is not sooo bad as it sounds.

I know this is not the ideal answer, but maybe it helps...

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


Re: Translating some Java to Python

2007-05-21 Thread Herman Slagman

"Daniel Gee" <[EMAIL PROTECTED]> schreef in bericht 
news:[EMAIL PROTECTED]

> class Foo:
>  def statAdd(self,a):
>return a+5
>
> or do you drop the 'self' bit and just use a 1 variable parameter list?

class Foo:
 @staticmethod
 def statAdd(a):
   return a+5

HTH

Herman

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


Re: Translating some Java to Python

2007-05-21 Thread Herman Slagman

"Ant" <[EMAIL PROTECTED]> schreef in bericht 
news:[EMAIL PROTECTED]

> Herman has shown you *how* to do static methods in Python, but
> typically they are not used. Since Python has first class functions,
> and they can be defined at the module level, there is no need to use
> static methods.

Hmm,

As an experienced developer I'm rather new to Python, so please forgive me 
any non-Pythonic babbling.
>From a language point you're probably right, but from a design point I'd 
like to have methods that are clearly associated with a class as methods of 
that class, even if they don't use any class or instance related data.

Herman 

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


Re: Translating some Java to Python

2007-05-21 Thread Herman Slagman

"Gabriel Genellina" <[EMAIL PROTECTED]> schreef in bericht 
news:[EMAIL PROTECTED]
> En Mon, 21 May 2007 07:39:09 -0300, Unknown <[EMAIL PROTECTED]> 
> escribió:
>
>> "Ant" <[EMAIL PROTECTED]> schreef in bericht
>> news:[EMAIL PROTECTED]
>>
>>> Herman has shown you *how* to do static methods in Python, but
>>> typically they are not used. Since Python has first class functions,
>>> and they can be defined at the module level, there is no need to use
>>> static methods.
>>
>> As an experienced developer I'm rather new to Python, so please forgive 
>> me any non-Pythonic babbling.
>>> From a language point you're probably right, but from a design point I'd
>> like to have methods that are clearly associated with a class as methods 
>> of that class, even if they don't use any class or instance related data.
>
> In that case you might want to revise the design, perhaps you carry some 
> preconceptions about how things should be, that are not directly 
> applicable here. (I'm not saying this is related to your specific problem 
> because I don't know exactly what you want, but in general, a lot of 
> design patterns *implementations* are not directly applicable to Python).

I don't really have problems with Python (yet), merely responding to the OPs 
question.

One example that comes to mind is a class that is a proxy for a database 
class, say Person.
The Person.Load(id) method doesn't use any instance or class data, it 
instantiates a Person and populates it from the database.
It is clearly a part of the class's interface so for that I use a 
@staticmethod.

> Modules are objects too - they're a good example of singletons. If you 
> want to create a class containing only static methods: use a module 
> instead. If you want to create a class having a single instance (a 
> singleton), most of the time you can use a module instead.
> Functions don't *have* to be methods in a class, and the resulting design 
> may still be a good design from an OO point of view.

*That* Pythonic I'm already ;-)
For a utility 'class' I'm using a module, no need for a class there.
Using a module for a Singleton is good tip though.

Herman 

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


Re: Python 2.5 licensing: stop this change

2006-04-01 Thread Ivan Herman
I would certainly look at *all details* of the announcement, including
the second line from the top which gives the date:-)

Ivan


Caleb Hattingh wrote:
> WAIT-
> 
> Did I just get caught by an April Fools Joke?
> 
> I have a nasty feeling about this :))
> 
> C
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to print without blank?

2006-04-08 Thread Ivan Herman
Ju Hui wrote:
> I want to print 3 numbers without blank.
 for x in range(3):
> ... print x
> ...
> 0
> 1
> 2
 for x in range(3):
> ... print x,
> ...
> 0 1 2
> 
> how to print
> 012
> ?
> 
> thanks.
> 

You may want to use the write command with stdout:

sys.stdout.write("%s" % x)

using 'write' you have much more facilities to format the output...

I hope this helps

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