Getting started with JPype

2007-08-13 Thread porter
Hi,

For nefarious javaesque reasons I've been trying to get started with
jpype (http://jpype.sourceforge.net). This looks like a potentially
useful tool for integrating java classes into C-python, but
frustratingly I've run into immediate problems. The documentation on
the project really doesn't deal with 'the basics' and I believe it is
this that I am running foul of: I have read much on the web, and I
suspect that this is a classpath issue, but I can't see what I'm doing
wrong.

And I'm confident that the path I specify is ok

The error I get is

"Package myclass.HelloWorld is not Callable"

but I suspect that this is, infact, telling me that the class
HelloWorld could not be found.

If so - why not? - Note that using java

Here's my python code snippet

from jpype import *

startJVM(getDefaultJVMPath(), "-ea", "-Djava.class.path=D:/tmp/jpype-
reli/test/dist/test.jar'' )

package = JPackage("myclass")
x = package.HelloWorld()
x.do_a_message()

shutdownJVM()

I have a java class called HelloWorld in package "myclass" which
resides in test.jar. The source is below:

package myclasses;

public class HelloWorld
{

/** Creates a new instance of HelloWorld */
public HelloWorld()
{
}

public void message()
{
System.out.println("Hello, World");
}

public static void do_a_message()
{
System.out.println("Static Hello, World");
}
}

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


Re: Getting started with JPype

2007-08-13 Thread porter
Gah - I hate it when that happens: Just after posting I figured out my
silly mistake: my package is called myclasses and I was referencing
'myclass'

apologies for wasting your time




> Hi,
>
> For nefarious javaesque reasons I've been trying to get started with
> jpype (http://jpype.sourceforge.net). This looks like a potentially
> useful tool for integrating java classes into C-python, but
> frustratingly I've run into immediate problems. The documentation on
> the project really doesn't deal with 'the basics' and I believe it is
> this that I am running foul of: I have read much on the web, and I
> suspect that this is a classpath issue, but I can't see what I'm doing
> wrong.
>
> And I'm confident that the path I specify is ok
>
> The error I get is
>
> "Package myclass.HelloWorld is not Callable"
>
> but I suspect that this is, infact, telling me that the class
> HelloWorld could not be found.
>
> If so - why not? - Note that using java
>
> Here's my python code snippet
>
> from jpype import *
>
> startJVM(getDefaultJVMPath(), "-ea", "-Djava.class.path=D:/tmp/jpype-
> reli/test/dist/test.jar'' )
>
> package = JPackage("myclass")
> x = package.HelloWorld()
> x.do_a_message()
>
> shutdownJVM()
>
> I have a java class called HelloWorld in package "myclass" which
> resides in test.jar. The source is below:
>
> package myclasses;
>
> public class HelloWorld
> {
>
> /** Creates a new instance of HelloWorld */
> public HelloWorld()
> {
> }
>
> public void message()
> {
> System.out.println("Hello, World");
> }
>
> public static void do_a_message()
> {
> System.out.println("Static Hello, World");
> }
>
> }


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


Processing Game Help

2017-12-10 Thread Lauren Porter
Hello all! I've been trying to create a game in Python Processing where a 
spaceship moves horizontally in order to miss a collision with an asteroid. I'm 
having difficulty making it so that the game quits when an asteroid hits the 
spaceship, could anybody help? Here is my code. As you can see, I tried using 
globals in order use variables from previous classes, but nothing has worked. 
For this specific approach, no error message popped up, but nothing happened 
either. Thanks so much!

COLORS = {"black":"#00", "white":"#FF",
  "red":"#FF", "green":"#00FF00",
  "blue":"#D1F5FF", "yellow":"#00",
  "orange":"#FFA500", "hendrixorange":"#F58025",
  "purple":"#9B30FF", "gray":"#808080", "lightgray": "#CACACA",
  "darkgray":"#A9A9A9"}
import random
asteroid = []
spaceship = []
stars = []
justPressed = False
aX = 0
aY = 0
x = 0
y = 0

def setup():
global aX, aY, X, Y
size(640, 480)
for s in range(1):
X = 320
Y = 440
spaceship.append(Space(X, Y, COLORS["orange"]))
for a in range(4):
aX = random.randint(0, 640)
aY = 0
asteroid.append(Asteroid(aX, aY, COLORS["orange"]))
for d in range(100):
randX = random.randint(0, 640)
randY = random.randint(0, 480)
stars.append(Star(randX, randY, COLORS["orange"]))



class Space:
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color   

def spaceship(self):
fill(COLORS["blue"])
stroke(COLORS["white"])
ellipse(self.x, self.y, 75, 75) #body
fill(COLORS["green"])
fill(COLORS["gray"])
stroke(COLORS["green"])
ellipse(self.x, self.y + 20, 120, 35)
stroke(COLORS["orange"])
fill(COLORS["purple"])
ellipse(self.x, self.y + 20, 10, 10)
ellipse(self.x + 30, self.y + 20, 10, 10)
ellipse(self.x - 30, self.y + 20, 10, 10)

def move(self, dx, dy):
self.x += dx
self.y += dy

class Asteroid:
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color

def update(self):
self.velx = 0
self.vely = random.randint(1, 5)
self.x += self.velx
self.y += self.vely
if self.y > 480:
self.y = 0
self.x = random.randint(1,640)

def asteroid(self):
fill(COLORS["lightgray"])
stroke(COLORS["white"])
ellipse(self.x, self.y, 50, 50)
fill(COLORS["gray"])
ellipse(self.x +15, self.y + 6, 15, 15)
ellipse(self.x -12, self.y + 7, 10, 10)
ellipse(self.x + 5, self.y - 13, 11, 11)
ellipse(self.x - 12, self.y - 9, 7, 7)
ellipse(self.x + 2, self.y + 18, 7, 7)

class Star:
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color   

def star(self):
fill(COLORS["white"])
ellipse(self.x, self.y, 3, 3)


def draw():
global justPressed
background(COLORS["black"])
for f in stars:
f.star()
for f in spaceship:
f.spaceship()
if f.x < 60:
f.move(3, 0)
elif f.x > 580:
f.move(-3, 0)
elif justPressed :
if key == 'd':
f.move(3, 0)
elif key == 'a':
f.move(-3, 0)
for f in asteroid:
f.asteroid() 
f.update()
#collision detection 'for' loop
distance = sqrt(((aX - X)**2) + ((aY - Y)**2))
for f in asteroid:
if distance < 62.5:
background(COLORS["red"])


def keyTyped():
global justPressed
justPressed = True
print("typed", key)

def keyPressed():
global justPressed
justPressed = True
print("pressed", key)

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


Dynamic Loading Modules

2009-01-17 Thread Riley Porter
Hello all,

This is the first time I have posted to this group.  That being said if I am
in the wrong place for this kind of support please let me know.

OK,

So I am writing a log parsing program and wish to allow for the community to
write "parsers".  Basically, what I have in place now is a "modules"
directory that contains .py files that are going to be used to parse
specific log types.

The question is, is there a way to dynamically import whatever is in that
modules directory and make is to the import name is actually the file name..

So after the modules directory is 'os.listdir' and it returns a listing of
modules (actually just .py files) IE: ng1-fw.py, cisco_asa_fw.py, etc... I
can just in the next line of code call:

ng1-fw.Parse(long_file)  #assuming the ng1-fw.py file has a Parse Function

right now using imp I got it to where i can say like:
x =  imp.load_source(md5.new(code_path).hexdigest(), code_path, f)
#assuming that I gave it the path and filename for ng1-fw.py
I can do this:

x.Parse(log_file)

But what I am really after is the ability to do this:
ng1-fw.Parse(log_file)

The reason again behind this is so that there is no need to "hard code"
parser file names.

Did I make myself clear?  Please let me know if I need to explain that
better.

Thanks !
-- 
Riley Porter
Network Security Engineer

Offensive Security - OSCP
SANS GIAC - GCIH
CCNA, Security+
ACSA - Arcsight Security Analyst
--
http://mail.python.org/mailman/listinfo/python-list


Compress a string

2008-05-18 Thread Matt Porter

Hi guys,

I'm trying to compress a string.
E.g:
 "BBBC" -> "ABC"

The code I have so far feels like it could be made clearer and more  
succinct, but a solution is currently escaping me.



def compress_str(str):
new_str = ""
for i, c in enumerate(str):
try:
if c != str[i+1]:
new_str += c
except IndexError:
new_str += c
return new_str


Cheers
Matt
--
--

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


Re: [EMAIL PROTECTED]: Re: Compress a string]

2008-05-18 Thread Matt Porter
On Sun, 18 May 2008 19:13:57 +0100, J. Clifford Dyer  
<[EMAIL PROTECTED]> wrote:


On Sun, May 18, 2008 at 07:06:10PM +0100, Matt Porter wrote regarding  
Compress a string:


Hi guys,

I'm trying to compress a string.
E.g:
 "BBBC" -> "ABC"

The code I have so far feels like it could be made clearer and more
succinct, but a solution is currently escaping me.


def compress_str(str):
new_str = ""
for i, c in enumerate(str):
try:
if c != str[i+1]:
new_str += c
except IndexError:
new_str += c
return new_str


Cheers
Matt


def compress_str(s):
# str is a builtin keyword. Don't overload it.
out = []
for c in s:
if out and c == out[-1]:
out.append(c) # This is faster than new_str += c
return ''.join(out)




Thanks. Had to change a few bits to make it behave as I expected:

def compress_str(s):
# str is a builtin keyword. Don't overload it.
out = [s[0],]
for c in s:
if out and c != out[-1]:
out.append(c) # This is faster than new_str += c
return ''.join(out)

Feels slightly less hacked together



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





--
--

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


Re: Compress a string

2008-05-18 Thread Matt Porter

On Sun, 18 May 2008 20:30:57 +0100, Peter Otten <[EMAIL PROTECTED]> wrote:


Matt Porter wrote:


I'm trying to compress a string.
E.g:
  "BBBC" -> "ABC"


Two more:


from itertools import groupby
"".join(k for k, g in groupby("aabbcc"))

'abc'


import re
re.compile(r"(.)\1*").sub(r"\1", "aaa")

'abc'



Brilliant - I was trying to figure out how to do this with the re  
capabilities.


Thanks to everyone


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





--
--

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


Re: License selection for free software

2008-05-06 Thread Matt Porter

On Tue, 06 May 2008 20:02:21 +0100, Paul Rubin
<"http://phr.cx"@nospam.invalid> wrote:


[EMAIL PROTECTED] (Ville M. Vainio) writes:
[EMAIL PROTECTED] (Ville M. Vainio) writes:

I don't think BSD/MIT like license really annoys anyone. Think python
here ;-)


Python's non-GPL license certainly is annoying to some of us.


I'm intrigued - how can it be annoying?


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





--
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/

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


sometype.__new__ and C subclasses

2010-05-01 Thread James Porter
I've been trying to write a Python C extension module that uses NumPy 
and has a subtype of numpy.ndarray written in C. However, I've run into 
a snag: calling numpy.ndarray.__new__(mysubtype, ...) triggers an 
exception in the bowels of Python (this is necessary for a handful of 
NumPy features). I'm posting to this list to try to figure out why this 
exception exists in the first place, and what (if anything) I can do to 
work around it.


The exception in question happens in Objects/typeobject.c in 
tp_new_wrapper. Here's the comment for the block:


/* Check that the use doesn't do something silly and unsafe like
   object.__new__(dict).  To do this, we check that the
   most derived base that's not a heap type is this type. */

The code has the end effect that basetype.__new__(subtype, ...) fails 
whenever subtype is a statically-defined type (i.e. a normal C extension 
type object). Why is this necessary in general? I can see why it might 
be bad for a limited number of core Python types, but it seems 
unnecessarily limiting for Python C extensions.


On a more practical note, is there a way (short of rewriting the subtype 
in Python) to work around this? It seems that I could call the type 
metaclass to create a heap type in C, but I'm not sure of all the 
implications of that.


Thanks in advance,
Jim

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


Re: sometype.__new__ and C subclasses

2010-05-02 Thread James Porter

On 5/2/2010 4:34 AM, Carl Banks wrote:

Why don't you use mysubtype.__new__(mysubtype,...)?

If you wrote mysubtype in C, and defined a different tp_new than
ndarray, then this exception will trigger.  And it ought to; you don't
want to use ndarray's tp_new to create an object of your subclass, if
you've defined a different tp_new.


Unfortunately, I can't do that, since that call is in NumPy itself and 
it's part of their "standard" way of making instances of subclasses of 
ndarray. Functions like numpy.zeros_like use ndarray.__new__(subtype, 
...) to create new arrays based on the shape of other arrays.


The Python version of the subclass is shown here: 
, 
and I'm trying to write something pretty similar in C. I'm trying to 
stay in C since everything else is in C, so it's easier to stay in C 
then to jump back and forth all the time.


Maybe the real answer to this question is "NumPy is doing it wrong" and 
I should be on their list; still, it seems strange that the behavior is 
different between Python and C.


- Jim

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


Re: sometype.__new__ and C subclasses

2010-05-02 Thread James Porter

On 5/2/2010 1:43 PM, Robert Kern wrote:

Perhaps things would be clearer if you could post the C code that you've
written that fails. So far, you've only alluded at what you are doing
using Python-syntax examples.


I'm not sure how much this will help, but here you go. The actual C code 
probably doesn't matter except for where I set tp_flags, tp_new, and 
register the type, but I included it for completeness. The full C source 
is available here if you need it, but be warned that other strangeness 
abounds in the code: 
.


Obviously, this is kind of a bizarre case, so I'm not entirely sure what 
the best route is here.


Thanks,
Jim

static PyObject*
iMeshArrObj_new(PyTypeObject *cls,PyObject *args,PyObject *kw)
{
static char *kwlist[] = {"object","instance",0};

PyObject *obj;
iMesh_Object *instance = NULL;
PyObject *arr = NULL;
iMeshArr_Object *self;

if(!PyArg_ParseTupleAndKeywords(args,kw,"O|O!",kwlist,&obj,
&iMesh_Type,&instance))
return NULL;

arr = PyArray_FROM_O(obj);
if(arr == NULL)
return NULL;

self = (iMeshArr_Object*)PyObject_CallMethod(arr,"view","O",cls);
Py_DECREF(arr);
if(self == NULL)
return NULL;

/* some boring stuff to set |instance| */

return self;
}

static void
iMeshArrObj_dealloc(iMeshArr_Object *self)
{
Py_XDECREF(self->instance);
self->array.ob_type->tp_free((PyObject*)self);
}

static PyObject*
iMeshArrObj_finalize(iMeshArr_Object *self,PyObject *args)
{
iMeshArr_Object *context;
if(PyArg_ParseTuple(args,"O!",&iMeshArr_Type,&context))
{
self->instance = context->instance;
Py_XINCREF(self->instance);
}
PyErr_Clear();
Py_RETURN_NONE;
}

static PyMethodDef iMeshArrObj_methods[] = {
{ "__array_finalize__", (PyCFunction)iMeshArrObj_finalize,
  METH_VARARGS, ""
},
{0}
};

static PyMemberDef iMeshArrObj_members[] = {
{"instance", T_OBJECT_EX, offsetof(iMeshArr_Object, instance),
 READONLY, "base iMesh instance"},
{0}
};

static PyTypeObject iMeshArr_Type = {
PyObject_HEAD_INIT(NULL)
/* ... */
(destructor)iMeshArrObj_dealloc,  /* tp_dealloc */
/* ... */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
"iMesh array objects",/* tp_doc */
/* ... */
iMeshArrObj_methods,  /* tp_methods */
iMeshArrObj_members,  /* tp_members */
/* ... */
iMeshArrObj_new,  /* tp_new */
};

PyMODINITFUNC initiMesh(void)
{
PyObject *m;
m = Py_InitModule("iMesh",module_methods);
import_array();

iMeshArr_Type.tp_base = &PyArray_Type;  
if(PyType_Ready(&iMeshArr_Type) < 0)
return;
Py_INCREF(&iMeshArr_Type);
PyModule_AddObject(m,"Array",(PyObject *)&iMeshArr_Type);
}

/* End C code */

And then in Python:

A = iMesh.Array(numpy.array([1,2,3,4,5]), instance=mesh)
numpy.zeros_like(A) # fails here

Inside NumPy, zeros_like looks like this (there's a bit more than this, 
but it's irrelevant to this problem):


def zeros_like(a):
if isinstance(a, ndarray):
res = ndarray.__new__(type(a), a.shape, a.dtype,
  order=a.flags.fnc)
res.fill(0)
return res

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


Re: sometype.__new__ and C subclasses

2010-05-02 Thread James Porter

On 5/2/2010 3:58 PM, Robert Kern wrote:

Well, I think we can change zeros_like() and the rest to work around
this issue. Can you bring it up on the numpy mailing list?

def zeros_like(a):
if isinstance(a, ndarray):
res = numpy.empty(a.shape, a.dtype, order=a.flags.fnc)
res.fill(0)
res = res.view(type(a))
return res
...


I'm having difficulty posting to the NumPy list (both via gmane and 
email) so I'm just going to put this here so it doesn't get lost. 
zeros_like probably needs to call __array_finalize__ for this to work 
properly (it'll cause a segfault for me otherwise):


 def zeros_like(a):
 if isinstance(a, ndarray):
 res = numpy.zeros(a.shape, a.dtype, order=a.flags.fnc)
 res = res.view(type(a))
 res.__array_finalize__(a)
 return res
 ...

- Jim

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


Re: [Fwd: Re: hex string to hex value]

2005-11-22 Thread Brett g Porter
tim wrote:
> 
> I end up with 66 again, back where I started, a decimal, right?
> I want to end up with 0x42 as being a hex value, not a string, so i can 
> pas it as an argument to a function that needs a hex value.
> (i am trying to replace the 0x42 in the line  midi.note_off(channel=0, 
> note=0x42) with a variable)


As far as Python is concerned, 66 decimal and 42 hex are exactly the 
same thing. There's absolutely no difference in calling

note_off(0x42)
and

note_off(66)

See:

 >>> def f(c):
...print c
...
 >>> f(66)
66
 >>> f(0x42)
66
 >>>



-- 
//  Today's Oblique Strategy (© Brian Eno/Peter Schmidt):
//  Repetition is a form of change
//  Brett g Porter * [EMAIL PROTECTED]

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


Re: Mutability of function arguments?

2005-12-07 Thread Brett g Porter
ex_ottoyuhr wrote:
> I'm trying to create a function that can take arguments, say, foo and
> bar, and modify the original copies of foo and bar as well as its local
> versions -- the equivalent of C++ funct(&foo, &bar).
> 
> I've looked around on this newsgroup and elsewhere, and I gather that
> this is a very common concern in Python, but one which is ordinarily
> answered with "No, you can't. Neat, huh?" A few websites, newsgroup
> posts, etc. have recommended that one ask for a more "Pythonic" way of
> doing things; so, is there one, or at least one that doesn't involve
> using objects as wrappers for mutable arguments?
> 
> And, indeed, would that approach work? Would declaring:
> 
> class FooWrapper :
> __init__(fooToLoad) :
> self.foo = fooToLoad
> 
> mean that I could now declare a FooWrapper holding a foo, pass the
> FooWrapper to a function, and have the function conclude with the foo
> within the FooWrapper now modified?

Well, you can test it yourself:

 >>> class wrapper(object):
...def __init__(self, val):
...   self.val = val
...
 >>> w = wrapper(42)
 >>> w.val
42
 >>> def foo(w):
...w.val = 11
...
 >>> foo(w)
 >>> w.val
11
 >>>

> 
> Thanks in advance for everyone's time; I hope I'm comprehensible.

You're comprehensible, but I think that you're also thinking in C++.
The object model that Python follows is very different --  instead of
thinking of assignment meaning
"Stick this value into this named location", you need to switch to 
thinking of assignment as meaning "stick this name onto that object 
until I tell you otherwise".

If you're trying to return multiple values from a function, Python lets 
you do that

 >>> def multiFoo(x, y, z):
...return x*2, y*2, z*2
...
 >>> x = 1
 >>> y = 2
 >>> z = 3
 >>> x, y, z = multiFoo(x, y, z)
 >>> x
2
 >>> y
4
 >>> z
6
 >>>
-- 
//  Today's Oblique Strategy (© Brian Eno/Peter Schmidt):
//  Repetition is a form of change
//  Brett g Porter * [EMAIL PROTECTED]

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


Re: How to compare files

2005-07-01 Thread Brett g Porter
Lad wrote:
> Hi,
> What is the best method for comparing two files by words?
> I was thinking about reading files by words and compare them but a word
> in one file can be linked with a new line character ( \n)
> and this '\n' will cause that the words will considered to be
> different( eventhough without '\n' are the same)
> 
> Thanks for help.
> LAd.
> 
Have you looked at the difflib module that comes with Python?

http://docs.python.org/lib/module-difflib.html



-- 
//  Today's Oblique Strategy (© Brian Eno/Peter Schmidt):
//  Change instrument roles
//  Brett g Porter * [EMAIL PROTECTED]

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


Re: Defending Python

2005-07-13 Thread Brett g Porter
Jorey Bump wrote:
> 
> Monty Python's Flying Circus used to begin with "It's..." I had read at one 
> time that "It's" was one of the original names proposed for the 
> troupe/show, although I can't seem to find verification.  

"In fact, one of the titles of the show was 'It's', so he must have been 
in there fairly early on. On a list of titles I've got scribbled in a 
notebook was 'It's' and just 'It,' so that's probably where he came from."

   -- Michael Palin (referring to the "It's" man) in _The First 20 Years 
of Monty Python_ by Kim "Howard" Johnson (St. Martin's Press, 1989), p.20


-- 
//  Today's Oblique Strategy (© Brian Eno/Peter Schmidt):
//  Change instrument roles
//  Brett g Porter * [EMAIL PROTECTED]
//  http://bgporter.inknoise.com/JerseyPorkStore
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: First Script Problem

2005-09-16 Thread Brett g Porter
Ed Hotchkiss wrote:
> This script should just be writing every possibly IP (yea, there are 
> billions i know blah blah) to a txt file. Instead of just writing the 
> IP, it continues and the number goes past 4 groups. IE: The possible IP 
> keeps getting 3 characters longer every time. And at the end of the last 
> loops do I somehow have to set my mySet to NULL? Any ideas here? 
> 
> -- 
> edward hotchkiss
>  
>  

>  
> 
> 
> # Script to Evaluate every possible IP Address Combo, then write it to a 
> text file
> # 9/15/05
> 
> # ipFileLocation = r"G:\Python\myCode\IPList.txt"
> 
> ipFileLocation = "IPList.txt"
> ipFile = open(ipFileLocation, 'w')
> 
> def findIPs():
>  for num in range(256):
>   mySet = "%03.d" % num

okay -- at this point, on the first iteration of this outer loop, mySet 
is '000'

>   for num in range(256):
>mySet = mySet + "." + "%03.d" % num
and on the first iteration of this first inner loop, mySet is '000.000'

>for num in range(256):
> mySet = mySet + "." + "%03.d" % num
second inner loop, first iteration, mySet is '000.000.000'
> for num in range(256):
>  mySet = mySet + "." + "%03.d" % num
>  ipFile.write(mySet+"\n")

Okay -- this innermost loop will now be executed 256 times (values 
ranging from 0 to 255, and mySet just keeps getting appended to, 
creating the ever-growing output string that you see.

A better way to write this would be something like:

for octet1 in range(256):
for octet2 in range(256):
   for octet3 in range(256):
  for octet4 in range(256):
 ipAddress = '%03.d.%03.d.%03.d.%03.d\n' % (octet1, octet2, 

 octet3, octet4)
 ipFile.write(ipAddress)

...which will generate output like you're looking for:

000.000.000.000
000.000.000.001
000.000.000.002
000.000.000.003
000.000.000.004
000.000.000.005
000.000.000.006
000.000.000.007
000.000.000.008
000.000.000.009
000.000.000.010
000.000.000.011
000.000.000.012
000.000.000.013
000.000.000.014

Also note that growing strings by concatenating with '+' is going to 
create code that runs very slowly as the strings continue to grow -- 
much better to either use string formatting or the idiom of using the 
join method of list objects to create a string in a single pop once a 
list of substrings is all populated.


-- 
//  Today's Oblique Strategy (© Brian Eno/Peter Schmidt):
//  Destroy -nothing -the most important thing
//  Brett g Porter * [EMAIL PROTECTED]
//  http://bgporter.inknoise.com/JerseyPorkStore
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pattern matching with string and list

2005-12-13 Thread Brett g Porter
BartlebyScrivener wrote:
> Even without the marker, can't you do:
> 
> sentence = "the fabric is red"
> colors = ["red", "white", "blue"]
> 
> for color in colors:
> if (sentence.find(color) > 0):
> print color, sentence.find(color)
> 
That depends on whether you're only looking for whole words:

 >>> colors = ['red', 'green', 'blue']
 >>> def findIt(sentence):
...for color in colors:
...   if sentence.find(color) > 0:
...  print color, sentence.find(color)
...
 >>> findIt("This is red")
red 8
 >>> findIt("Fredrik Lundh")
red 1
 >>>

It's easy to see all the cases that this approach will fail for...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: URL 'special character' replacements

2006-01-09 Thread Brett g Porter
Claude Henchoz wrote:
> Hi guys
> 
> I have a huge list of URLs. These URLs all have ASCII codes for special
> characters, like "%20" for a space or "%21" for an exclamation mark.
> 
> I've already googled quite some time, but I have not been able to find
> any elegant way on how to replace these with their 'real' counterparts
> (" " and "!").
> 
> Of course, I could just replace(), but that seems to be a lot of work.
> 
> Thanks for any help.
> 
> Cheers, Claude
> 

The standard library module 'urllib' gies you two choices, depending on 
the exact behavior you'd like:

http://www.python.org/doc/2.3.2/lib/module-urllib.html
unquote(string)
 Replace "%xx" escapes by their single-character equivalent.

 Example: unquote('/%7Econnolly/') yields '/~connolly/'.

unquote_plus(string)
 Like unquote(), but also replaces plus signs by spaces, as required 
for unquoting HTML form values.


-- 
//  Today's Oblique Strategy (© Brian Eno/Peter Schmidt):
//  Accretion
//  Brett g Porter * [EMAIL PROTECTED]

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


Re: String handling and the percent operator

2006-07-13 Thread Brett g Porter
Justin Azoff wrote:
> Tom Plunket wrote:
>>  boilerplate = \
>> """
> [big string]
>> """
>>
>>  return boilerplate % ((module,) * 3)
>>
[deletia...]

> Of course..
> 
 stuff = {'lang': 'python', 'page': 'typesseq-strings.html'}
 print """I should read the %(lang)s documentation at
> ... http://docs.%(lang)s.org/lib/%(page)s""" % stuff
> I should read the python documentation at
> http://docs.python.org/lib/typesseq-strings.html

...or perhaps cooler:
http://docs.python.org/lib/node109.html

something like:

from string import Template

def GetPyContents(module):
boilerplate = Template( \
"""
class $moduleName:
pass

if __name__ == '__main__':
import unittest
unittest.main('${moduleName}_t')
""")

return boilerplate.substitute(moduleName=module)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: xmlrpclib and methods declared at runtime

2006-07-26 Thread Brett g Porter
squid wrote:
> 
> Based on having read the python tutorial and remembering the list of
> built-in functions, my guess would have been calling setattr in the
> constructor or after doing a listMethods operation against the XML-RPC
> server.. That is, assuming the XML-RPC service supports this api..
> something like that.. But that does not seem to be the case here, as a
> search of xmlrpclib.py does not show ANY instances of setattr being
> used. I did, however, notice some cases of classes implementing a
> __getattr__ method, which leads me to the question of how the
> interpreter performs lookup of methods when they are called. Does it
> use getattr itself? Is it possible to, say, effectively override
> getattr for a specific class, thereby returning a pointer to a generic
> function that could be used to handle... well.. everything?
> 

You seem to have gotten it. When Python can't find an attribute in an 
object's dict, it then looks for the magic __getattr__ method. If it's 
present, it passes that method the name that you're looking for. This 
lets you synthesize attributes and methods at runtime.

 >>> class Foo(object):
...def __getattr__(self, name):
...   return name.upper()
...
 >>> f = Foo()
 >>> f.test
'TEST'

With xml-rpc, a method call on your side of the connection is 
implemented by building up an XML message and sending it to the server 
-- rather than statically try to figure out what oprations the server 
supports, xmlrpclib will happily attempt to call any method name that 
you can think of, and let the server tell you if there's an error.



It's probably not a good idea to let __getattr__ handle EVERYTHING your 
class needs to do, but in cases like this where you don't know in 
advance what the class will need to handle, it lets your code hide the 
magic in a way that lets the users of your code forget that there's 
anything magic going on at all. It just looks like code.

-- 
// Brett g Porter * [EMAIL PROTECTED]
// http://www.bgporter.net/blog
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: do people really complain about significant whitespace?

2006-08-09 Thread Brett g Porter
[EMAIL PROTECTED] wrote:
> Its not the typing, its the fact that when you say the same thing
> twice, there is the potential for them to get out of sync.  If the
> method the compiler uses (braces) and the method the human uses
> (indentation) to determine what the code does don't agree, then a
> reader will be likely to misunderstand what it will actually do.  One
> of the driving principles behind Python is that, because code will be
> read more often than written, readability is more important.

Not to mention the errors that creep in when code is maintained, like 
when C code starting out as

if (i < SOME_CONSTANT)
doSomething();

gets "maintained" to

if (i < SOME_CONSTANT)
doSomething();
doSomethingDangerous();

without the programmer adding the surrounding braces. The programmer's 
intent is clear to me as a human, but the C compiler will disagree with 
me, and in this case, the compiler will be right and I'm wrong.

You can (and we do, at my company) have coding standards that mandate 
braces around single line if()s in C/C++, but that's really just 
patching around the problem (and it counts on humans being consistent).

Pushing the scutwork down onto tools is not as good a solution as 
eliminating the scutwork, especially when it shouldn't be necessary at 
all...




-- 
// Brett g Porter * [EMAIL PROTECTED]
// http://www.bgporter.net/blog
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to *Search* with google from inside my programme and get the search result?

2006-02-15 Thread Brett g Porter
I V wrote:
> Frank Potter wrote:
>> Does google supply some webservice to programmers? I did see
> 
> Googling for "google api" gets you to:
> 
> http://www.google.com/apis/
> 
> It appears to be a SOAP API, which you can access with python, but I
> think you'll need a third-party library. Googling for "python soap"
> gets you:
> 
> http://www-128.ibm.com/developerworks/library/ws-pyth5/
> 
> which might be a place to start.
> 
Or even easier:
http://pygoogle.sourceforge.net/

SUMMARY
---
This module allows you to access Google's web APIs through SOAP,
to do things like search Google and get the results programmatically.
This API is described here:
   http://www.google.com/apis/

SYSTEM REQUIREMENTS
---
Requires Python 2.0 or later

Requires the SOAPpy library from the Python Web Services project
(http://pywebsvcs.sourceforge.net).  We include an older version, but
its use is now deprecated (and will go away completely in future
releases).  Unfortunately, versions of SOAPpy prior to 0.11.3 will not
work correctly, and thus PyGoogle will fall back on the included
SOAP.py library if an earlier version is found.

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


Re: Python forum

2005-05-17 Thread Brett g Porter
Jonas Melian wrote:
> Hi,
> 
> I'm going to say a suggestion, why don't you create a forum like the one
> of Ruby (http://www.rubyforums.com/)? for the novices this is a great
> help, better than a mail list
> 
> It's also worth noting that rubyforums.com has nearly no posts (six
> total) because it takes very just a short time working.
> 
> I know that you have python-list, it's both an email and a usenet list.
> But I think that a forum is great for the learning. The test is in
> gentoo's forums. They are a lot of experienced people answering
> questions without any problem and it goes very well
> 
> Thanks

Don't forget that there's also the Tutor list (see 
http://www.python.org/mailman/listinfo/tutor ), targeted to people 
looking to learn the language...


-- 
//  Today's Oblique Strategy (© Brian Eno/Peter Schmidt):
//  Change instrument roles
//  Brett g Porter * [EMAIL PROTECTED]

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


Re: Iteration over strings

2007-07-31 Thread Brett g Porter
Robert Dailey wrote:
> Hi,
> 
> I have the following code:
> 
> str = "C:/somepath/folder/file.txt"
> 
> for char in str:
> if char == "\\":
> char = "/"
> 
> The above doesn't modify the variable 'str' directly. I'm still pretty 
> new to Python so if someone could explain to me why this isn't working 
> and what I can do to achieve the same effect I would greatly appreciate it.
> 

The thing that you need to remember is that  strings in Python never 
change (and nothing ever changes that).

Any time that you start out thinking "I need to change this string'  you 
need to immediately translate that thought into "I need to create a new 
string with some changes made to this string".

String objects can already do what you're trying to do here:

 >>> str = "C:\\somepath\\folder\\file.txt"
 >>> str
'C:\\somepath\\folder\\file.txt'
 >>> str2 = str.replace('\\', '/')
 >>> str2
'C:/somepath/folder/file.txt'
 >>> str
'C:\\somepath\\folder\\file.txt'


replace() returns a new string with all instances of the  1st subsstring 
replaced with the second substring -- note that the original string 
'str' is unmodified.

Also note that if this is your actual use  case,  the standard lib also 
contains a function os.path.normpath() that does all the correct 
manipulations to correctly normalize file paths on the current platform.

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


Re: Eureka moments in Python

2007-03-13 Thread Brett g Porter
Steven D'Aprano wrote:
> I'd be interested in hearing people's stories of Eureka moments in Python,
> moments where you suddenly realise that some task which seemed like it
> would be hard work was easy with Python.

Mine was definitely when I was first working with the xmlrpc module, and 
I was puzzled to no end how it was that I was able to make a call to a 
method of an object when that method didn't exist. All the talk about 
Python being a dynamic language had bounced off of me until that moment, 
when I walked through the __getattr__ method in the debugger and was 
enlightened.

Not surprisingly, that was also the moment when C++ started feeling like 
a straightjacket to me...

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


Re: Eureka moments in Python

2007-03-13 Thread Brett g Porter
Dustan wrote:
> On Mar 13, 10:05 am, Brett g Porter <[EMAIL PROTECTED]> wrote:
>> Steven D'Aprano wrote:
>>> I'd be interested in hearing people's stories of Eureka moments in Python,
>>> moments where you suddenly realise that some task which seemed like it
>>> would be hard work was easy with Python.
>> Mine was definitely when I was first working with the xmlrpc module, and
>> I was puzzled to no end how it was that I was able to make a call to a
>> method of an object when that method didn't exist. All the talk about
>> Python being a dynamic language had bounced off of me until that moment,
>> when I walked through the __getattr__ method in the debugger and was
>> enlightened.
>>
>> Not surprisingly, that was also the moment when C++ started feeling like
>> a straightjacket to me...
> 
> Started? Meaning there was a time when it DIDN'T feel like a
> straightjacket? If I were a journalist, this would be all over the
> news...
> 

If you're born wearing a straightjacket, I'm sure that it feels natural 
and fine until the first time someone unties it...

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


Re: Non-web-based templating system

2006-04-28 Thread Brett g Porter
Diez B. Roggisch wrote:
> [EMAIL PROTECTED] wrote:
> 
> Maybe the built-in string interpolation is sufficient?
> 
> print "Hello %(name)s" % dict(name="Peter Pan")


Or in recent pythons, the built-in string templating system (see 
http://docs.python.org/lib/node109.html)


 >>> from string import Template
 >>> d = dict(name="Barney")
 >>> s = Template("Hello $name")
 >>> s.substitute(d)
'Hello Barney'

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


Re: Python program as daemon?

2008-07-25 Thread Brett g Porter

Johny wrote:

Is it possible to run a Python program as daemon?


Sure -- see http://code.activestate.com/recipes/66012/ for an example 
(and some useful stuff in the comments.)

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


Re: Reasoning behind 'self' parameter in classes?

2008-07-30 Thread Brett g Porter

Robert Dailey wrote:


This is an example of a response I'm looking for:
"The self parameter is required because the parser is a bit old and 
needs to know the exact object you're referencing"


This is _not_ an example of what I'm looking for:
"Specifying self is a great mysterious thing that we should never 
question. Do not question the language! The language is mighty! Don't 
bring C++ to Python!"




Fredrik Lundh has written a  very clear explanation of this at 
http://effbot.org/pyfaq/why-must-self-be-used-explicitly-in-method-definitions-and-calls.htm


(or http://bit.ly/3EUiCf if you don't feel like stitching that URL back 
together...)


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


Re: Python MIDI in 2008

2008-05-06 Thread Brett g Porter

Maciej Bliziński wrote:

For the last couple of days, I've been looking for a Python midi
library. I'm generally interested in sending MIDI events via ALSA. It
seems like everything out there is pretty old; packages are from 2003
or 2005. Some packages don't seem to be really used, for instance
portmidi doesn't even support installing it system-wide; you can
compile it and... no make install for you.

I haven't used the PortMidi bindings that are in the Cheeseshop at 
http://pypi.python.org/pypi/pyPortMidi/0.0.3


but I've used PortMidi extensively from C++ code and have had excellent 
results with it.

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