Re: urlopen exception

2009-01-10 Thread alex goretoy
I would try:

site="http://www.bput.org/";
payloads="alert('xss')"
attack= urllib2.urlopen(site+payloads,80).readlines()


-Alex Goretoy
http://www.alexgoretoy.com
somebodywhoca...@gmail.com


On Sun, Jan 11, 2009 at 2:49 AM, Steve Holden  wrote:

> Paul Rubin wrote:
> > asit  writes:
> >> site="www.bput.org"
> >> payloads="alert('xss')"
> >> attack= urllib2.urlopen(site+payloads,80).readlines()
> >>
> >> according to my best knowledge, the above code is correct.
> >> but why it throws exceptio 
> >
> > The code is incorrect.  Look at the string ou are sending into
> > urlopen.  What on earth are you trying to do?
>
> He's investigating potential cross-site scripting vulnerabilities.
>
> regards
>  Steve
> --
> Steve Holden+1 571 484 6266   +1 800 494 3119
> Holden Web LLC  http://www.holdenweb.com/
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: urlopen exception

2009-01-10 Thread alex goretoy
 oops, remove the ,80 since port is not needed. Well, in my case it wasn't
working with port. notice it gives me 404, but this with my domain

>>> att=urllib2.urlopen(site+payload,80).readlines()
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/local/lib/python2.6/urllib2.py", line 124, in urlopen
return _opener.open(url, data, timeout)
  File "/usr/local/lib/python2.6/urllib2.py", line 381, in open
req = meth(req)
  File "/usr/local/lib/python2.6/urllib2.py", line 1057, in do_request_
'Content-length', '%d' % len(data))
TypeError: object of type 'int' has no len()

>>> att=urllib2.urlopen(site+payload).readlines()
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/local/lib/python2.6/urllib2.py", line 124, in urlopen
return _opener.open(url, data, timeout)
  File "/usr/local/lib/python2.6/urllib2.py", line 389, in open
response = meth(req, response)
  File "/usr/local/lib/python2.6/urllib2.py", line 502, in http_response
'http', request, response, code, msg, hdrs)
  File "/usr/local/lib/python2.6/urllib2.py", line 427, in error
return self._call_chain(*args)
  File "/usr/local/lib/python2.6/urllib2.py", line 361, in _call_chain
result = func(*args)
  File "/usr/local/lib/python2.6/urllib2.py", line 510, in
http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 404: Not Found

-Alex Goretoy
http://www.alexgoretoy.com
somebodywhoca...@gmail.com


On Sun, Jan 11, 2009 at 5:58 AM, alex goretoy
wrote:

> I would try:
>
> site="http://www.bput.org/";
> payloads="alert('xss')"
> attack= urllib2.urlopen(site+payloads,80).readlines()
>
>
> -Alex Goretoy
> http://www.alexgoretoy.com
> somebodywhoca...@gmail.com
>
>
>
> On Sun, Jan 11, 2009 at 2:49 AM, Steve Holden  wrote:
>
>> Paul Rubin wrote:
>> > asit  writes:
>> >> site="www.bput.org"
>> >> payloads="alert('xss')"
>> >> attack= urllib2.urlopen(site+payloads,80).readlines()
>> >>
>> >> according to my best knowledge, the above code is correct.
>> >> but why it throws exceptio 
>> >
>> > The code is incorrect.  Look at the string ou are sending into
>> > urlopen.  What on earth are you trying to do?
>>
>> He's investigating potential cross-site scripting vulnerabilities.
>>
>> regards
>>  Steve
>> --
>> Steve Holden+1 571 484 6266   +1 800 494 3119
>> Holden Web LLC  http://www.holdenweb.com/
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: File layout in development stage

2009-01-11 Thread alex goretoy
sys.path.append()

-Alex Goretoy
http://www.alexgoretoy.com
somebodywhoca...@gmail.com


On Mon, Jan 12, 2009 at 2:00 AM, Steven Woody  wrote:

> Hi,
>
> Adapted your kindly suggestions in a previous post,  I now decide to
> organize my source tree in a pattern like below:
>
>
> prj:
>src:
>lib:
>foomodule.py
>barmodule.py
>scripts:
>prj_main.py
> test:
> footest.py
> bartest.py
> ...
>
>
> That is, I want to put the top-level scripts in  prj/src/scripts  and
> share libraries in prj/src/lib.  In the prj/test directory I want to
> put my unit-tests using unittest module.  My question is that when in
> development stage there is  no file is actually distributed, so how
> should a python source in one directory refer to (import) another
> module in another directory?
>
> Thanks in advance.
>
> -
> narke
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


error: cannot invoke setopt() - perform() is currently running

2009-01-14 Thread alex goretoy
hello all,

I have a problem when using pycurl with threading Thread

from threading import Thread

the error i get is this:

error: cannot invoke setopt() - perform() is currently running


how do I catch a error like this in my code and perform a action like
wait for perform to finish until it tries to setopt again?

Has anyone come across this?

Any help in this matter will be highly appreciated, I've spent a week
on this and can't seem to figure it out. Googling hasn't brought me
any thing except my own codehahaha go figure TIA

-- 
-Alex Goretoy
http://www.alexgoretoy.com
somebodywhoca...@gmail.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: error: cannot invoke setopt() - perform() is currently running

2009-01-14 Thread alex goretoy
more info for all:

the class I'm trying to use threading on top of called pcrunchly. I've
posted it previously on here, but you can find it at this link.

http://article.gmane.org/gmane.comp.python.general/604050

How can i make this work with threading Thread?

On 1/15/09, alex goretoy  wrote:
> hello all,
>
> I have a problem when using pycurl with threading Thread
>
> from threading import Thread
>
> the error i get is this:
>
> error: cannot invoke setopt() - perform() is currently running
>
>
> how do I catch a error like this in my code and perform a action like
> wait for perform to finish until it tries to setopt again?
>
> Has anyone come across this?
>
> Any help in this matter will be highly appreciated, I've spent a week
> on this and can't seem to figure it out. Googling hasn't brought me
> any thing except my own codehahaha go figure TIA
>
> --
> -Alex Goretoy
> http://www.alexgoretoy.com
> somebodywhoca...@gmail.com
>


-- 
-Alex Goretoy
http://www.alexgoretoy.com
somebodywhoca...@gmail.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: error: cannot invoke setopt() - perform() is currently running

2009-01-14 Thread alex goretoy
sorry for multi posting It's a habit I have.

The closest thing I can come up with is this

http://pycurl.cvs.sourceforge.net/viewvc/pycurl/pycurl/examples/retriever-multi.py?revision=1.29&view=markup

but how to make this work with pcrunchly and threading Thread?

On 1/15/09, alex goretoy  wrote:
> more info for all:
>
> the class I'm trying to use threading on top of called pcrunchly. I've
> posted it previously on here, but you can find it at this link.
>
> http://article.gmane.org/gmane.comp.python.general/604050
>
> How can i make this work with threading Thread?
>
> On 1/15/09, alex goretoy  wrote:
>> hello all,
>>
>> I have a problem when using pycurl with threading Thread
>>
>> from threading import Thread
>>
>> the error i get is this:
>>
>> error: cannot invoke setopt() - perform() is currently running
>>
>>
>> how do I catch a error like this in my code and perform a action like
>> wait for perform to finish until it tries to setopt again?
>>
>> Has anyone come across this?
>>
>> Any help in this matter will be highly appreciated, I've spent a week
>> on this and can't seem to figure it out. Googling hasn't brought me
>> any thing except my own codehahaha go figure TIA
>>
>> --
>> -Alex Goretoy
>> http://www.alexgoretoy.com
>> somebodywhoca...@gmail.com
>>
>
>
> --
> -Alex Goretoy
> http://www.alexgoretoy.com
> somebodywhoca...@gmail.com
>


-- 
-Alex Goretoy
http://www.alexgoretoy.com
somebodywhoca...@gmail.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: ifconfig in python

2009-01-19 Thread alex goretoy
ifconfig -a|grep "inet addr"|awk '{print $2}'

wget http://myip.dk&&; cat index.html|grep "http://www.alexgoretoy.com
somebodywhoca...@gmail.com


On Tue, Jan 20, 2009 at 3:42 AM, Дамјан Георгиевски wrote:

> Something *like*  this could work:
>
>myip = 
> urllib2.urlopen('http://whatismyip.org/').read(
> )
>
> of course then you are depending on an external service, not a very
> reliable one even. But then again, you might create an internal service
> like that yourself.
>
> This cgi-bin shell code like this for ex:
>
> #! /bin/sh
> echo "Content-type: text/plain"
> echo
> echo "${REMOTE_ADDR}"
>
>
> --
> дамјан ( http://softver.org.mk/damjan/ )
>
> Spammers scratch here with a diamond to find my address:
> |||
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


PyNutButter BETA 1.0.0 - Automates CSV data Importation into any website http/https and/or mysql database

2009-01-31 Thread alex goretoy
Introducing PynutButter BETA 1.0.0

Automates csv data importation into any website. Or your money back.
Programs like this idea of a program I have here cost $2500. Pynutbutter is
opensource. You can use the code anyway you want. As long as I get my credit
where it is due. I've worked on this project for roughly 1.5 years now. This
is an idea I tried in 2 languages. PHP and python, now.

No matter how much data in your csv file.
No matter what the field names are.
No matter how data is formatted

With PyNutButter you  can parse this data in custom functions and then send
it to its destinations.
You can map all the csv file headers to fields of a html page.
It loops for each line in the csv file and imports your data.

You must configure your configuration and create custom functions that you
can call from this configuration.

I've uploaded all the main files, except my configuration(I am working on
examples and making the main project page better)

You can find this project here:

http://code.google.com/p/pynutbutter/



I've worked long and hard on this application and the idea behind it. Any
help making this tool better would be greatly appreaciated.

Please let me know what you this of this tool. Any ideas/features are also
always welcome.

I also have a presentation I am working on for this tool. I hope to find a
nice job. This tools is very powerfuls. I was think next to try it with
scapy. That would be sweet. You can add custom flavors(data parsing/sending
libraries). My goal for this tool was to make everything as dynamic as
possible. calling of functions and dealing with parsed data in functions.
Only reason why I built is because I needed a tool like this. I know someone
else woulnd't mind having a tool like this either, so here you go. If you
can please donate or something somehow.

Upcoming Features:
use of parsed data from more than one file at a time.
pyGTK for ease of configuration creation(any help?)
gui creation of custom functions
automatic form parsing based on given urls in config

-Alex Goretoy
http://www.alexgoretoy.com
somebodywhoca...@gmail.com
--
http://mail.python.org/mailman/listinfo/python-list


reconstruct html form in pyGTK window and create dict from pyGTK

2009-02-05 Thread alex goretoy
Hello All,

What would be the best way to fetch a form/s from a webpage and then
recreate it in a pygtk window?

I'm doing some research on this for a project called pynutbutter. This is
for jellpy actually, which handles creating option mappings for pynutbutter
from a GUI.
The things I know I would need some examples on:

How to work multiple glade files? (so i can have multiple pages for
different types of options) more efficient way, is this a good option?

loading of forms fields and reconstructiting in pyGTK with
comboboxes/comboboxtextentry textboxes/textentry and textviews, not how to
load them or display them...I can see that on pygtk websitebut the more
efficient way to do this dynamically.

What is the best way to create a dict from a gui? just have a user type the
dict: somedict={"some":thing} or have another window pop up that handles for
name value pairs of the dict and a field for dict name.

After all this what would be the best way for me to merge this dict into a
options file. There will be other options in there. How would I only either
prepend the new dict or if one with same name exists overwrite it. Would
that be a safe move?

What would be the most effiecient and user friendly way to contruct this on
a form basis in a pyGTK GUI

defaults = {"formfield":"somevalue","anotherfield":"somefieldvalue"}
mappings =
{"somefield":"filefield1","anotherfield":"some_function(filefield2)"}
headers = {"filefield1":"somefield","filefield2":"anotherfield"}

What would be the best way for me to construct this dict from a user
friendly form in pyGTK

Sorry this is alot of questions. Any advise on this matter will be greatly
appreciated. Thank you.


-Alex Goretoy
http://www.alexgoretoy.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Where to host a (Python) project?

2009-02-05 Thread alex goretoy
I use google code.
http://code.google.com/p/pynutbutter

-Alex Goretoy
http://www.alexgoretoy.com



On Thu, Feb 5, 2009 at 6:55 PM, Ben Finney <
bignose+hates-s...@benfinney.id.au >wrote:

> a...@pythoncraft.com (Aahz) writes:
>
> > In article <
> 6dcb8ce5-c93e-458c-9047-e5db60f27...@v18g2000pro.googlegroups.com>,
> > andrew cooke   wrote:
> > >hi, just fyi, i investigated this and you can join any publicly
> > >readable group by sending an email to the "-subscribe" address. you
> > >do not need a google login for this and, as far as i can tell, it
> > >then operates for you like a normal mailing list.
> >
> > The same thing is theoretically true for Yahoo groups, but I've
> > heard from people over the years about various difficulties fixing
> > problems with list subscriptions in the absence of a real Yahoo
> > login and I'm not particularly interested in finding out that the
> > same thing ends up being true for Google lists.
>
> Indeed it does. I have succeeded in subscribing to Google mailing
> lists in the absence of a Google account, but *managing* that
> subscription thereafter in the absence of a Google account is
> obnoxiously difficult. Your caution is well advised.
>
> --
>  \"I got fired from my job the other day. They said my |
>  `\  personality was weird. … That's okay, I have four more." |
> _o__)   —Bug-Eyed Earl, _Red Meat_ |
> Ben Finney
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Where to host a (Python) project?

2009-02-07 Thread alex goretoy
If you don't mind changing dns entries. You can also use Google App Engine.
It's really nice.

http://code.google.com/appengine/docs/python/tools/webapp/overview.html

-Alex Goretoy
http://www.alexgoretoy.com



On Fri, Feb 6, 2009 at 1:07 AM, alex goretoy wrote:

> I use google code.
> http://code.google.com/p/pynutbutter
>
> -Alex Goretoy
> http://www.alexgoretoy.com
>
>
>
>
> On Thu, Feb 5, 2009 at 6:55 PM, Ben Finney <
> bignose+hates-s...@benfinney.id.au 
> >wrote:
>
>> a...@pythoncraft.com (Aahz) writes:
>>
>> > In article <
>> 6dcb8ce5-c93e-458c-9047-e5db60f27...@v18g2000pro.googlegroups.com>,
>> > andrew cooke   wrote:
>> > >hi, just fyi, i investigated this and you can join any publicly
>> > >readable group by sending an email to the "-subscribe" address. you
>> > >do not need a google login for this and, as far as i can tell, it
>> > >then operates for you like a normal mailing list.
>> >
>> > The same thing is theoretically true for Yahoo groups, but I've
>> > heard from people over the years about various difficulties fixing
>> > problems with list subscriptions in the absence of a real Yahoo
>> > login and I'm not particularly interested in finding out that the
>> > same thing ends up being true for Google lists.
>>
>> Indeed it does. I have succeeded in subscribing to Google mailing
>> lists in the absence of a Google account, but *managing* that
>> subscription thereafter in the absence of a Google account is
>> obnoxiously difficult. Your caution is well advised.
>>
>> --
>>  \"I got fired from my job the other day. They said my |
>>  `\  personality was weird. … That's okay, I have four more." |
>> _o__)   —Bug-Eyed Earl, _Red Meat_ |
>> Ben Finney
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
>
--
http://mail.python.org/mailman/listinfo/python-list


GAE open()

2009-02-08 Thread alex goretoy
Hello,

How to open binary file for writing into datastore. I'm trying to loop over
listdir output of images directory, How to do this without using

self.request.POST.get.file.read(), or rather how to loop this task in app
engine

file(os.curdir+"somefile").read()

UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position
14: ordinal not in range(128)

but when I try to read binary with b, I get IOError.


raise IOError('invalid mode: %s' % mode)
IOError: invalid mode: b

-Alex Goretoy
http://www.alexgoretoy.com
--
http://mail.python.org/mailman/listinfo/python-list


GAE read binary file into db.BlobProperty()

2009-02-09 Thread alex goretoy
How to read Binary file into GAE(Google App Engine) db.BlobProperty()
datastore?

-Alex Goretoy
http://www.goretoy.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: GAE read binary file into db.BlobProperty()

2009-02-10 Thread alex goretoy
was not able to use open to open a binary file so what I did was use
urlfetch to fetch the image for me and read the content into BlobProperty()
Not sure why it took me so long to figure this out. Hope it helps someone.
thx

  def post(self,key):
k=db.get(key)
  img=images.Image(urlfetch.Fetch("http://www.example.com/
"+k.image).content)
  img.rotate(90)
  jpg_data= img.execute_transforms(images.JPEG)
  k.image_blob=jpg_data
  k.put()

-Alex Goretoy
http://www.goretoy.com



On Mon, Feb 9, 2009 at 11:07 AM, alex goretoy
wrote:

> How to read Binary file into GAE(Google App Engine) db.BlobProperty()
> datastore?
>
> -Alex Goretoy
> http://www.goretoy.com
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: best way to serve wsgi with multiple processes

2009-02-11 Thread alex goretoy
GAE (Google App Engine) uses WSGI for webapps. You don't have to overhead of
managing a server and all it's services this way as well. Just manage dns
entries. Although, there are limitations depending on your project needs of
what libs you need to use.

appengine.google.com

-Alex Goretoy
http://www.goretoy.com



On Wed, Feb 11, 2009 at 1:59 PM, Graham Dumpleton <
graham.dumple...@gmail.com> wrote:

> On Feb 11, 8:50 pm, Robin  wrote:
> > Hi,
> >
> > I am building some computational web services using soaplib. This
> > creates a WSGI application.
> >
> > However, since some of these services are computationally intensive,
> > and may be long running, I was looking for a way to use multiple
> > processes. I thought about using multiprocessing.Process manually in
> > the service, but I was a bit worried about how that might interact
> > with a threaded server (I was hoping the thread serving that request
> > could just wait until the child is finished). Also it would be good to
> > keep the services as simple as possible so it's easier for people to
> > write them.
> >
> > I have at the moment the following WSGI structure:
> > TransLogger(URLMap(URLParser(soaplib objects)))
> > although presumably, due to the beauty of WSGI, this shouldn't matter.
> >
> > As I've found with all web-related Python stuff, I'm overwhelmed by
> > the choice and number of alternatives. I've so far been using cherrypy
> > and ajp-wsgi for my testing, but am aware of Spawning, twisted etc.
> > What would be the simplest [quickest to setup and fewest details of
> > the server required - ideally with a simple example] and most reliable
> > [this will eventually be 'in production' as part of a large scientific
> > project] way to host this sort of WSGI with a process-per-request
> > style?
>
> In this sort of situation one wouldn't normally do the work in the
> main web server, but have a separarte long running daemon process
> embedding mini web server that understands XML-RPC. The main web
> server would then make XML-RPC requests against the backend daemon
> process, which would use threading and or queueing to handle the
> requests.
>
> If the work is indeed long running, the backend process would normally
> just acknowledge the request and not wait. The web page would return
> and it would be up to user to then somehow occassionally poll web
> server, manually or by AJAX, to see how progres is going. That is,
> further XML-RPC requests from main server to backend daemon process
> asking about progress.
>
> I do't believe the suggestions about fastcgi/scgi/ajp/flup or mod_wsgi
> are really appropriate as you don't want this done in web server
> processes as then you are at mercy of web server processes being
> killed or dying when part way through something. Some of these systems
> will do this if requests take too long. Thus better to offload real
> work to another process.
>
> Graham
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: best way to serve wsgi with multiple processes

2009-02-11 Thread alex goretoy
>
>
> GAE is definitely not suitable in this case... The servers are
>> provided and maintained as part of a large scientific project for
>> which I am providing just a few services... Other groups are running
>> services in other platforms on tomcat through soaplab/instantsoap -
>> but I was hoping to use native python services since I thought it
>> would be easier.
>>
>
OK, that's cool. I understand about project requirements. It was just a
suggestion. Nonetheless I'm still interested in what people have to say in
this thread.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Module for console text formatting?

2009-02-18 Thread alex goretoy
I created a little script for doing stdout coloring for me a while back.
Maybe this will get you closer to what you are looking for. It's kinda
hackish, but it works.

http://code.google.com/p/python-stdout-colors/

-Alex Goretoy
http://www.goretoy.com



On Wed, Feb 18, 2009 at 10:22 PM, srinivasan srinivas <
sri_anna...@yahoo.co.in> wrote:

> Hi,
> Is it possible to apply more than one formatting to a string?
> For ex: the string 'test' has to be underlined and it should be bold. How
> to do that?
>
> Thanks,
> Srini
>  --
> *From:* geremy condra 
> *To:* python-list@python.org
> *Sent:* Wednesday, 18 February, 2009 10:04:34 AM
> *Subject:* Re: Python Module for console text formatting?
>
> You can insert those codes just like you would any other character. If
> there's enough interest I can whip up a wrapper library for you.
>
> http://www.linux.gr/cgi-bin/man2html?console_codes+4
>
> On Tue, Feb 17, 2009 at 11:19 PM, srinivasan srinivas <
> sri_anna...@yahoo.co.in> wrote:
>
>>
>> Hi,
>> Does anyone know any python module other than 'ConsoleFormat0.1.1' used to
>> format text on console?
>> For example, printing bold characters on console.
>>
>> Thanks,
>> Srini
>>
>>
>>  Did you know? You can CHAT without downloading messenger. Go to
>> http://in.webmessenger.yahoo.com/
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
>
>
> --
> OpenMigration LLC- Open Source solutions for your business. Visit us at
> http://OpenMigration.net <http://openmigration.net/>.
>
> --
> Add more friends to your messenger and enjoy! Invite them 
> now.<http://in.rd.yahoo.com/tagline_messenger_6/*http://messenger.yahoo.com/invite/>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Explanation for trailing comma in example from Learning Python?

2009-02-19 Thread alex goretoy
Thank you for clerification Christian,
when using trailing comma with print statement/function, does it not mean to
output newline after printed data?

-Alex Goretoy
http://www.goretoy.com



On Thu, Feb 19, 2009 at 2:54 PM, Christian Heimes  wrote:

> Carl Schumann wrote:
> > I could see the logic in always or never having a trailing comma.   What
> > I don't understand here is why only the single element case has a
> > trailing comma.   Any explanations please?
>
> Does this code shad some light on the trailing comma? :)
>
> >>> (1) == 1
> True
> >>> (1,) == 1
> False
> >>> type((1))
> 
> >>> type((1,))
> 
>
> >>> a = 1
> >>> a
> 1
> >>> a = (1)
> >>> a
> 1
> >>> a = (1,)
> >>> a
> (1,)
> >>> a = 1,
> >>> a
> (1,)
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


parsing csv files class

2008-12-27 Thread alex goretoy
Hello All,

I have this class that I use in one of my projects. I know it's missing
functionality and some things could have been done differently. Can you ehlp
me make this class better? What can I do to make it more resistant to error?
You can find the stdout_colours class on Google if you want it, JFGI I want
to make it more pythonic. I come from a PHP background, can you tell?

Any and all help is appreciated
-Alex

#!/usr/bin/env python
from ctypes import *
import os, sys, types, csv, urllib, urllib2, urlparse, string,stdout_colours

class parsercsvy(object):
"""Return a line from a csv file or total amount of lines"""
def __init__(self,file_name=""):
self.func_me_color="white_on_black"
self.soc=stdout_colours.stdout_colors()
self.soc.me_him(['ENTER:',__name__],self.func_me_color)
self.filename = file_name
self.buffer = []
self.bufferp= []
if string.find(self.filename,"http") != -1:
resp=urllib2.urlopen(self.filename)
file=resp.read()
lfi=len(string.split(self.filename,"/"))
filename = "/tmp/"+string.split(self.filename,"/")[lfi-1]
f=open(filename,"w")
f.write(file)
f.close
self.parse(self.filename)
else:
self.parse(self.filename)
self.soc.me_him(['EXIT:',__name__],self.func_me_color)
def parse(self,filename,ret=0):
self.soc.me_him(['ENTER:',__name__],self.func_me_color)
i = 0
try:
reader = csv.reader(file(filename, "rb"))
try:
for row in reader:
self.buffer.append(row)
s,a=[],{}

for j in range(len(self.buffer[0])):
a[self.buffer[0][j]]=row[j]
self.bufferp.append(a)
i+=1
self.total = i-1
except csv.Error, e:
sys.exit('file %s, line %d: %s' % (filename,
reader.line_num, e))
except IOError, e:
sys.exit('file %s, IOError: %s' % (filename, e))
self.soc.me_him(['EXIT:',__name__],self.func_me_color)
def index(self, index):
"""return line for index"""
self.soc.me_him(['ENTER:',__name__],self.func_me_color)

self.soc.me_him(['RETURN:',self.buffer[int(index)],__name__],self.func_me_color)
return self.buffer[int(index)]
def total(self):
"""return total number of lines in csv file"""
self.soc.me_him(['ENTER:',__name__],self.func_me_color)
self.soc.me_him(['RETURN:',self.total,__name__],self.func_me_color)
return self.total
def header(self):
"""return csv header == line 0"""
self.soc.me_him(['ENTER:',__name__],self.func_me_color)

self.soc.me_him(['RETURN:',self.buffer[0],__name__],self.func_me_color)
return self.buffer[0]
def find_and_replace(self,li,fi,re):
"""
find and replace a string inside a string, return list
find_and_replace(list,find,replace)
"""
this=[]
for l in li:
#found_index=string.find(l,fi)
this.append(l.replace(fi,re))
return this
def return_buffer(self):
self.soc.me_him(['ENTER:',__name__],self.func_me_color)
self.soc.me_him(['RETURN:',self.buffer,__name__],self.func_me_color)
return self.buffer
if __name__ == "__main__":
if len(sys.argv) < 1:
print "Usage: %s file"% sys.argv[0]
f=sys.argv[1]
c=csv_parser(f)
print c.bufferp
-- 
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
--
http://mail.python.org/mailman/listinfo/python-list


Re: parsing csv files class

2008-12-27 Thread alex goretoy
I know it's messy with all those self.soc.* functions, but it works in one
of my current project. I just want to make it more pythonic I also want to
add capability for makeing csv file if I give it input like:
1234,something nice, hey this is something nice
2468,something else, something else

On Sat, Dec 27, 2008 at 4:54 AM, alex goretoy
wrote:

> Hello All,
>
> I have this class that I use in one of my projects. I know it's missing
> functionality and some things could have been done differently. Can you ehlp
> me make this class better? What can I do to make it more resistant to error?
> You can find the stdout_colours class on Google if you want it, JFGI I want
> to make it more pythonic. I come from a PHP background, can you tell?
>
> Any and all help is appreciated
> -Alex
>
> #!/usr/bin/env python
> from ctypes import *
> import os, sys, types, csv, urllib, urllib2, urlparse,
> string,stdout_colours
>
> class parsercsvy(object):
> """Return a line from a csv file or total amount of lines"""
> def __init__(self,file_name=""):
> self.func_me_color="white_on_black"
> self.soc=stdout_colours.stdout_colors()
> self.soc.me_him(['ENTER:',__name__],self.func_me_color)
> self.filename = file_name
> self.buffer = []
> self.bufferp= []
> if string.find(self.filename,"http") != -1:
> resp=urllib2.urlopen(self.filename)
> file=resp.read()
> lfi=len(string.split(self.filename,"/"))
> filename = "/tmp/"+string.split(self.filename,"/")[lfi-1]
> f=open(filename,"w")
> f.write(file)
> f.close
> self.parse(self.filename)
> else:
> self.parse(self.filename)
> self.soc.me_him(['EXIT:',__name__],self.func_me_color)
> def parse(self,filename,ret=0):
> self.soc.me_him(['ENTER:',__name__],self.func_me_color)
> i = 0
> try:
> reader = csv.reader(file(filename, "rb"))
> try:
> for row in reader:
> self.buffer.append(row)
> s,a=[],{}
>
> for j in range(len(self.buffer[0])):
> a[self.buffer[0][j]]=row[j]
> self.bufferp.append(a)
> i+=1
> self.total = i-1
> except csv.Error, e:
> sys.exit('file %s, line %d: %s' % (filename,
> reader.line_num, e))
> except IOError, e:
> sys.exit('file %s, IOError: %s' % (filename, e))
> self.soc.me_him(['EXIT:',__name__],self.func_me_color)
> def index(self, index):
> """return line for index"""
> self.soc.me_him(['ENTER:',__name__],self.func_me_color)
>
> self.soc.me_him(['RETURN:',self.buffer[int(index)],__name__],self.func_me_color)
> return self.buffer[int(index)]
> def total(self):
> """return total number of lines in csv file"""
> self.soc.me_him(['ENTER:',__name__],self.func_me_color)
> self.soc.me_him(['RETURN:',self.total,__name__],self.func_me_color)
> return self.total
> def header(self):
> """return csv header == line 0"""
> self.soc.me_him(['ENTER:',__name__],self.func_me_color)
>
> self.soc.me_him(['RETURN:',self.buffer[0],__name__],self.func_me_color)
> return self.buffer[0]
> def find_and_replace(self,li,fi,re):
> """
> find and replace a string inside a string, return list
> find_and_replace(list,find,replace)
> """
> this=[]
> for l in li:
> #found_index=string.find(l,fi)
> this.append(l.replace(fi,re))
> return this
> def return_buffer(self):
> self.soc.me_him(['ENTER:',__name__],self.func_me_color)
>
> self.soc.me_him(['RETURN:',self.buffer,__name__],self.func_me_color)
> return self.buffer
> if __name__ == "__main__":
> if len(sys.argv) < 1:
> print "Usage: %s file"% sys.argv[0]
> f=sys.argv[1]
> c=csv_parser(f)
> print c.bufferp
> --
> А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
> а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
>



-- 
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
--
http://mail.python.org/mailman/listinfo/python-list


Re: parsing csv files class

2008-12-27 Thread alex goretoy
It's main concern is to grab the file into the buffer for use in other
classes. The self.soc.me_him is just so I know when its ENTERING or EXITING
in that function when I run it in terminal. It's prints it in color. My main
concern right now is to add error handling. I'm still learning how to use
assert and yield, but I got try,except down pat.  All this class does is
grabs the file either from http or local storage into a buffer and I use
that in other classes. I want to add support for creating creating csv as
well. I read the doc on csv and  will try some things out soon. Thanks for
helping me.


On Sat, Dec 27, 2008 at 2:15 PM, Gabriel Genellina
wrote:

> En Sat, 27 Dec 2008 11:02:13 -0200, Gary M. Josack 
> escribió:
>
>> alex goretoy wrote:
>>
>
>  I know it's messy with all those self.soc.* functions, but it works in one
>>> of my current project. I just want to make it more pythonic I also want to
>>> add capability for makeing csv file if I give it input like:
>>> 1234,something nice, hey this is something nice
>>> 2468,something else, something else
>>>
>>
> reader = csv.reader(file(filename, "rb"))
>>>try:
>>>for row in reader:
>>>self.buffer.append(row)
>>>s,a=[],{}
>>>
>>
>  Do you know that there is a csv module in the standard library already?
>>
>
> I'd say he already knows, he even used it in the code.
>
> To Alex G.: I didn't understand what's the purpose of this class. Probably
> you want to do too much things in the same place; looks like it has multiple
> concerns, and that's not a good idea usually.
>
> --
> Gabriel Genellina
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я



-- 
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
--
http://mail.python.org/mailman/listinfo/python-list


Re: parsing csv files class

2008-12-27 Thread alex goretoy
I might as well add a UnicodeReader and UnicodeWriter and support for
passing delimiter in from other classes.  At the same time. Anyone have a
good csv class I can pick thru? I'm planning on posting my mysql adn curl
classes that I use in my projects I just want to make them better and have
less error.

On Sat, Dec 27, 2008 at 5:18 PM, alex goretoy
wrote:

> It's main concern is to grab the file into the buffer for use in other
> classes. The self.soc.me_him is just so I know when its ENTERING or EXITING
> in that function when I run it in terminal. It's prints it in color. My main
> concern right now is to add error handling. I'm still learning how to use
> assert and yield, but I got try,except down pat.  All this class does is
> grabs the file either from http or local storage into a buffer and I use
> that in other classes. I want to add support for creating creating csv as
> well. I read the doc on csv and  will try some things out soon. Thanks for
> helping me.
>
>
> On Sat, Dec 27, 2008 at 2:15 PM, Gabriel Genellina  > wrote:
>
>> En Sat, 27 Dec 2008 11:02:13 -0200, Gary M. Josack 
>> escribió:
>>
>>> alex goretoy wrote:
>>>
>>
>>  I know it's messy with all those self.soc.* functions, but it works in
>>>> one of my current project. I just want to make it more pythonic I also want
>>>> to add capability for makeing csv file if I give it input like:
>>>> 1234,something nice, hey this is something nice
>>>> 2468,something else, something else
>>>>
>>>
>> reader = csv.reader(file(filename, "rb"))
>>>>try:
>>>>for row in reader:
>>>>self.buffer.append(row)
>>>>s,a=[],{}
>>>>
>>>
>>  Do you know that there is a csv module in the standard library already?
>>>
>>
>> I'd say he already knows, he even used it in the code.
>>
>> To Alex G.: I didn't understand what's the purpose of this class. Probably
>> you want to do too much things in the same place; looks like it has multiple
>> concerns, and that's not a good idea usually.
>>
>> --
>> Gabriel Genellina
>>
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
>
>
> --
> А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
> а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
>
>
>
> --
> А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
> а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
>



-- 
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
--
http://mail.python.org/mailman/listinfo/python-list


how to make a class to get all forms and input fields from webpage

2008-12-27 Thread alex goretoy
Hello All,

How do I make a class for retrieving all forms and input fields on a web
page. Meaning, form name, form url,all input fields,
text,textarea,select,etc...I have something currently and it kinda works. It
also kinda works for retrieving all images on webpages. My main concer here
is to make is retrive forms and input fields into a dict that has this kinda
of outline: Maybe not exactly like this, but something to this nature. So I
can use it in other classes.

forms=
{"name":{"url":{"""input_name1":"","input_name_2","select_input":{"value1":"","value2":"selected","value3":""

This is what I have made a long time ago, I haven't touched it in a while,
but I need to make it work with some other classes. I need tit to receive
all forms and inputs for me. What is a more efficient way to do this? My
background is in PHP and I want to extend my python knowledge. I came up
with this script by Googling something a long time ago and making
modifications and additions to it. You can find the stdout_colours class on
line, JFGI. It's allows for display of caller and called function and colors
output to terminal. Thanks for your help my friends.

#!/usr/bin/python
import urllib, urllib2
import re, sys,string
import os, sys, Image
from sgmllib import SGMLParser
from urlparse import urlparse
import stdout_colours
class URLPacker(SGMLParser):

def __init__(self,colorize,caller):
self.colorize=colorize
self.caller=caller
self.reset()
def reset(self):
SGMLParser.reset(self)
self.func_me_color="white_on_black"

self.soc=stdout_colours.stdout_colors(self.colorize,self.caller)
self.soc.me_him(['ENTER:',__name__],self.func_me_color)

self.urls = {}
self.imgs = {}
self.forms = {}
self.inputs = {}
self.action = ""
self.method = ""
self.url=""
self.path=""
self.source=""
self.dirname=""
self.level=0
self.max_depth=4
self.urlRExp = re.compile('[.]htm$|[.]html$|[.]shtml$|[/]$|[.]php$',
re.IGNORECASE)
self.fileRExp = re.compile('[\/:*?"<>|]')
self.formats=[]

self.soc.me_him(['EXIT:',__name__],self.func_me_color)
def start_a(self,attrs):
self.soc.me_him(['ENTER:',__name__],self.func_me_color)
self.soc.w(attrs,"red")
href = [v for k,v in attrs if k=='href']
for value in href:
if self.urls.has_key(value):
pass
else:
self.urls[value]=0

self.soc.me_him(['EXIT:',__name__],self.func_me_color)

def start_img(self,attrs):
self.soc.me_him(['ENTER:',__name__],self.func_me_color)
self.soc.w(attrs,"blue")
src = [v for k,v in attrs if k=="src"]
for value in src:
if self.imgs.has_key(value):
pass
else:
self.imgs[value]=0

self.soc.me_him(['EXIT:',__name__],self.func_me_color)
def start_form(self,attrs):
self.soc.me_him(['ENTER:',__name__],self.func_me_color)
self.soc.w(attrs,"green")
method = [v for k, v in attrs if k=='method']
action = [v for k,v in attrs if k=="action"]
if string.join(method,"") != "":
self.method=method[0]
else:
self.method="post"

self.action=action[0]

self.soc.w(action,"white_on_green")
self.soc.w(method,"white_on_blue")
self.forms[self.action]={}

self.forms[self.action][self.method]={}

self.soc.me_him(['EXIT:',__name__],self.func_me_color)
def start_input(self,attrs):
self.soc.me_him(['ENTER:',__name__],self.func_me_color)
self.soc.w(attrs,"yellow")
name = [v for k, v in attrs if k=='name']
value = [v for k,v in attrs if k=="value"]
if string.join(name,"") !="":
if string.join(value,"")!="":
self.forms[self.action][self.method][name[0]]=value[0]
else:
self.forms[self.action][self.method][name[0]]=""
self.soc.w(self.forms,"white_on_gold")
self.soc.me_him(['EXIT:',__name__],self.func_me_color)
def url_dirname(self, url):
self.soc.me_him(['RETURN:',__name__],self.func_me_color)
#print url
return self.fileRExp.sub('_',url)
def dirname(self,url):
self.soc.me_him(['RETURN:',__name__],self.func_me_color)
return os.path.dirname(url)
def save_images(self,minsize):
if os.path.isdir(self.path+self.dirname):
return False # aborting, dir exists
else:
a=self.path+self.dirname
os.mkdir(a)
os.chdir(a)
print self.url
for img in self.imgs.keys():
loc=self.url_dirname(img)
print loc, img, a
try:
if self.imgs[img]==0:
#urllib.urlretrieve(img,loc)
#os.sy

Re: parsing csv files class

2008-12-27 Thread alex goretoy
How would I change this to work with numpy: (Would it be more feasible for
storing big files? 300-30,000 records)
 for row in reader:
self.buffer.append(row)
s,a=[],{}

for j in range(len(self.buffer[0])):
a[self.buffer[0][j]]=row[j]
self.bufferp.append(a)
i+=1
self.total = i-1

Instead of doing self.buffer.append(row)

would I initialize numpy like this: self.buffer=numpy.array() and then in
the loop do:
self.buffer.append(row) ? How do I achieve the same for lower code, where it
appends to a dict with header of each column? Thank you.

On Sat, Dec 27, 2008 at 5:31 PM, alex goretoy
wrote:

> I might as well add a UnicodeReader and UnicodeWriter and support for
> passing delimiter in from other classes.  At the same time. Anyone have a
> good csv class I can pick thru? I'm planning on posting my mysql adn curl
> classes that I use in my projects I just want to make them better and have
> less error.
>
>
> On Sat, Dec 27, 2008 at 5:18 PM, alex goretoy  > wrote:
>
>> It's main concern is to grab the file into the buffer for use in other
>> classes. The self.soc.me_him is just so I know when its ENTERING or EXITING
>> in that function when I run it in terminal. It's prints it in color. My main
>> concern right now is to add error handling. I'm still learning how to use
>> assert and yield, but I got try,except down pat.  All this class does is
>> grabs the file either from http or local storage into a buffer and I use
>> that in other classes. I want to add support for creating creating csv as
>> well. I read the doc on csv and  will try some things out soon. Thanks for
>> helping me.
>>
>>
>> On Sat, Dec 27, 2008 at 2:15 PM, Gabriel Genellina <
>> gagsl-...@yahoo.com.ar> wrote:
>>
>>> En Sat, 27 Dec 2008 11:02:13 -0200, Gary M. Josack 
>>> escribió:
>>>
>>>> alex goretoy wrote:
>>>>
>>>
>>>  I know it's messy with all those self.soc.* functions, but it works in
>>>>> one of my current project. I just want to make it more pythonic I also 
>>>>> want
>>>>> to add capability for makeing csv file if I give it input like:
>>>>> 1234,something nice, hey this is something nice
>>>>> 2468,something else, something else
>>>>>
>>>>
>>> reader = csv.reader(file(filename, "rb"))
>>>>>try:
>>>>>for row in reader:
>>>>>self.buffer.append(row)
>>>>>s,a=[],{}
>>>>>
>>>>
>>>  Do you know that there is a csv module in the standard library already?
>>>>
>>>
>>> I'd say he already knows, he even used it in the code.
>>>
>>> To Alex G.: I didn't understand what's the purpose of this class.
>>> Probably you want to do too much things in the same place; looks like it has
>>> multiple concerns, and that's not a good idea usually.
>>>
>>> --
>>> Gabriel Genellina
>>>
>>>
>>> --
>>> http://mail.python.org/mailman/listinfo/python-list
>>>
>>
>>
>>
>> --
>> А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
>> а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
>>
>>
>>
>> --
>> А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
>> а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
>>
>
>
>
> --
> А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
> а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
>



-- 
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
--
http://mail.python.org/mailman/listinfo/python-list


Re: parsing csv files class

2008-12-28 Thread alex goretoy
Tim, Thank you for your suggestions that you made. I will modify my class to
what you said. I will also remove find_and_replace. seeing as I won't use it
anywhere else. I think I put it there for some test and forgot to delete it.
I was actually deleting the header outside of the class. This works much
better for me. Any other suggestions are appreciated. Thank you. -A

On Sun, Dec 28, 2008 at 5:46 AM, Tim Roberts  wrote:

> "alex goretoy"  wrote:
> >
> >class parsercsvy(object):
> >"""Return a line from a csv file or total amount of lines"""
> >def __init__(self,file_name=""):
> >self.func_me_color="white_on_black"
> >self.soc=stdout_colours.stdout_colors()
> >self.soc.me_him(['ENTER:',__name__],self.func_me_color)
> >self.filename = file_name
> >self.buffer = []
> >self.bufferp= []
> >if string.find(self.filename,"http") != -1:
> >resp=urllib2.urlopen(self.filename)
> >file=resp.read()
> >lfi=len(string.split(self.filename,"/"))
> >filename = "/tmp/"+string.split(self.filename,"/")[lfi-1]
>
> Style issue:  unless you are running Python 1.x, you virtually never need
> to import the "string" module.  Also, you can always refer to the last
> element of a list or tuple by using [-1]:
>
>parts = self.filename.split( "/" )
>filename = "/tmp/" + parts[-1]
>
>
> >def parse(self,filename,ret=0):
> >self.soc.me_him(['ENTER:',__name__],self.func_me_color)
> >i = 0
> >try:
> >reader = csv.reader(file(filename, "rb"))
> >try:
> >for row in reader:
> >self.buffer.append(row)
> >s,a=[],{}
> >
> >for j in range(len(self.buffer[0])):
> >a[self.buffer[0][j]]=row[j]
> >self.bufferp.append(a)
> >i+=1
> >self.total = i-1
>
> You might consider keeping the header line separate.
>
>reader = csv.reader(open(filename, "rb"))
>header = reader.next()
>self.buffer = list(reader)
>self.bufferp = [ dict( zip( header, line ) ) for line in reader ]
>self.header = header
>
> Also, you don't really need a separate "total" variable, since it's equal
> to len(self.buffer).
>
> >def total(self):
> >"""return total number of lines in csv file"""
> >self.soc.me_him(['ENTER:',__name__],self.func_me_color)
> >
>  self.soc.me_him(['RETURN:',self.total,__name__],self.func_me_color)
> >return self.total
>
> There's a problem here, as this was originally written.  "self.total"
> starts out being a function (this one here).  But after self.parse runs,
> "self.total" will be an integer, and this function is lost.  You need to
> decide whether you want users to just access the self.total integer, or
> force them to use the function.  In the latter case, you can change the
> counter to self._total.
>
> On the other hand, the self.total counter is unnecessary:
>def total(self):
>return len(self.buffer)
>
> >def find_and_replace(self,li,fi,re):
> >"""
> >find and replace a string inside a string, return list
> >find_and_replace(list,find,replace)
> >"""
> >this=[]
> >for l in li:
> >#found_index=string.find(l,fi)
> >this.append(l.replace(fi,re))
> >return this
>
>def find_and_replace(self,li,fi,re):
> return [l.replace(fi,re) for l in li]
>
> I'm not sure why this is a member of the class; it doesn't use any of the
> members.
> --
> Tim Roberts, t...@probo.com
> Providenza & Boekelheide, Inc.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
--
http://mail.python.org/mailman/listinfo/python-list


Re: parsing csv files class

2008-12-30 Thread alex goretoy
This line doesn't work for me. bufferp is empty afterwards.

self.bufferp= [dict(zip(header,line)) for line in reader]

needs to be this
self.bufferp= [dict(zip(header,line)) for line in self.buffer]

after reading from the reader, it becomes empty. Figured maybe someone would
find this info useful. Thank you Tim for helping me make my library better.
I may need some assistance in another thread about a pycurl library. I want
it to fall back to urllib/urllib2 if pycurl is not installed module. look
for thread "pycurl urllib fallback" I will post it here shortly to
python-list.

On Mon, Dec 29, 2008 at 6:15 AM, alex goretoy
wrote:

> Tim, Thank you for your suggestions that you made. I will modify my class
> to what you said. I will also remove find_and_replace. seeing as I won't use
> it anywhere else. I think I put it there for some test and forgot to delete
> it. I was actually deleting the header outside of the class. This works much
> better for me. Any other suggestions are appreciated. Thank you. -A
>
>
> On Sun, Dec 28, 2008 at 5:46 AM, Tim Roberts  wrote:
>
>> "alex goretoy"  wrote:
>> >
>> >class parsercsvy(object):
>> >"""Return a line from a csv file or total amount of lines"""
>> >def __init__(self,file_name=""):
>> >self.func_me_color="white_on_black"
>> >self.soc=stdout_colours.stdout_colors()
>> >self.soc.me_him(['ENTER:',__name__],self.func_me_color)
>> >self.filename = file_name
>> >self.buffer = []
>> >self.bufferp= []
>> >if string.find(self.filename,"http") != -1:
>> >resp=urllib2.urlopen(self.filename)
>> >file=resp.read()
>> >lfi=len(string.split(self.filename,"/"))
>> >filename = "/tmp/"+string.split(self.filename,"/")[lfi-1]
>>
>> Style issue:  unless you are running Python 1.x, you virtually never need
>> to import the "string" module.  Also, you can always refer to the last
>> element of a list or tuple by using [-1]:
>>
>>parts = self.filename.split( "/" )
>>filename = "/tmp/" + parts[-1]
>>
>>
>> >def parse(self,filename,ret=0):
>> >self.soc.me_him(['ENTER:',__name__],self.func_me_color)
>> >i = 0
>> >try:
>> >reader = csv.reader(file(filename, "rb"))
>> >try:
>> >for row in reader:
>> >self.buffer.append(row)
>> >s,a=[],{}
>> >
>> >for j in range(len(self.buffer[0])):
>> >a[self.buffer[0][j]]=row[j]
>> >self.bufferp.append(a)
>> >i+=1
>> >self.total = i-1
>>
>> You might consider keeping the header line separate.
>>
>>reader = csv.reader(open(filename, "rb"))
>>header = reader.next()
>>self.buffer = list(reader)
>>self.bufferp = [ dict( zip( header, line ) ) for line in reader ]
>>self.header = header
>>
>> Also, you don't really need a separate "total" variable, since it's equal
>> to len(self.buffer).
>>
>> >def total(self):
>> >"""return total number of lines in csv file"""
>> >self.soc.me_him(['ENTER:',__name__],self.func_me_color)
>> >
>>  self.soc.me_him(['RETURN:',self.total,__name__],self.func_me_color)
>> >return self.total
>>
>> There's a problem here, as this was originally written.  "self.total"
>> starts out being a function (this one here).  But after self.parse runs,
>> "self.total" will be an integer, and this function is lost.  You need to
>> decide whether you want users to just access the self.total integer, or
>> force them to use the function.  In the latter case, you can change the
>> counter to self._total.
>>
>> On the other hand, the self.total counter is unnecessary:
>>def total(self):
>>return len(self.buffer)
>>
>> >def find_and_replace(self,li,fi,re):
>> >"""
>> >find and replace a string inside a string, return list
>> >find_and_replace(list,find,replace)
>> >"""
>> >this=[]
>> >for l in li:
>> >#found_index=string.find(l,fi)
>> >this.append(l.replace(fi,re))
>> >return this
>>
>>def find_and_replace(self,li,fi,re):
>> return [l.replace(fi,re) for l in li]
>>
>> I'm not sure why this is a member of the class; it doesn't use any of the
>> members.
>> --
>> Tim Roberts, t...@probo.com
>> Providenza & Boekelheide, Inc.
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
>
>
> --
> А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
> а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
>



-- 
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
--
http://mail.python.org/mailman/listinfo/python-list


pycurl urllib fallback

2008-12-30 Thread alex goretoy
Hello All,

I have this class I like to call pcrunchly. That works to do all my request
via libcurl library. What I want to do is add capability for this class to
fallback to urllib if pycurl module is not install or is not importable for
some reason. I'm posting my whole class. Use it however you want, just
please help me to make it better. As you can see from the code I've already
started to add this functionality. I found some code on Google that I'm
trying to combine with my class, so that it can achieve this task. I want to
ask the reader of this thread. Is this a good conservative thing to do. Will
this make my class to bulky. Is this something I want? or do I want
something else? Is there a better way to achieve this perhaps? I would
appreciate any comments on this matter. I would like this class to be able
to handle any protocol you throw at it. So as to make it other apps that
need to use a different protocol and stuff. Please notice the first huge
comment. That is what I'm currently combining into my working pycurl class.
Is this good? Oh yeah, please don't mind all those self.soc functions calls.
They print things in color to my terminal for me.

#!/usr/bin/env python
from ctypes import *
import os, sys, types, urllib, urllib2, urlparse
import stdout_colours



   #1. #!/usr/bin/env python
   #2. # -*- coding: UTF-8 -*-
   #3.
   #4. import cookielib
   #5. import urllib
   #6. import urllib2
   #7.
   #8. cj = cookielib.CookieJar()
   #9. opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(c  j))
  #10. resp = opener.open('http://www.amm.com/login.asp') # save a cookie
  #11.
  #12. theurl = 'http://www.amm.com/login.asp'
  #13. # an example url that sets a cookie, try different urls here and see
the cookie collection you can make !
  #14. body={'username':'AMMT54590570','password':'AMMT32  564288'}
  #15. txdata = urllib.urlencode(body)
  #16. # if we were making a POST type request, we could encode a dictionary
of values here - using urllib.urlencode
  #17. txheaders =  {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5;
Windows NT)'}
  #18. # fake a user agent, some websites (like google) don't like automated
exploration
  #19.
  #20.
  #21. try:
  #22. req = urllib2.Request(theurl, txdata, txheaders) # create a
request object
  #23. handle = opener.open(req) # and open it to return a handle on the
url
  #24. HTMLSource = handle.read()
  #25. f = file('test.html', 'w')
  #26. f.write(HTMLSource)
  #27. f.close()
  #28.
  #29. except IOError, e:
  #30. print 'We failed to open "%s".' % theurl
  #31. if hasattr(e, 'code'):
  #32. print 'We failed with error code - %s.' % e.code
  #33. elif hasattr(e, 'reason'):
  #34. print "The error object has the following 'reason' attribute
:", e.reason
  #35. print "This usually means the server doesn't exist, is down,
or we don't have an internet connection."
  #36. sys.exit()
  #37.
  #38. else:
  #39. print 'Here are the headers of the page :'
  #40. print handle.info() # handle.read() returns the page,
handle.geturl() returns the true url of the page fetched (in case urlopen
has followed any redirects, which it sometimes does)


class curl(object):
"Encapsulate user operations on CGIs through curl."
def __init__(self, base_url=""):
self.func_me_color="white_on_black"
self.soc=stdout_colours.stdout_colors()
self.soc.me_him(['ENTER:',__name__],self.func_me_color)
# These members might be set.
self.base_url = base_url
self.verbose = 0
self.response = ""
self.PYCURL=None
try:
import pycurl
self.PYCURL = True
except ImportError,e:
import cookielib
import urllib
import urllib2
self.PYCURL = False
#print "\ntrouble with importing pycurl %s\n" % e
#sys.exit(1)
# Nothing past here should be modified by the caller.
if self.PYCURL:

self.curlobj = pycurl.Curl()
# Verify that we've got the right site...
#self.curlobj.setopt(pycurl.SSL_VERIFYHOST, 2)
# Follow redirects in case it wants to take us to a CGI...
self.curlobj.setopt(pycurl.FOLLOWLOCATION, 1)
#self.curlobj.setopt(pycurl.MAXREDIRS, 15)
# Setting this option with even a nonexistent file makes libcurl
# handle cookie capture and playback automatically.
self.curlobj.setopt(pycurl.COOKIEFILE, "/dev/null")
# Set timeouts to avoid hanging too long
self.curlobj.setopt(pycurl.CONNECTTIMEOUT, 60)
self.curlobj.setopt(pycurl.TIMEOUT, 600)
#self.set_verbosity(self.verbose)
# Set up a callback to capture
else:
self.cj=cookielib.CookieJar()
print "\nurllib:\n"
def response_callback(x):
self.soc.me_him(['ENTER:',__name__],self.fun

Re: Videocapture in python

2009-01-01 Thread alex goretoy
Can you post your code or a code segment? I would be interested in seeing
how this works.

On Thu, Jan 1, 2009 at 3:29 AM,  wrote:

> I face issues in videocapture in python. Cant find anyplace where we
> can raise bug reports, so mentioning here. Also help required if
> somebody has solved it earlier.
>
> On using videocapture (python 2.4), I am facing the following issues
> while creating a video sort of application.
> -> Pull out the usb cable : Videocapture gets the data stored
> initially in the buffer and returns always. The images are not updated
> - but also there is no error returned.
> i.e. there is no information to the viewer that it is not working
> anymore. Especially because since the timestamp is updated everytime
> (it is done inside videocapture.py - wherein current time is
> overwritten on the received image), it gives a feeling that video is
> running.
>
> Currently I have done a workaround in that every 2 captures, i setup
> the camera again - but it takes too much time. Anyone has any
> suggestions on solving this?
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
--
http://mail.python.org/mailman/listinfo/python-list


Re: Creating an application for Linux

2009-01-01 Thread alex goretoy
I found a great video on how to do this last night. I wasn't even looking
for it. Check it out. It's really good. Makes me want to start making videos
as well. Thanks.

Ubuntu: Making a .deb package out of a python program (English) tutorial
video - Ubuntu: Making a .deb package out of a python program (English) -
Learn: python, deb, deb_package, publishing, package, english, ubuntu,
linux

On Wed, Dec 31, 2008 at 9:54 PM, Mike Driscoll  wrote:

> On Dec 31, 3:36 pm, lkcl  wrote:
> > hiya mike: where do i know you from?  i've heard your name somewhere
> > and for the life of me can't remember where!  anyway... onwards.
> >
>
> I don't know...while your username looks vaguely familiar, I don't
> think I've communicated with you recently. I spend most of my time on
> the wxPython list now...
>
>
> > your simplest bet is to take advantage of the .deb install system,
> > which, if you follow that, will allow you to pull in all of the
> > dependencies _without_ screwing around with the ubuntu distribution,
> > or requiring that you build "special" versions of the dependencies.
> >
> > so - your first port of call is to locate a similar app to your own
> > one:
> >
> > apt-cache  search wxwidgets
> > [rose-tinted filter on the results...]
> > cryptonit - A client side PKI (X.509) cryptographic tool
> > fontypython - A GUI tool to manage ttf fonts
> > jmdlx - jugglemaster deluxe using wxWidgets
> > wxmaxima - a wxWidgets GUI for the computer algebra system maxima
> > multiget - graphical download manager
> >
> > then, do apt-cache show , paying particular attention to
> > the dependencies.  apt-cache show fontypython looks like a good
> > candidate.
> >
> > so, do apt-get source fontypython (or other candidate)
> >
> > also do apt-get build-essential dh-make dpkg-dev debutils python-dev
> > devscripts python-setuptools juuust for fun, but the essential ones
> > are probably dh-make and dpkg-dev.
> >
> > then you have something to work from (an example - the source of the
> > deb-wrapped fontypython) and you will have most of the debian
> > developer utils etc. etc.
> >
> > _then_ you go to e.g.  this:
> http://www.pythonmark.com/python-library/debian/howto-build-a-debian-...
> > the preamble for which says "don't bother with that annoying ubuntu
> > python deb howto video, particularly on the basis that who gives a
> > stuff about _verbal_ instructions when you actually want stuff you can
> > READ!"
> >
> > :)
> >
> > the most important thing that _you_ need to remember is that you
> > _must_ identify the correct libraries (and their debian packagenames -
> > can't bring myself to say ubuntu packagenames) and make damn sure that
> > you add them into the dependencies in the debian/control file.
> >
> > do _not_ be tempted to "bundle" customised versions of python-
> > pysqlite, python-sqlalchemy etc. etc.
> >
> > testing: you should really use a debootstrap absolute "basic"
> > environment (set up a chroot, or a virtual KVM or other virtual PC,
> > qemu, whatever, or even a real machine) do NOT do a "full" install of
> > ubuntu, do an absolute minimalist install (netbook, businesscard,
> > whatever).
>
>
> I thought the general practice was to test on the closest software/
> hardware combo that your application was most likely to run on. I have
> heard of doing testing on the lowest common denominator before though.
> Unfortunately, I don't have time to set up a bare-bones VM since we're
> closing soon, but I may give this a go on Friday and report back.
>
> >
> > ... and _then_ install your .deb (with dpkg -i) followed by apt-get -f
> > install (to pull in all of the dependencies).
> >
> > then, use export DISPLAY=192.168.1.5:0.0 (adapt as necessary), run
> > xhost + on 192.168.1.5 (adapt as necessary), and _then_ fire up your
> > test app.
> >
> > if you get a python library not found runtime error, you know that you
> > got your dependencies wrong, in the debian/control file.
> >
> > if you install a "vanilla" ubuntu desktop, various other packages will
> > pull in the dependencies for you - and you will never find out if you
> > got all of the dependencies correct.
> >
> > that having been said, if you don't _care_ about correctness, skip the
> > above six sentences :)
> >
> > l.
> >
>
> Thanks for the instructions.
>
> Mike
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pass by reference

2009-01-01 Thread alex goretoy
I recently conquered this pass by ref thing. This is how I did it.

Python 2.4.3 (#1, Apr  3 2006, 14:02:53)
[GCC 3.4.6] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def f1(v):
... v="asdf"
...
>>> def f2(v):
... v=["asdf"]
...
>>> def f3(v):
... v.append("asdf")
...
>>> a="fdsa"
>>> b=["fdsa"]
>>> f1(a)
>>> a
'fdsa'
>>> f1(b)
>>> b
['fdsa']
>>> f2(a)
>>> a
'fdsa'
>>> f2(b)
>>> b
['fdsa']
>>> f3(a)
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 2, in f3
AttributeError: 'str' object has no attribute 'append'
>>> f3(b)
>>> b
['fdsa', 'asdf']
>>>
if you only want one value in there, you can pop off the first value and
then append.
def f4(v):
_old=v.pop()
v.append("asdf")

you can then also turn it back into a string by doing this:

b[0]

I was very glad to have learned this way to do by ref. Thanks.

On Wed, Dec 31, 2008 at 11:32 PM, Aaron Brady  wrote:

> On Dec 31, 5:30 am, iu2  wrote:
> > Hi,
> >
> > Is it possible somehow to change a varible by passing it to a
> > function?
> >
> > I tried this:
> >
> > def change_var(dict0, varname, val):
> >   dict0[varname] = val
> >
> > def test():
> >   a = 100
> >   change_var(locals(), 'a', 3)
> >   print a
> >
> > But test() didn't work, the value a remains 100.
> >
> > I have several variables initialized to None.
> > I need to convert each one of them an object only if it is None.
> > something like:
> >
> > if not var1: var1 = MyObject()
> >
> > I want this to be a function, that is:
> >
> > def create_obj(var):
> >   if not var: var = MyObj()
> >   # set properties of var
> >
> > Now, I know I can achieve this by functional programming,
> >
> > def create_obj(var):
> >   if not var:
> > x = MyObj()
> > # set properties of x
> > return x
> >   return var
> >
> > and then
> >
> > var = creaet_obj(var)
> >
> > Is there another way?
> >
> > Thanks
>
> A practical way is to use a container.  Some people use lists; I like
> an object.
>
> thingref= Ref( thing )
> f( thingref )
> print thingref() #or thingref.get() or w'ver.
>
> Then 'f' can assign like this:
>
> def f( aref ):
>  # blah blah
>  aref( newthing ) #or aref.set( newthing )
>
> But the short answer is no.  A function receives the contents of a
> variable, not a variable.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
--
http://mail.python.org/mailman/listinfo/python-list


list iteration if statement

2009-01-02 Thread alex goretoy
Hello All,

I'm doing this in my code

[[v.append(j) for j in i] for i in self.value]

if works and all, but I need to add a if statement in the mix. Can't seem to
remember the syntax to do so and everything I've tried seems to fail. How do
I add a check to see if j is not int("0") then append to v list? Thank you
in advance. -A

-- 
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pass by reference

2009-01-02 Thread alex goretoy
You are correct, terminology is a must. In order to stay on the same page.
And yes, it;s not technically by ref. but it works for me at the moment.

I was doing this in my code:
l={"user":"asdf","pass":"goog"}
d= {
"login_url":"http://example.com/login";,
"user":l["user"],
"pass":l["pass"]

}
and it wouldn't work. So I had to do some research on how to make it work.
passing a mutable object resolved my problem. Thank you for correcting me.
-A


On Thu, Jan 1, 2009 at 6:22 PM, Terry Reedy  wrote:

> alex goretoy wrote:
>
>> I recently conquered this pass by ref thing. This is how I did it.
>>
>
> What you did was to pass a mutable object and mutate it.  Absolutely
> standard practice in Python.  I am glad you learned it, but also learning
> and using the standard terminology will also help.  Hope you enjoy Python
> too.
>
> tjr
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pass by reference

2009-01-02 Thread alex goretoy
You are correct, terminology is a must. In order to stay on the same page.
And yes, it;s not technically by ref. but it works for me at the moment.

I was doing this in my code:
l={"user":"asdf","pass":"goog"}
d= {
"login_url":"http://example.com/login";,
"user":l["user"],
"pass":l["pass"]

}
and it wouldn't work. So I had to do some research on how to make it work.
passing a mutable object resolved my problem. Thank you for correcting me.
-A

ps.I have this habit of pressing reply instead of reply to all. Working on
fixing that.
--
http://mail.python.org/mailman/listinfo/python-list


Re: list iteration if statement

2009-01-02 Thread alex goretoy
Thank you Steve and MRAB,

This is what I was looking for:

 [[v.append(j) for j in i if j != 0] for i in self.value]

the value is actually stored as a string so I would need to check if it is
"0". I do have one more question about list comprehension though. After
doing this I get an unwanted list of None how do I make it disappear or not
return this list. Would I have to be modifying it in place for this to
happen? Wouldn't modifying it in place potentially overwrite some other
values? I just don't want it to return [[None], [None, None], [None, None],
[None]]

You guys rock, thanks for helping me learn python.

On Sat, Jan 3, 2009 at 2:09 AM, Steve Holden  wrote:

> alex goretoy wrote:
> > Hello All,
> >
> > I'm doing this in my code
> >
> > [[v.append(j) for j in i] for i in self.value]
> >
> > if works and all, but I need to add a if statement in the mix. Can't
> > seem to remember the syntax to do so and everything I've tried seems to
> > fail. How do I add a check to see if j is not int("0") then append to v
> > list? Thank you in advance. -A
>
> Who, tiger. It "works" for a value of "works" that involves creating two
> lists. One is the one you want, referenced by v, and the other is the
> value if the list comprehension, which will be a list full of lists of
> all the None values returned by those append() calls. But I presume you
> are throwing that second list away ...
>
> See, a list comprehension is intended to create a list. So what you
> should have used (assuming v was the empty list before you started) was
>
> v = [[j for j in i] for i in self.value]
>
> Further, when you say 'j is not int("0")', do you actually mean that a
> is not in integer with the value 0? Assuming you do then what you need is
>
> v = [[j for j in i if not j] for i in self.value]
>
> or, more pedantically
>
> v = [[j for j in i if j==0] for i in self.value]
>
> regards
>  Steve
> --
> Steve Holden+1 571 484 6266   +1 800 494 3119
> Holden Web LLC  http://www.holdenweb.com/
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
--
http://mail.python.org/mailman/listinfo/python-list


Re: list iteration if statement

2009-01-02 Thread alex goretoy
v should have ['3','4','1'] sorry if I made it confusing.

On Sat, Jan 3, 2009 at 2:43 AM, alex goretoy wrote:

> rather, how do I suppress the output of the list with all None in it?
>
> >>> l=[['3'], ['0', '4'], ['0', '1'], ['0']]
> >>> v=[]
> >>> [[v.append(j)for j in i if j != "0"] for i in l]
> [[None], [None], [None], []]
> >>> v
> ['39', '32', '1']
>
> >>>
>
> On Sat, Jan 3, 2009 at 2:38 AM, alex goretoy 
> wrote:
>
>> Thank you Steve and MRAB,
>>
>> This is what I was looking for:
>>
>>  [[v.append(j) for j in i if j != 0] for i in self.value]
>>
>> the value is actually stored as a string so I would need to check if it is
>> "0". I do have one more question about list comprehension though. After
>> doing this I get an unwanted list of None how do I make it disappear or not
>> return this list. Would I have to be modifying it in place for this to
>> happen? Wouldn't modifying it in place potentially overwrite some other
>> values? I just don't want it to return [[None], [None, None], [None, None],
>> [None]]
>>
>> You guys rock, thanks for helping me learn python.
>>
>>
>> On Sat, Jan 3, 2009 at 2:09 AM, Steve Holden  wrote:
>>
>>> alex goretoy wrote:
>>> > Hello All,
>>> >
>>> > I'm doing this in my code
>>> >
>>> > [[v.append(j) for j in i] for i in self.value]
>>> >
>>> > if works and all, but I need to add a if statement in the mix. Can't
>>> > seem to remember the syntax to do so and everything I've tried seems to
>>> > fail. How do I add a check to see if j is not int("0") then append to v
>>> > list? Thank you in advance. -A
>>>
>>> Who, tiger. It "works" for a value of "works" that involves creating two
>>> lists. One is the one you want, referenced by v, and the other is the
>>> value if the list comprehension, which will be a list full of lists of
>>> all the None values returned by those append() calls. But I presume you
>>> are throwing that second list away ...
>>>
>>> See, a list comprehension is intended to create a list. So what you
>>> should have used (assuming v was the empty list before you started) was
>>>
>>> v = [[j for j in i] for i in self.value]
>>>
>>> Further, when you say 'j is not int("0")', do you actually mean that a
>>> is not in integer with the value 0? Assuming you do then what you need is
>>>
>>> v = [[j for j in i if not j] for i in self.value]
>>>
>>> or, more pedantically
>>>
>>> v = [[j for j in i if j==0] for i in self.value]
>>>
>>> regards
>>>  Steve
>>> --
>>> Steve Holden+1 571 484 6266   +1 800 494 3119
>>> Holden Web LLC  http://www.holdenweb.com/
>>>
>>> --
>>> http://mail.python.org/mailman/listinfo/python-list
>>>
>>
>>
>>
>> --
>> А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
>> а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
>>
>
>
>
> --
> А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
> а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
>



-- 
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
--
http://mail.python.org/mailman/listinfo/python-list


Re: list iteration if statement

2009-01-02 Thread alex goretoy
rather, how do I suppress the output of the list with all None in it?

>>> l=[['3'], ['0', '4'], ['0', '1'], ['0']]
>>> v=[]
>>> [[v.append(j)for j in i if j != "0"] for i in l]
[[None], [None], [None], []]
>>> v
['39', '32', '1']
>>>

On Sat, Jan 3, 2009 at 2:38 AM, alex goretoy wrote:

> Thank you Steve and MRAB,
>
> This is what I was looking for:
>
>  [[v.append(j) for j in i if j != 0] for i in self.value]
>
> the value is actually stored as a string so I would need to check if it is
> "0". I do have one more question about list comprehension though. After
> doing this I get an unwanted list of None how do I make it disappear or not
> return this list. Would I have to be modifying it in place for this to
> happen? Wouldn't modifying it in place potentially overwrite some other
> values? I just don't want it to return [[None], [None, None], [None, None],
> [None]]
>
> You guys rock, thanks for helping me learn python.
>
>
> On Sat, Jan 3, 2009 at 2:09 AM, Steve Holden  wrote:
>
>> alex goretoy wrote:
>> > Hello All,
>> >
>> > I'm doing this in my code
>> >
>> > [[v.append(j) for j in i] for i in self.value]
>> >
>> > if works and all, but I need to add a if statement in the mix. Can't
>> > seem to remember the syntax to do so and everything I've tried seems to
>> > fail. How do I add a check to see if j is not int("0") then append to v
>> > list? Thank you in advance. -A
>>
>> Who, tiger. It "works" for a value of "works" that involves creating two
>> lists. One is the one you want, referenced by v, and the other is the
>> value if the list comprehension, which will be a list full of lists of
>> all the None values returned by those append() calls. But I presume you
>> are throwing that second list away ...
>>
>> See, a list comprehension is intended to create a list. So what you
>> should have used (assuming v was the empty list before you started) was
>>
>> v = [[j for j in i] for i in self.value]
>>
>> Further, when you say 'j is not int("0")', do you actually mean that a
>> is not in integer with the value 0? Assuming you do then what you need is
>>
>> v = [[j for j in i if not j] for i in self.value]
>>
>> or, more pedantically
>>
>> v = [[j for j in i if j==0] for i in self.value]
>>
>> regards
>>  Steve
>> --
>> Steve Holden+1 571 484 6266   +1 800 494 3119
>> Holden Web LLC  http://www.holdenweb.com/
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
>
>
> --
> А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
> а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
>



-- 
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a better algorithm?

2009-01-02 Thread alex goretoy
I personally like this solution the best. Thanks mr.

tuples = [(1, 2), (3, 4, 5), (6, 7)]

def triple_or_pair(seq):
   u = None
   try:
   k, u, v = seq
   except ValueError:
   k, v = seq
   return k, u, v

for k, u, v in [ triple_or_pair(seq) for seq in tuples ]:
   print k, u, v

On Sat, Jan 3, 2009 at 4:55 AM, Kottiyath  wrote:

> On Jan 3, 2:38 am, mr  wrote:
> > As has been noted, the best is to fix the input to be regular-3-
> > tuples. For the fun of it, here's another variation of a solution:
> >
> > tuples = [(1, 2), (3, 4, 5), (6, 7)]
> >
> > def triple_or_pair(seq):
> > u = None
> > try:
> > k, u, v = seq
> > except ValueError:
> > k, v = seq
> > return k, u, v
> >
> > for k, u, v in [ triple_or_pair(seq) for seq in tuples ]:
> > print k, u, v
>
> It is a code to post some data to HTML server.
> Even though usually the POST values are of type(name, value), if file
> transfer is involved, then POST values change to (name, filename,
> value).
> My view was that since filename is a rare occurance and doesnt make
> sense in a usual POST, I had not kept it as a full 3 tuple.
> Since so many programmers (that too much more capable than me) are
> suggesting that it is code smell, I am reviewing my decision.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
--
http://mail.python.org/mailman/listinfo/python-list


Re: Noob question: Is all this typecasting normal?

2009-01-03 Thread alex goretoy
for each his own.

Any more word on userio?

On Sat, Jan 3, 2009 at 6:14 PM, Russ P.  wrote:

> On Jan 2, 10:50 pm, Ben Finney 
> 
> >
> wrote:
> > s0s...@gmail.com writes:
> > > On Jan 2, 7:20 pm, Ben Finney 
> > > 
> >
> > > wrote:
> > > > They don't need to be creative; they merely need to conform with
> > > > the naming scheme as laid out in the PEP.
> >
> > > If it's something to be included in the standard library, I agree
> > > (just for consistency, not because using_underscores is better).
> >
> > > But for user code, I prefer mixedCase.
> >
> > That seems superficially like an easy distinction. Indeed, PEP 8
> > explicitly is meant to apply only to code intended for inclusion in
> > the Python standard library.
> >
> > But consider:
> >
> > Python libraries generally don't get into the standard library until
> > they've had a history of widespread public use as an external library.
> > This helps ensure many of the harder-to-find wrinkles get discovered
> > through wide exposure and ironed out before becoming standard.
> >
> > Code bases, especially library interfaces, that get a lot of use
> > across wide communities are naturally going to have a whole lot of
> > other people's code directly using those interfaces.
> >
> > Interfaces that are so widely used garner a high resistance to change,
> > especially for something as non-functional as a naming convention.
> >
> > Choosing the naming convention for one's code is much easier to do
> > when its usage base is smaller than when that base is larger.
> > Therefore the easiest time to choose when to code in conformance to
> > PEP 8 is right at the start.
> >
> > The best conclusion I can come to from this? Unless you explicitly
> > *never* intend sharing your code with *anyone*, it's best to code all
> > your Python code in accordance with PEP 8 anyway. You then don't have
> > to make the decision about whether this is the time to follow PEP 8 or
> > not; just do it by default, and you avoid the needless pain on those
> > occasions, often unforeseeable at the start, where your code later
> > ends up widely used.
> >
> > --
> >  \   "One of the most important things you learn from the internet |
> >   `\   is that there is no 'them' out there. It's just an awful lot of |
> > _o__)'us'." —Douglas Adams |
> > Ben Finney
>
> Fair enough, but for code that is not intended for general public
> usage (i.e., most code) so-called camelCase is every bit as good if
> not better than using underscores to divide variable names. It saves a
> few characters, and in my opinion it's significantly easier to read.
> Identifiers divided by underscores always appear to me at first glance
> to be multiple words, and I find that very annoying.
>
> So unless you think the standard library will someday include code for
> air traffic management, I'll stick with camelCase, and I'll thank you
> for not making an issue of it.
>
> As far as I am concerned, this is one of the most important bits of
> advice in PEP 8:
>
> A Foolish Consistency is the Hobgoblin of Little Minds
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
--
http://mail.python.org/mailman/listinfo/python-list


Re: simple turn-based multiplayer game via TCP server/client

2009-01-03 Thread alex goretoy
Since we are on the subject of Rock, Paper, Scissors. I've recntly watched
this one video on how to make a .deb out of .py files and the tutor was
using a rock, paper scissors game.

Not sure how this may come of use to you but, I'll post it anyway for you to
look at. May help somehow.

http://www.google.com/search?hl=en&q=filetype%3Apy+%22rock+paper+scissors%22&btnG=Search

http://www.showmedo.com/videos/video?name=linuxJensMakingDeb&fromSeriesID=37


Hope this help you in your journey for multiplayer game somehow

On Sun, Jan 4, 2009 at 3:58 AM, greyw...@gmail.com wrote:

> Hi everyone,
>
> I'm learning python to get a multiplayer roleplaying game up and
> running.
>
> I didn't see any simple examples of multiplayer games on the web so I
> thought I'd post mine here.  I choose Rock, Paper, Scissors as a first
> game to experiment with as the game logic/options are easy to
> implement and understand.
>
> Initially, I tried to get the socketserver.TCPServer example in the
> Python Docs to work, but couldn't get my game variables into the
> handle method of the class MyTCPHandler.  And I didn't know how else
> to do it.  I ended up creating my own server & client out of simple
> sockets based on the simple echo server & client examples in the
> Python Docs.
>
> I also wanted to send chat messages OR game variables back & forth,
> but I couldn't figure out how to do the OR, so the basic idea in this
> implementation is to send the dictionary 'game' back and forth.  game
> dict contains all the gaming variables as well as any chat messages.
> The program processes results depending on whether the game is
> starting, there's a chat message, or there's a game move.
>
> Finally, in testing, I ran the server in IDLE, but I had to load a
> command prompt and switch to c:\python30; then type 'python
> rpsmulti.py' for the client every time.  Anyone know how to test
> server/client code strictly in IDLE?
>
> Anyway, try it out and let me know how you would improve it.
>
> John R.
>
> # NAME: rpsmulti.py
> # DESCRIPTION: rock, paper, scissors game multiplayer game
> # AUTHOR: John Robinson
> # DATE: 1/3/09
> # VERSION: Python 3.0
> # TO DO:
> #   .server_address instead of HOST, PORT?
>
> import socket
> from random import choice
> from pickle import dumps, loads
> from pprint import pprint
>
> HOST, PORT = "localhost",   # defined for now
> BUFFSIZE = 1024 # for socket.send & recv commands
> BACKLOG = 2 # number of clients supported by
> server
> SECONDS = 3 # seconds until socket.timeout (not
> implemented)
> # moves dict to translate 'rps' choice
> MOVES = {'r':'Rock',
> 'p':'Paper',
> 's':'Scissors'}
> # outcome dict stores result for all possible scenarios
> OUTCOME = {('p','r'): 'win',
>   ('r','s'): 'win',
>   ('s','p'): 'win',
>   ('p','p'): 'draw',
>   ('r','r'): 'draw',
>   ('s','s'): 'draw',
>   ('r','p'): 'lose',
>   ('s','r'): 'lose',
>   ('p','s'): 'lose'}
>
> def main_menu(game):
>""" initialize game dict variables & opening screen of the game
> """
>game['total'] = 0   # total number of games played
>game['won'] = 0 # total games won by player
>game['lost'] = 0# total games lost by player
>game['drew'] = 0# total games drew by player
>game['move'] = ''   # player's move (rps)
>game['message'] = ''# player's chat message
>game['sentmessage'] = ''# player's previous message
>game['start'] = True# setting up the game boolean
>
>print("\tROCK PAPER SCISSORS\n")
>if game['name']=='':# if returning to menu don't display
> the following
>game['name'] = get_name()
>print("Welcome "+game['name']+". Remember...")
>print("Rock smashes scissors! Paper covers Rock! Scissors cuts
> paper!\n")
>print("1. Play single player game")
>print("2. Start two player game")
>print("3. Join two player game")
>print("4. Quit")
>print()
>c = safe_input("Your choice? ", "1234")
>c = int(c)
>if c==1:
>one_player(game)
>elif c==2:
>start_two_player(game)
>elif c==3:
>two_player_join(game)
>else:
>print('Play again soon.')
>
> def safe_input(prompt, values='abcdefghijklmnopqrstuvwxyz'):
>""" gives prompt, checks first char of input, assures it meets
> given values
>default is anything goes """
>while True:
>i = input(prompt)
>try:
>c = i[0].lower()
>except IndexError:  # the only possible error?!
>if c=='':
>print("Try again.")
>else:
>if c not in values: # some other character
>print("Try again.")
>else:   # looks good. continue.
>break
>return i
>
> def get_name():
>""" returns input as name """
>while True:
>nam

Re: Noob question: Is all this typecasting normal?

2009-01-04 Thread alex goretoy
My gmail did that. FYI, it wasn't intentional.

А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
Paula Poundstone  - "I don't have a bank account because I don't know my
mother's maiden name."

On Sun, Jan 4, 2009 at 1:41 AM, Steven D'Aprano <
st...@remove-this-cybersource.com.au> wrote:

> On Sat, 03 Jan 2009 16:19:58 +0100, Bruno Desthuilliers wrote:
>
> > But indeed, you obviously cannot add strings with numerics nor
> > concatenate numerics with strings. This would make no sense.
>
> The OP comes from a Perl background, which AFAIK allows you to concat
> numbers to strings and add strings to numbers. That's probably the (mis)
> feature he was hoping Python had.
>
>
>
> --
> Steven
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: math module for Decimals

2009-01-04 Thread alex goretoy
No, I know there's a typo because python told me there is. If you have svn
repo locally. then cd into Lib/ and run python decimal.py

It will tell you line 683 has syntax error, please see below.

haha python-svn # python Lib/decimal.py
  File "Lib/decimal.py", line 683
sign = 0 if _math.copysign(1.0, f) == 1.0 else 1
  ^
SyntaxError: invalid syntax


Although, It may be only because I ran it through python 2.4.3

Thanks for quick response, I wasn't expecting so quick. :)


On Sun, Jan 4, 2009 at 10:21 AM, Mark Dickinson  wrote:

> On Jan 4, 9:52 am, "alex goretoy"  wrote:
> > Also, another reason why I'm posting to this thread. I noticed some
> > error/typo in line 683 of decimal.py located on public svn repo. This is
> > what is looks like.
> >
> > sign = 0 if _math.copysign(1.0, f) == 1.0 else 1
>
> This line looks okay to me; can you say why you think there's a typo
> here?
>
> If it's the 'sign = 0' part that's bothering you, that's just
> a peculiarity of Decimal: the stored sign value is 0 for
> positive numbers, 1 for negative numbers, which I agree
> is a little counterintuitive.  (Think of the sign
> as analogous to the sign *bit* in an IEEE 754 floating-point
> number.)
>
> Mark
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
--
http://mail.python.org/mailman/listinfo/python-list


Re: math module for Decimals

2009-01-04 Thread alex goretoy
I've been watching this thread for couple days now. I followed the bug
report and all that stuff. It's very interesting to me how you guys talk
about this stuff. I like it alot. I a new guy to python, just fyi. I'm one
of my current projects I'm using Decimal as well and I think it be a huge
pain in the you know what that it doesn't take floats as input.

I'm currently doing this in my code:

a=str(decimal.Decimal(str(round(self.value,2)-round(float(subtract),2

I know it's messy and I need sleep, yawn. But you see what I'm getting at
here. I have to jump through somuch hoops to get what I wanted out of this.
To be up front, I'm not sure that's what I wanted. Too tired. Anyway, I'm
glad you guys got it pushed into 2.7 and 3.1. Thank you so much for this.

Also, another reason why I'm posting to this thread. I noticed some
error/typo in line 683 of decimal.py located on public svn repo. This is
what is looks like.

sign = 0 if _math.copysign(1.0, f) == 1.0 else 1

I'm not trying to mention it to show someones flaws, rather I want to help
you guys. Genuinely. I want in on the action. To do what I can, or what I'm
capable of. So please do _NOT_ take it that way. This is awesome stuff,
Thank you. -A



On Sun, Jan 4, 2009 at 1:30 AM, Steven D'Aprano <
st...@remove-this-cybersource.com.au> wrote:

> On Sat, 03 Jan 2009 13:34:11 -0800, Mark Dickinson wrote:
>
> > On Jan 3, 9:27 pm, Mark Dickinson  wrote:
> >> Decimal.from_float() implemented by Raymond Hettinger for Python 2.7
> >> and Python 3.1, within 72 hours of Steven submitting the feature
> >> request.  If only all issues could be resolved this quickly. :-)
> >
> > Rats.  I left out the crucial line of that post, namely:
> >
> > Thank you, Steven!
>
> And many thanks to both you and Raymond, firstly for doing the actual
> work, and secondly for your patience with my questions on the bug tracker.
>
>
> --
> Steven
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
--
http://mail.python.org/mailman/listinfo/python-list


Re: deleting a method

2009-01-04 Thread alex goretoy
HAHAHAHA, I like your sig Ben. So much that I blogged about it.

starnixalpha.blogspot.com

Oh yeah, and the info on this thread was helpful.

Thanks, -A

А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я


On Sun, Jan 4, 2009 at 10:12 AM, Ben Finney <
bignose+hates-s...@benfinney.id.au >wrote:

> "Filip Gruszczyński"  writes:
>
> > Thanks, now I see, what happens, but don't exactly know why. Could
> > you point me to some good explanation how object creation is
> > performed in Python?
>
> Rather than "how object creation is performed", I would recommend
> you get a better handle on how the object *model* works in Python.
>
> If you haven't yet, please work through all of the Python Tutorial
> http://docs.python.org/tutorial/>. Read each part, experiment
> with code until you understand what is presented, and only *then* move
> on to the next section.
>
> For theoretical explanations, the effbot's "Python Objects" article
> http://effbot.org/zone/python-objects.htm> is also recommended.
>
> Before theory though, use the Tutorial for concrete demonstrations
> coming from your very fingers.
>
> --
>  \  "… a Microsoft Certified System Engineer is to information |
>  `\ technology as a McDonalds Certified Food Specialist is to the |
> _o__)   culinary arts." —Michael Bacarella |
> Ben Finney
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python training in Colorado, January 27-30

2009-01-04 Thread alex goretoy
I'd be interested in attending if you make it to Tulsa,OK. Are your courses
only in Colorado?

-Alex Goretoy
http://www.alexgoretoy.com


On Sun, Jan 4, 2009 at 7:29 PM, Mark Lutz  wrote:

> Python author and trainer Mark Lutz will be teaching a 4-day
> Python class on January 27-30, in Longmont, Colorado.
>
> This is a public training session open to individual enrollments,
> and covers the same topics and hands-on lab work as the onsite
> sessions that Mark teaches.  The class provides an in-depth
> introduction to both Python and its common applications, and
> parallels the instructor's popular Python books.
>
> For more information on this session, please visit its web page:
>
> http://home.earthlink.net/~python-training/2009-public-classes.htm<http://home.earthlink.net/%7Epython-training/2009-public-classes.htm>
>
> For additional background on the class itself, see our home page:
>
> http://home.earthlink.net/~python-training<http://home.earthlink.net/%7Epython-training>
>
> Thanks for your interest,
> --Python Training Services
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Package / Module Hierarchy question

2009-01-04 Thread alex goretoy
You might try this in qwe.py

import os,sys
sys.path.append(os.getcwd()+"../")

This will allow you to then import modules from module(dir).
Hope this helps. OTOH, there maybe a better solution.

-Alex Goretoy
http://www.alexgoretoy.com



On Sun, Jan 4, 2009 at 9:10 PM, Torsten Mohr  wrote:

> Hi,
>
> in a package i use these files:
>
> module (dir)
>  __init__.py
>  submodule
>__init__.py
>qwe.py
>
>
> qwe.py defines a class that derives from a class defined in submodule (and
> by that in submodule/__init__.py.
>
> Is it possible somehow to write in qwe.py to import submodule (though
> __init__.py is in the same directory as qwe.py ?
>
> I'd like to keep the tests for qwe.py within qwe.py, the code that i want
> to
> execute when i directly execute qwe.py and then:
>
> if __name__ == '__main__':
>some_test_code()
>
>
> Or do i need to write an external test code?
>
>
> Thanks for any hints,
> Torsten.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


threading a 10 lines out of a file

2009-01-04 Thread alex goretoy
Hello All,

I have a question. I'm not sure exactly as how to explain it in any other
way then the way I will explain it. So I'm sorry if it's hard to understand
exactly what it is I'm trying to do. Maybe not. Anyway. Here goes.

Lets say I have a file that looks like this.

id,name,desc,test
123,abc,testing is fun,yeah baby
456,qwe,python makes if funner, yeah baby
789,zxc,this is another line in this file, yeah baby
...
...

This file can have an unknown amount of lines in it. It can be 700,400 or
even 7,000.
I do this to read the file:

try:
reader = csv.reader(file(filename, "rb"))
try:
header = reader.next()
self.buffer = list(reader) # total = len(self.buffer)
self.bufferp= [dict(zip(header,line)) for line in
self.buffer]
self.header = header
#for row in reader:
#self.buffer.append(row)
#s,a=[],{}

#for j in range(len(self.buffer[0])):
#a[self.buffer[0][j]]=row[j]
#self.bufferp.append(a)
#i+=1
#self.total = i-1
except csv.Error, e:
sys.exit('file %s, line %d: %s' % (filename,
reader.line_num, e))
except IOError, e:
sys.exit('file %s, IOError: %s' % (filename, e))

What I am currently doing is looping over this file, performing a function
for every line. This function isbeing called from this class __init__(),

def loop_lines(self):

for k in range(len(self.buffer)): #for every line in csv file
self.line=self.buffer[k]
self.some_function(self.line)


Now, for my question. Is it possible for me to thread this scenario somehow?

So that I can set a variable that says how many lines to work on at the same
time?

lets say 10 lines at a time, once it finishes some it moves on to the next
ones that are not in the thread pool or something to that nature. Always
making sure that it works on 10 at the same time.

How would I achieve something like this in my program? Can someone please
recommend something for me. I would greatly appreciate. My program would
appreciate it too, seeing as it will be multi-threaded :) Thank you for your
help.

-Alex Goretoy
http://www.alexgoretoy.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: threading a 10 lines out of a file

2009-01-04 Thread alex goretoy
I've found a great example on how to do threads. It compares a ping program
in regular for loop and with threaded for loop. The link is below if anyone
is interested.

http://www.wellho.net/solutions/python-python-threads-a-first-example.html

I hope my eagerness to post doesn't annoy anyone. I like to get as much info
from as many places as possible and compare. This way I think I may have a
better solution for a problem. Plus people that Google will find this post
or any words in it. Any more information on threading a for loop would be
greatly appreciated. TIA

-Alex Goretoy
http://www.alexgoretoy.com



On Mon, Jan 5, 2009 at 6:00 AM, alex goretoy wrote:

> Hello All,
>
> I have a question. I'm not sure exactly as how to explain it in any other
> way then the way I will explain it. So I'm sorry if it's hard to understand
> exactly what it is I'm trying to do. Maybe not. Anyway. Here goes.
>
> Lets say I have a file that looks like this.
>
> id,name,desc,test
> 123,abc,testing is fun,yeah baby
> 456,qwe,python makes if funner, yeah baby
> 789,zxc,this is another line in this file, yeah baby
> ...
> ...
>
> This file can have an unknown amount of lines in it. It can be 700,400 or
> even 7,000.
> I do this to read the file:
>
> try:
> reader = csv.reader(file(filename, "rb"))
> try:
> header = reader.next()
> self.buffer = list(reader) # total = len(self.buffer)
> self.bufferp= [dict(zip(header,line)) for line in
> self.buffer]
> self.header = header
> #for row in reader:
> #self.buffer.append(row)
> #s,a=[],{}
>
> #for j in range(len(self.buffer[0])):
> #a[self.buffer[0][j]]=row[j]
> #self.bufferp.append(a)
> #i+=1
> #self.total = i-1
> except csv.Error, e:
> sys.exit('file %s, line %d: %s' % (filename,
> reader.line_num, e))
> except IOError, e:
> sys.exit('file %s, IOError: %s' % (filename, e))
>
> What I am currently doing is looping over this file, performing a function
> for every line. This function isbeing called from this class __init__(),
>
> def loop_lines(self):
>
> for k in range(len(self.buffer)): #for every line in csv file
> self.line=self.buffer[k]
> self.some_function(self.line)
>
>
> Now, for my question. Is it possible for me to thread this scenario
> somehow?
>
> So that I can set a variable that says how many lines to work on at the
> same time?
>
> lets say 10 lines at a time, once it finishes some it moves on to the next
> ones that are not in the thread pool or something to that nature. Always
> making sure that it works on 10 at the same time.
>
> How would I achieve something like this in my program? Can someone please
> recommend something for me. I would greatly appreciate. My program would
> appreciate it too, seeing as it will be multi-threaded :) Thank you for your
> help.
>
> -Alex Goretoy
> http://www.alexgoretoy.com
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python training in Colorado, January 27-30

2009-01-05 Thread alex goretoy
,ubuntu,etc...If they haven't yet.

All I know is this. I want linux and python to own USA turf.


This will also make it so that development and new applications/tools will
come out faster. More users, programmers, hackers, etc...

Don't get me wrong, It's nothing personal against Microsoft. I just don't
like how so many people are wasting there time with it. Especially when
there are significantly way better things out there to feed you mind and
your computer. In an unrestrictive so much environment as windows.
Especially for development.

Sorry this is long and off topic. (I need to learn how to write better.)
It's just some things I think about sometimes. Please help me some how to
achieve this goal. I want people to really harness the true power of there
computer and stop eating BS for applications and development environments.
If there is more sand, then there's more sand castles, holes and fun. Why
would someone want to pass up the ability to use the same thing in so many
more ways than one. It doesn't compute. By all means I'm not trying to steal
your thread. Please don't feel that way.

-Alex Goretoy
http://www.alexgoretoy.com



On Mon, Jan 5, 2009 at 6:47 PM,  wrote:

>
>lutz> Per my web page, my classes may be available in a different
>lutz> location later this year (Florida is a strong possibility), but
>lutz> not in Tulsa, unfortunately.
>
> Maybe if Tulsa had more appealing geography or weather??? ;-)
>
> Skip
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: math module for Decimals

2009-01-05 Thread alex goretoy
>
> Hmm.  Maybe we shouldn't be using this syntax in from_float, if it's
> the only thing that prevents the trunk version of decimal.py from
> being used with Python 2.4.  On the other hand, from_float isn't
> going to work until 2.7 anyway, since it uses a whole bunch of
> new stuff:  as_integer_ratio and copysign (both introduced in 2.6),
> and bit_length (introduced in 2.7).
>

I so new to python that I'm not sure that anything I can say may help as
much as someone with more experience. I would leave is compatability to be
decided by what other functions it relies on.(as_integer_ratio and copysign)
Throw the rest out the window.

Since that would make this function more bulky and I don't think there will
be that many people wanting to use it with 2.4, OTOH I'm using BackTrack2
and it comes with python2.4.3

I started building my little program using ubuntu with python2.5.x, then I
started to use my other option for dual-boot. Backtrack2 is an old time
favorite and is alot faster for me to use when running X,firefox(with
anywhere from 15-100 tabs open),konqueror,etc

Ialready installed other versions of python for bt, no problem there. I'm
just wondering about this import error in decimal.py inside python2.7a0(svn
repo), don't let curiosity kill this cat.

I just wanted to let All know what decimal.py is doing on my pc. Maybe I'm
the only one getting this? This version of python2.7 is from python's svn
repo. Is the python repo considered to be unstable(wrong word?) and this is
expected?

I get this when importing decimal:

Python 2.7a0 (trunk:68339M, Jan  5 2009, 05:18:41)
[GCC 3.4.6] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import decimal
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/local/lib/python2.7/decimal.py", line 138, in 
import math as _math
ImportError: No module named math
>>>


Are other people seeing this as well? Just curious.
--
http://mail.python.org/mailman/listinfo/python-list


Re: threading a 10 lines out of a file

2009-01-05 Thread alex goretoy
Steve,

Are you referring to the endless GIL debate? I googled about what you said.
I'll look into it here shortly. I just know one thing, is that I need a
comparison for regular code and something about how GIL and threading fit in
the picture. It makes it easier for me to understand what is going on. Can
you post an example? something I can use to truely thread a for loop? The
example previously posted show that it works 10 times faster than original
for loop. My current program runs for 4.5 hours. I think it will be good to
minimize that by 10 times. But if It can do more/faster, than that would be
great. TIA for all your help.

-Alex Goretoy
http://www.alexgoretoy.com



On Mon, Jan 5, 2009 at 6:13 PM, Steve Holden  wrote:

> re, however, that the CPython implementation won't net you any
> benefit if all threads are CPU-bound, since due to something called the
> GIL (global interpreter lock) no two threads will run concurrently.
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: threading a 10 lines out of a file

2009-01-05 Thread alex goretoy
>
> Se we need to know a bit more about your 4.5-hour program before we can
> determine whether threads can help. There is light at the end of the
> tunnel, however, since even if threads don't work it's possible that the
> multiprocessing module will (assuming you have multi-processor hardware
> at your disposal).

What my program is doing is sending each line to a function that processes
it via pycurl(with urllib fallback),mysqlDB(with _mysql fallback). It check
the mysql database to see if this line exists. If it doesn't then it sends
it either via mysql query or pycurl. Depending on the option set in the
functions. Some sections of the function  have time.sleep(6) in them.
Otherwise things won't work. This considerably slows down performance. If I
thread all lines then it will process more at the same time. So that means
there will be like 10 or set amount threads running doing all steps in the
functions. posting forms, performing queries and waiting for form postings
to process on the server, etc... I hope this adds more light at the end of
that tunnel. It currently works under my ubuntu install of python(2.5.x) and
bt's python(2.4.3). Then reason why I added a fallback to MySQLdb and pycurl
is then a person can install this on a server that is hosted elsewhere.
Where you can't install python modules, due to permissions and such. I want
it to work everywhere. There's alot more to this application, I'm not sure I
can disclose at the moment. Seeing as it can be used for good or bad. I
don't want it to get in the wrong hands if it's public. OTOH, I think I'll
make it public. That's all up in the air at the moment. One thing it that it
does make life easier for me. A lot easier. Although, I haven't made money
with it. Yet. Plus, I want to make pyGTK frontend for it. Looking into that
too. I wouldn't be against a private team assembling to create this though.
As long as I can get money out of it somehow. Cuz I'm broke. and I live with
my mom. Not sure how anyone can help me there. But I'll throw it up in the
air for all to see. Maybe somethings comes out of it. This program is an
idea I've been building inside my garage(my room) for about a year and a
half. Built in PHP and python, now.

Would something that uses pycurl,mysql be good for threading? It doesn't run
on SMP but maybe one day.

I also need to look into how to make a python package out of it. I
researched some stuff awhile ago, but I didn't quite need it then. I just
wanted to see what I'm getting into.  Any other stuff about this would be
appreciated to. Although of topic. Sorry.

By the way, I wanted to really thank everyone for all your help. It means a
lot to me.

-Alex Goretoy
http://www.alexgoretoy.com



On Mon, Jan 5, 2009 at 9:17 PM, Steve Holden  wrote:

> I did, once upon a time, write code
> that used several hundred threads to send emails, and gave a dramatic
> speed-up (because of the network-bound nature of the task). Can I
> presume that your original inquiry was a toy, and that your real problem
> is also IO-bound? Otherwise I am unsure how you will benefit by
> threading - if your line-processing tasks don't contain any IO then
> using a threaded approach will not yield any speed-up at all.
>
> The example you quoted achieved its speed-up because a thread releases
> the GIL while waiting for a network response, allowing other threads to
> process. Thus it effectively ran all the pings in parallel.
>
> Se we need to know a bit more about your 4.5-hour program before we can
> determine whether threads can help. There is light at the end of the
> tunnel, however, since even if threads don't work it's possible that the
> multiprocessing module will (assuming you have multi-processor hardware
> at your disposal).
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: multiprocessing vs thread performance

2009-01-05 Thread alex goretoy
There doesn't seem to be any good examples on POSH or it's not clear to me.
For when using with a for loop like mk is doing who started this thread. How
would somethings like this be possible to do with POSH? The example show how
to share variables between processes/threads but nothing about How the
thread starts or a for loop.

-Alex Goretoy
http://www.alexgoretoy.com
somebodywhoca...@gmail.com


On Sat, Jan 3, 2009 at 1:31 PM, Nick Craig-Wood  wrote:

> mk  wrote:
> >  After reading http://www.python.org/dev/peps/pep-0371/ I was under
> >  impression that performance of multiprocessing package is similar to
> >  that of thread / threading. However, to familiarize myself with both
> >  packages I wrote my own test of spawning and returning 100,000 empty
> >  threads or processes (while maintaining at most 100 processes / threads
> >  active at any one time), respectively.
> >
> >  The results I got are very different from the benchmark quoted in PEP
> >  371. On twin Xeon machine the threaded version executed in 5.54 secs,
> >  while multiprocessing version took over 222 secs to complete!
> >
> >  Am I doing smth wrong in code below?
>
> Yes!
>
> The problem with your code is that you never start more than one
> process at once in the multiprocessing example.  Just check ps when it
> is running and you will see.
>
> My conjecture is that this is due to the way fork() works under unix.
> I think that when the parent forks it yields the CPU to the child.
> Because you are giving the child effectively no work to do it returns
> immediately, re-awakening the parent, thus serialising your jobs.
>
> If you give the children some work to do you'll see a quite different
> result.  I gave each child time.sleep(1) to do and cut down the total
> number to 10,000.
>
> $ ./test_multiprocessing.py
> == Process 1000 working ==
> == Process 2000 working ==
> == Process 3000 working ==
> == Process 4000 working ==
> == Process 5000 working ==
> == Process 6000 working ==
> == Process 7000 working ==
> == Process 8000 working ==
> == Process 9000 working ==
> == Process 1 working ==
> === Main thread waiting for all processes to finish ===
> Total time: 101.382129192
>
> $ ./test_threading.py
> == Thread 1000 working ==
> == Thread 2000 working ==
> == Thread 3000 working ==
> == Thread 4000 working ==
> == Thread 5000 working ==
> == Thread 6000 working ==
> == Thread 7000 working ==
> == Thread 8000 working ==
> == Thread 9000 working ==
> == Thread 1 working ==
> Total time:  100.659118176
>
> So almost identical results and as expected - we ran 10,000 sleep(1)s
> in 100 seconds so we must have been running 100 simultaneously.
>
> If you replace the "time.sleep(1)" with "for _ in xrange(100):
> pass" you get this much more interesting answer on my dual core linux
> laptop, showing nicely the effect of the contention on the python
> global interpreter lock and how multiprocessing avoids it.
>
> $ ./test_multiprocessing.py
> == Process 1000 working ==
> == Process 2000 working ==
> == Process 3000 working ==
> == Process 4000 working ==
> == Process 5000 working ==
> == Process 6000 working ==
> == Process 7000 working ==
> == Process 8000 working ==
> == Process 9000 working ==
> == Process 1 working ==
> === Main thread waiting for all processes to finish ===
> Total time: 266.808327913
>
> $ ./test_threading.py
> == Thread 1000 working ==
> == Thread 2000 working ==
> == Thread 3000 working ==
> == Thread 4000 working ==
> == Thread 5000 working ==
> == Thread 6000 working ==
> == Thread 7000 working ==
> == Thread 8000 working ==
> == Thread 9000 working ==
> == Thread 1 working ==
> Total time:  834.81882
>
> --
> Nick Craig-Wood  -- http://www.craig-wood.com/nick
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Measuring bytes of packet sent from python application

2009-01-05 Thread alex goretoy
Have you looked into scapy?

www.secdev.org/projects/*scapy*/

There's another one, it comes with python I think. Can't seem to remember
the name. I may be mistaken though.

-Alex Goretoy
http://www.alexgoretoy.com
somebodywhoca...@gmail.com


On Mon, Jan 5, 2009 at 11:23 PM, Kangkook Jee  wrote:

> Jonathan Gardner wrote:
>
>> On Jan 5, 2:26 pm, Kangkook Jee  wrote:
>>
>>> I'd like to measure number of bytes sent(or recv'd) from my python
>>> application. Does anyone have any idea how can I achieve this?
>>>
>>> I tried to do this by tracing some socket calls (send, sendto, sendAll)
>>>  using 'metaclass' but I could find exactly place that I can put this in.
>>>
>>> My application runs some number of protocols (bittorrent, xmlrpc ..) in
>>> it and will be measured for a couple of hours.
>>>
>>>
>> A good universal tool on the Linux platform is tcpdump. It takes some
>> learning, but is very useful for this kind of task. You can use a tool
>> like ethereal to visualize the data that tcpdump gathers.
>>
>
> Thanks a lot Jonathan
>
> That seems like a good solution for my issue but how can I distinguish
> traffics from my application to others?
>
> I'm still struggling to solve it within python process since it looks
> cleaner but it doesn't seems to be easy at all.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a best linux distro for a python hobbyist?

2009-01-05 Thread alex goretoy
+1 for ubuntu

-Alex Goretoy
http://www.alexgoretoy.com
somebodywhoca...@gmail.com


On Tue, Jan 6, 2009 at 12:39 AM,  wrote:

> Hi,
>
> I would have to put in a vote for Ubuntu.
>
> There seems to be a working ubuntu package for most of the things that I
> have tried. Instead of having to use a pythonic package - just get one from
> the os.
>
> As for the things you mention.. give it a go
>
> On Mon, 5 Jan 2009 15:42:00 -0800, "member thudfoo" 
> wrote:
> > One with all the major python GUIs: pyQT, pyGtk, pyKde, wxPython, 
> > And so on.
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Measuring bytes of packet sent from python application

2009-01-05 Thread alex goretoy
You can alot run "lsof -i -T -n" from popen2 to see what applications use
what port and addr they are connected to.
In order to see all jobs though it needs to be ran as root. This way you can
find out what ports and such Then perform tcp dump thru popen2 and filter
for port and addr. This is just a first shot, then I would figure out what
to do after having gotten to this point.

import popen2
#find out what ports and addrs what program is connected to
r,w,e=popen2.popen3("lsof -i -T -n") # this may need sudo prepended to lsof
r=r.readlines()
e=e.readlines()
#get tcpdump, doesn't quiet work hereneeds something more, maybe a
different way altogether.
#tcpdump to pcap file and read file periodically?
r1,w1,e1=popen2.popen3("sudo tcpdump -i eth1")
r1=r1.readlines()
e1=e1.readlines()

Something to this nature, then do regular expression on tcpdump output,
either logged to pcap output file or by other means.

-Alex Goretoy
http://www.alexgoretoy.com
somebodywhoca...@gmail.com


On Mon, Jan 5, 2009 at 8:14 PM, Grant Edwards  wrote:

> On 2009-01-05, Kangkook Jee  wrote:
>
> > I'd like to measure number of bytes sent(or recv'd) from my
> > python application. Does anyone have any idea how can I
> > achieve this?
>
> Aside from tcpdump/wireshark, you can set up iptables rules to
> enable accounting for traffic based on IP addresses and ports.
>
> http://wiki.openvz.org/Traffic_accounting_with_iptables
> http://www.faqs.org/docs/linux_network/x-087-2-accounting.ipfwadm.html
> http://www.catonmat.net/blog/traffic-accounting-with-iptables/
>
> --
> Grant
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a better algorithm?

2009-01-05 Thread alex goretoy
>
> class entry:
>  filename = None
>
>  def __init__(self, name, value, filename=None):
>self.name = name
>self.value = value
>if filename is not None:
>  self.filename = filename
>
> [entry('name', 'Gabriel'), entry('age', 18), entry('pic', picture_data,
> 'path/to/file')]


Gabriel thank you for this. I just now realized I've being doing things the
hard way. :)
-Alex Goretoy
http://www.alexgoretoy.com
somebodywhoca...@gmail.com


On Mon, Jan 5, 2009 at 8:58 PM, Gabriel Genellina wrote:

> En Sat, 03 Jan 2009 02:55:12 -0200, Kottiyath 
> escribió:
>
>  tuples = [(1, 2), (3, 4, 5), (6, 7)]
>>>
>>
>> It is a code to post some data to HTML server.
>> Even though usually the POST values are of type(name, value), if file
>> transfer is involved, then POST values change to (name, filename,
>> value).
>> My view was that since filename is a rare occurance and doesnt make
>> sense in a usual POST, I had not kept it as a full 3 tuple.
>> Since so many programmers (that too much more capable than me) are
>> suggesting that it is code smell, I am reviewing my decision.
>>
>
> What about using another data structure instead - like this:
>
> class entry:
>  filename = None
>
>  def __init__(self, name, value, filename=None):
>self.name = name
>self.value = value
>if filename is not None:
>  self.filename = filename
>
> [entry('name', 'Gabriel'), entry('age', 18), entry('pic', picture_data,
> 'path/to/file')]
>
> --
> Gabriel Genellina
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: math module for Decimals

2009-01-06 Thread alex goretoy
Yes I ran strace python and imported math

time(NULL)  = 1231244692
futex(0x80575d8, FUTEX_WAKE, 1) = 0
stat64("math", 0xbfabef50)  = -1 ENOENT (No such file or
directory)
open("math.so", O_RDONLY|O_LARGEFILE)   = -1 ENOENT (No such file or
directory)
open("mathmodule.so", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or
directory)
open("math.py", O_RDONLY|O_LARGEFILE)   = -1 ENOENT (No such file or
directory)
open("math.pyc", O_RDONLY|O_LARGEFILE)  = -1 ENOENT (No such file or
directory)
stat64("/usr/lib/python24.zip/math", 0xbfabef50) = -1 ENOENT (No such file
or directory)
open("/usr/lib/python24.zip/math.so", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No
such file or directory)
open("/usr/lib/python24.zip/mathmodule.so", O_RDONLY|O_LARGEFILE) = -1
ENOENT (No such file or directory)
open("/usr/lib/python24.zip/math.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No
such file or directory)
open("/usr/lib/python24.zip/math.pyc", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No
such file or directory)
stat64("/usr/lib/python2.4/math", 0xbfabef50) = -1 ENOENT (No such file or
directory)
open("/usr/lib/python2.4/math.so", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No
such file or directory)
open("/usr/lib/python2.4/mathmodule.so", O_RDONLY|O_LARGEFILE) = -1 ENOENT
(No such file or directory)
open("/usr/lib/python2.4/math.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No
such file or directory)
open("/usr/lib/python2.4/math.pyc", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No
such file or directory)
stat64("/usr/lib/python2.4/plat-linux2/math", 0xbfabef50) = -1 ENOENT (No
such file or directory)
open("/usr/lib/python2.4/plat-linux2/math.so", O_RDONLY|O_LARGEFILE) = -1
ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/mathmodule.so", O_RDONLY|O_LARGEFILE) =
-1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/math.py", O_RDONLY|O_LARGEFILE) = -1
ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/math.pyc", O_RDONLY|O_LARGEFILE) = -1
ENOENT (No such file or directory)
stat64("/usr/lib/python2.4/lib-tk/math", 0xbfabef50) = -1 ENOENT (No such
file or directory)
open("/usr/lib/python2.4/lib-tk/math.so", O_RDONLY|O_LARGEFILE) = -1 ENOENT
(No such file or directory)
open("/usr/lib/python2.4/lib-tk/mathmodule.so", O_RDONLY|O_LARGEFILE) = -1
ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-tk/math.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT
(No such file or directory)
open("/usr/lib/python2.4/lib-tk/math.pyc", O_RDONLY|O_LARGEFILE) = -1 ENOENT
(No such file or directory)
stat64("/usr/lib/python2.4/lib-dynload/math", 0xbfabef50) = -1 ENOENT (No
such file or directory)
open("/usr/lib/python2.4/lib-dynload/math.so", O_RDONLY|O_LARGEFILE) = 3
fstat64(3, {st_mode=S_IFREG|0755, st_size=12716, ...}) = 0
open("/usr/lib/python2.4/lib-dynload/math.so", O_RDONLY) = 4
read(4, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\200\16"..., 512) =
512
fstat64(4, {st_mode=S_IFREG|0755, st_size=12716, ...}) = 0
mmap2(NULL, 15588, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 4, 0) =
0xb7f2b000
mmap2(0xb7f2e000, 4096, PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 4, 0x2) = 0xb7f2e000
close(4)= 0
close(3)        = 0

It's probably because I only downloaded python from svn repo and ran
./configure&&make&&make install

I didn't do anything else. Like set PYTHONPATH. I solved it though. You can
tell by the output it's looking for it in my other python install lib path.

Thank you.
-Alex Goretoy
http://www.alexgoretoy.com
somebodywhoca...@gmail.com


On Tue, Jan 6, 2009 at 10:44 AM, Mark Dickinson  wrote:

> dule built, but Python is looking in the wrong
> place for it, for some reason.
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: python is great

2009-01-06 Thread alex goretoy
>
> I use Andrea Gavana's GUI2Exe to create my binaries. He recently added
> a py2app wrapper to it. I don't have a Mac, so I haven't tested that
> part of his app. However, the py2exe portion rocks! I put in the path
> to my main Python executable, add any special 3rd party modules and it
> just works! I've written a tutorial for the py2exe part of it if
> you're interested...
>

Can you post the link to this tutorial?

If you want to save me the trouble, then I'd like to see those notes.
> If you want, I can host the notes at dotancohen.com to that they will
> be publicaly accessible.
>
Any more news on this research?

-Alex Goretoy
http://www.alexgoretoy.com
somebodywhoca...@gmail.com


On Tue, Jan 6, 2009 at 9:24 PM, Mike Driscoll  wrote:

> On Jan 6, 2:24 pm, Joe Strout  wrote:
> > M.-A. Lemburg wrote:
> > >> On the Mac in particular, if you want
> > >> your app to run on any PowerPC or Intel machine runing 10.4 or later,
> > >> and you're using anything not in the standard framework (such as
> > >> MySQLdb), it's a bit of a nightmare.
> >
> > > You're looking for py2app:
> >
> > >http://undefined.org/python/py2app.html
> >
> > No, I'm *using* py2app.  I've been trying to use it for a couple of
> > weeks now, with the generous help of such people as Robin Dunn, and I
> > still don't have it quite working properly.  (I'd be happy to send you
> > my notes on what was required to get as far as I've gotten, but it's
> > several pages, a bit long to post here.)
> >
> > (py2exe works a little more easily, thank goodness.)
> >
> > >> So I would say that Python as a language is great, and its standard
> > >> framework is great.  But its (many) IDEs are pretty poor, and the
> > >> process of building a polished, packaged app is abysmal.
> >
> > > It's certainly work, but that's always the case for nicely polished
> > > apps :-)
> >
> > In Python, yes.  :)  Not in all environments.
> >
> > > For packaging, you can choose from a multitude of installer builders -
> > > none of which are really Python specific.
> >
> > I'm not even talking about that level of packaging -- I'm just talking
> > about making something that appears to the user like a normal
> > executable, which they can double-click on their system and have it
> > actually run, rather than aborting with something unhelpful like "No
> > module named MySQLdb".
> >
> > >> And there are
> > >> some things (such as Flash-style web applets) that you still can't do
> at
> > >> all in Python, even after all these years.
> >
> > > You're looking for Silverlight:
> > >http://www.voidspace.org.uk/ironpython/silverlight/index.shtml
> >
> > Maybe.  I'm not a big fan of anything so Microsoftian, but I'll admit
> > that this does mostly fit the bill I described above (or has the
> > potential to, anyway).
> >
> > Thanks,
> > - Joe
>
> I use Andrea Gavana's GUI2Exe to create my binaries. He recently added
> a py2app wrapper to it. I don't have a Mac, so I haven't tested that
> part of his app. However, the py2exe portion rocks! I put in the path
> to my main Python executable, add any special 3rd party modules and it
> just works! I've written a tutorial for the py2exe part of it if
> you're interested...
>
> Mike
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why does numpy.array(a[0],b[0]) have this meaning?

2008-11-02 Thread alex goretoy
just a shot in the dark.

second arg to numpy.array is of type

see numpy.array.__doc__

-nop


On Mon, Nov 3, 2008 at 1:26 AM, Rick Giuly <[EMAIL PROTECTED]> wrote:

> Hello All,
>
> Case 1
> This generates an error, which makes sense because the argument should
> be a list of numbers:
> numpy.array(10,10)
>
> Case 2
> This does not generate an error and the result is an array with a
> single element:
> a = numpy.array([10])
> b = numpy.array([10])
> numpy.array(a[0],b[0])
>
> The only different I see here between the numpy.array call in the
> cases is that
> a[0] is a numpy int32
> 10 is an int
>
> Why would this minor difference in integer types cause a totally
> different result for the two cases - or is something else causing the
> difference in results?
>
>
> -rick
>
> P.S.
> I am aware that numpy.array([10,10]) will work, but I'm trying to
> understand what is going on syntactically/semantically in the two
> cases above.
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


[PyGTK] Singleton Window

2009-03-05 Thread alex goretoy
Hello All,

I am trying to create a singleton window in pygtk and for the life of me
can't seem to figure out a better way to go about doing this. The way I'm
doing it now is to recreate the window and show it. Example code is below. I
would much appreciate any assistance in this matter. I've googled to no
avail. I'm hiding the child window because when I execute main_quit on the
child it kills parent (which makes sense).

My singleton hack works, but its cluncky, I am wondering if theres some
other way(working shmingleton?).

My question is this. How to create a singleton child window without hiding
old childs(seeing as this creates many hidden childs after a while) or how
to hide it and when showing it again also have it display all contents in
the child window?

Thank you.

#!/usr/bin/env python
import os, sys

import pygtk
pygtk.require('2.0')
try:
  import gtk
except:
  print >> sys.stderr, "You need to install the python gtk bindings"
  sys.exit(1)



class Singleton_Test(object):
  def __init__(self):
self.root_window = gtk.Window( type=gtk.WINDOW_TOPLEVEL )
self.root_window.set_title("Singleton Test")
self.root_window.connect("delete_event", lambda w,e: gtk.main_quit())

self.vbox = gtk.VBox(False,0)
self.root_window.add(self.vbox)
self.vbox.show()

self.singleton_button = gtk.Button("SINGLETON")
self.singleton_button.connect("clicked",self.singleton_cb)
self.vbox.pack_start(self.singleton_button,False,False,0)

self.singleton_button.show()

self.shmingleton_button = gtk.Button("SHMINGLETON")
self.shmingleton_button.connect("clicked",self.shmingleton_cb)
self.vbox.pack_start(self.shmingleton_button,False,False,0)

self.shmingleton_button.show()

self.create_singleton_child_window()

self.root_window.show()

  singleton_window_count=0
  def singleton_cb(self,w):
if self.singleton_window_count>0:
  self.create_singleton_child_window()

self.singleton_child_window.show()
print "singleton child window count is ",self.singleton_window_count
self.singleton_window_count+=1

  def shmingleton_cb(self,w):
self.singleton_child_window.show_all() #doesn't work as expected,
neither does show


  def create_singleton_child_window(self):
self.singleton_child_window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.singleton_child_window.set_title("SINGLETON child")

#only hiding since gtk.main_quit kills parent, any better way?
self.singleton_child_window.connect("destroy", lambda w:
self.singleton_child_window.hide())
self.singleton_child_window.connect("delete_event", lambda w,e:
self.singleton_child_window.hide())

self.vbox = gtk.VBox(False, 0)
self.singleton_child_window.add(self.vbox)
self.vbox.show()
self.label = gtk.Label("SINGLETON")
self.vbox.pack_start(self.label,False,False,0)
self.label.show()

  def main(self):
gtk.main()

if __name__ == "__main__":
  singleton = Singleton_Test()
  singleton.main()

-Alex Goretoy
http://www.goretoy.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: [PyGTK] Singleton Window

2009-03-05 Thread alex goretoy
Correction, it's not True singleton.....

-Alex Goretoy
http://www.goretoy.com



On Thu, Mar 5, 2009 at 10:38 PM, alex goretoy
wrote:

> Hello All,
>
> I am trying to create a singleton window in pygtk and for the life of me
> can't seem to figure out a better way to go about doing this. The way I'm
> doing it now is to recreate the window and show it. Example code is below. I
> would much appreciate any assistance in this matter. I've googled to no
> avail. I'm hiding the child window because when I execute main_quit on the
> child it kills parent (which makes sense).
>
> My singleton hack works, but its cluncky, I am wondering if theres some
> other way(working shmingleton?).
>
> My question is this. How to create a singleton child window without hiding
> old childs(seeing as this creates many hidden childs after a while) or how
> to hide it and when showing it again also have it display all contents in
> the child window?
>
> Thank you.
>
> #!/usr/bin/env python
> import os, sys
>
> import pygtk
> pygtk.require('2.0')
> try:
>   import gtk
> except:
>   print >> sys.stderr, "You need to install the python gtk bindings"
>   sys.exit(1)
>
>
>
> class Singleton_Test(object):
>   def __init__(self):
> self.root_window = gtk.Window( type=gtk.WINDOW_TOPLEVEL )
> self.root_window.set_title("Singleton Test")
> self.root_window.connect("delete_event", lambda w,e: gtk.main_quit())
>
> self.vbox = gtk.VBox(False,0)
> self.root_window.add(self.vbox)
> self.vbox.show()
>
> self.singleton_button = gtk.Button("SINGLETON")
> self.singleton_button.connect("clicked",self.singleton_cb)
> self.vbox.pack_start(self.singleton_button,False,False,0)
>
> self.singleton_button.show()
>
> self.shmingleton_button = gtk.Button("SHMINGLETON")
> self.shmingleton_button.connect("clicked",self.shmingleton_cb)
> self.vbox.pack_start(self.shmingleton_button,False,False,0)
>
> self.shmingleton_button.show()
>
> self.create_singleton_child_window()
>
> self.root_window.show()
>
>   singleton_window_count=0
>   def singleton_cb(self,w):
> if self.singleton_window_count>0:
>   self.create_singleton_child_window()
>
> self.singleton_child_window.show()
> print "singleton child window count is ",self.singleton_window_count
> self.singleton_window_count+=1
>
>   def shmingleton_cb(self,w):
> self.singleton_child_window.show_all() #doesn't work as expected,
> neither does show
>
>
>   def create_singleton_child_window(self):
> self.singleton_child_window = gtk.Window(gtk.WINDOW_TOPLEVEL)
> self.singleton_child_window.set_title("SINGLETON child")
>
> #only hiding since gtk.main_quit kills parent, any better way?
> self.singleton_child_window.connect("destroy", lambda w:
> self.singleton_child_window.hide())
> self.singleton_child_window.connect("delete_event", lambda w,e:
> self.singleton_child_window.hide())
>
> self.vbox = gtk.VBox(False, 0)
> self.singleton_child_window.add(self.vbox)
> self.vbox.show()
> self.label = gtk.Label("SINGLETON")
> self.vbox.pack_start(self.label,False,False,0)
> self.label.show()
>
>   def main(self):
> gtk.main()
>
> if __name__ == "__main__":
>   singleton = Singleton_Test()
>   singleton.main()
>
> -Alex Goretoy
> http://www.goretoy.com
>
>
--
http://mail.python.org/mailman/listinfo/python-list


__import__ with dict values

2009-03-12 Thread alex goretoy
How would I import with __import__ from dict values?
I want sys.path value inside d['syspath'], below code doesn't work for me


d={}
d['sys']='sys'
d['path']='path'

d['syspath']=__import__(d['sys'],fromlist=[d['path']])

and how come does  above line doesn't give me diff value than below line?

d['syspath']=__import__(d['sys'])

Meaning, when I do this doesn't work. Which makes sense.
d['syspath']()
d['syspath'].d['path']

but this works both with fromlist and without.

d['syspath'].path


-Alex Goretoy
http://www.goretoy.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: __import__ with dict values

2009-03-12 Thread alex goretoy
I have resolved this problem in my code. It has something to do with your
current working directory when you append cwd/jars to sys.path and try to
import from interactive console
-Alex Goretoy
http://www.goretoy.com



On Thu, Mar 12, 2009 at 4:58 AM, alex goretoy
wrote:

> How would I import with __import__ from dict values?
> I want sys.path value inside d['syspath'], below code doesn't work for me
>
>
> d={}
> d['sys']='sys'
> d['path']='path'
>
> d['syspath']=__import__(d['sys'],fromlist=[d['path']])
>
> and how come does  above line doesn't give me diff value than below line?
>
> d['syspath']=__import__(d['sys'])
>
> Meaning, when I do this doesn't work. Which makes sense.
> d['syspath']()
> d['syspath'].d['path']
>
> but this works both with fromlist and without.
>
> d['syspath'].path
>
>
> -Alex Goretoy
> http://www.goretoy.com
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: __import__ with dict values

2009-03-12 Thread alex goretoy
yay, no more

exec ("import " + "sys")

in my code

-Alex Goretoy
http://www.goretoy.com



On Thu, Mar 12, 2009 at 5:42 AM, alex goretoy
wrote:

> I have resolved this problem in my code. It has something to do with your
> current working directory when you append cwd/jars to sys.path and try to
> import from interactive console
> -Alex Goretoy
> http://www.goretoy.com
>
>
>
> On Thu, Mar 12, 2009 at 4:58 AM, alex goretoy  > wrote:
>
>> How would I import with __import__ from dict values?
>> I want sys.path value inside d['syspath'], below code doesn't work for me
>>
>>
>> d={}
>> d['sys']='sys'
>> d['path']='path'
>>
>> d['syspath']=__import__(d['sys'],fromlist=[d['path']])
>>
>> and how come does  above line doesn't give me diff value than below line?
>>
>> d['syspath']=__import__(d['sys'])
>>
>> Meaning, when I do this doesn't work. Which makes sense.
>> d['syspath']()
>> d['syspath'].d['path']
>>
>> but this works both with fromlist and without.
>>
>> d['syspath'].path
>>
>>
>> -Alex Goretoy
>> http://www.goretoy.com
>>
>>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: __import__ with dict values

2009-03-12 Thread alex goretoy
or eval for that matter
-Alex Goretoy
http://www.goretoy.com



On Thu, Mar 12, 2009 at 5:43 AM, alex goretoy
wrote:

> yay, no more
>
> exec ("import " + "sys")
>
> in my code
>
> -Alex Goretoy
> http://www.goretoy.com
>
>
>
> On Thu, Mar 12, 2009 at 5:42 AM, alex goretoy  > wrote:
>
>> I have resolved this problem in my code. It has something to do with your
>> current working directory when you append cwd/jars to sys.path and try to
>> import from interactive console
>> -Alex Goretoy
>> http://www.goretoy.com
>>
>>
>>
>> On Thu, Mar 12, 2009 at 4:58 AM, alex goretoy <
>> aleksandr.gore...@gmail.com> wrote:
>>
>>> How would I import with __import__ from dict values?
>>> I want sys.path value inside d['syspath'], below code doesn't work for me
>>>
>>>
>>> d={}
>>> d['sys']='sys'
>>> d['path']='path'
>>>
>>> d['syspath']=__import__(d['sys'],fromlist=[d['path']])
>>>
>>> and how come does  above line doesn't give me diff value than below line?
>>>
>>> d['syspath']=__import__(d['sys'])
>>>
>>> Meaning, when I do this doesn't work. Which makes sense.
>>> d['syspath']()
>>> d['syspath'].d['path']
>>>
>>> but this works both with fromlist and without.
>>>
>>> d['syspath'].path
>>>
>>>
>>> -Alex Goretoy
>>> http://www.goretoy.com
>>>
>>>
>>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: __import__ with dict values

2009-03-12 Thread alex goretoy
note i would still like to be able to do __import__("sys")."path"

maybe if __import__ had __str__ defined, How is my thinking on this?
and how would I achieve something like this?
-Alex Goretoy
http://www.goretoy.com



On Thu, Mar 12, 2009 at 5:44 AM, alex goretoy
wrote:

> or eval for that matter
> -Alex Goretoy
> http://www.goretoy.com
>
>
>
> On Thu, Mar 12, 2009 at 5:43 AM, alex goretoy  > wrote:
>
>> yay, no more
>>
>> exec ("import " + "sys")
>>
>> in my code
>>
>> -Alex Goretoy
>> http://www.goretoy.com
>>
>>
>>
>> On Thu, Mar 12, 2009 at 5:42 AM, alex goretoy <
>> aleksandr.gore...@gmail.com> wrote:
>>
>>> I have resolved this problem in my code. It has something to do with your
>>> current working directory when you append cwd/jars to sys.path and try to
>>> import from interactive console
>>> -Alex Goretoy
>>> http://www.goretoy.com
>>>
>>>
>>>
>>> On Thu, Mar 12, 2009 at 4:58 AM, alex goretoy <
>>> aleksandr.gore...@gmail.com> wrote:
>>>
>>>> How would I import with __import__ from dict values?
>>>> I want sys.path value inside d['syspath'], below code doesn't work for
>>>> me
>>>>
>>>>
>>>> d={}
>>>> d['sys']='sys'
>>>> d['path']='path'
>>>>
>>>> d['syspath']=__import__(d['sys'],fromlist=[d['path']])
>>>>
>>>> and how come does  above line doesn't give me diff value than below
>>>> line?
>>>>
>>>> d['syspath']=__import__(d['sys'])
>>>>
>>>> Meaning, when I do this doesn't work. Which makes sense.
>>>> d['syspath']()
>>>> d['syspath'].d['path']
>>>>
>>>> but this works both with fromlist and without.
>>>>
>>>> d['syspath'].path
>>>>
>>>>
>>>> -Alex Goretoy
>>>> http://www.goretoy.com
>>>>
>>>>
>>>
>>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: __import__ with dict values

2009-03-12 Thread alex goretoy
__import__(opt['imp_mod']).options

eval(opt['imp_mod']+"."+opt['imp_opt'])

how to make top work like bottom?
-Alex Goretoy
http://www.goretoy.com



On Thu, Mar 12, 2009 at 5:56 AM, alex goretoy
wrote:

> note i would still like to be able to do __import__("sys")."path"
>
> maybe if __import__ had __str__ defined, How is my thinking on this?
> and how would I achieve something like this?
> -Alex Goretoy
> http://www.goretoy.com
>
>
>
> On Thu, Mar 12, 2009 at 5:44 AM, alex goretoy  > wrote:
>
>> or eval for that matter
>> -Alex Goretoy
>> http://www.goretoy.com
>>
>>
>>
>> On Thu, Mar 12, 2009 at 5:43 AM, alex goretoy <
>> aleksandr.gore...@gmail.com> wrote:
>>
>>> yay, no more
>>>
>>> exec ("import " + "sys")
>>>
>>> in my code
>>>
>>> -Alex Goretoy
>>> http://www.goretoy.com
>>>
>>>
>>>
>>> On Thu, Mar 12, 2009 at 5:42 AM, alex goretoy <
>>> aleksandr.gore...@gmail.com> wrote:
>>>
>>>> I have resolved this problem in my code. It has something to do with
>>>> your current working directory when you append cwd/jars to sys.path and try
>>>> to import from interactive console
>>>> -Alex Goretoy
>>>> http://www.goretoy.com
>>>>
>>>>
>>>>
>>>> On Thu, Mar 12, 2009 at 4:58 AM, alex goretoy <
>>>> aleksandr.gore...@gmail.com> wrote:
>>>>
>>>>> How would I import with __import__ from dict values?
>>>>> I want sys.path value inside d['syspath'], below code doesn't work for
>>>>> me
>>>>>
>>>>>
>>>>> d={}
>>>>> d['sys']='sys'
>>>>> d['path']='path'
>>>>>
>>>>> d['syspath']=__import__(d['sys'],fromlist=[d['path']])
>>>>>
>>>>> and how come does  above line doesn't give me diff value than below
>>>>> line?
>>>>>
>>>>> d['syspath']=__import__(d['sys'])
>>>>>
>>>>> Meaning, when I do this doesn't work. Which makes sense.
>>>>> d['syspath']()
>>>>> d['syspath'].d['path']
>>>>>
>>>>> but this works both with fromlist and without.
>>>>>
>>>>> d['syspath'].path
>>>>>
>>>>>
>>>>> -Alex Goretoy
>>>>> http://www.goretoy.com
>>>>>
>>>>>
>>>>
>>>
>>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: __import__ with dict values

2009-03-12 Thread alex goretoy
Gabriel,

Thank you. This makes sense to me. I will go with sys.modules. Can you give
me a good example how to do it getattr way?

currently I am having this problem in my code. Kinda off subject, but not
entirely. I set default variable in self.opt after that I import
jar.properties into self.opt['properties']. Now my self.opt doesn't have the
same defaults set. in other words we load our configuration properties. Then
we over write any configuration properties with supplied sys.argv[1::]
arguments I am passing my sys.argv to a class and inside the class I use
getopt to get site_name and files_name, also many other variable that
overwrite the configuration that is set from the jar.properties

This was working when I was using exec and eval. I was not able to just use
exec I had to use exec on import and eval on module.module it was wierd, can
someone tell me why?

-Alex Goretoy
http://www.goretoy.com



On Thu, Mar 12, 2009 at 1:00 PM, Gabriel Genellina
wrote:

> En Thu, 12 Mar 2009 09:27:35 -0200, alex goretoy <
> aleksandr.gore...@gmail.com> escribió:
>
>  note i would still like to be able to do __import__("sys")."path"
>>>
>>
> p = __import__("sys").path
>
> That's a convoluted way of doing:
>
> import sys
> p = sys.path
>
> (except that the latter one inserts "sys" in the current namespace)
>
>  maybe if __import__ had __str__ defined, How is my thinking on this?
>>> and how would I achieve something like this?
>>>
>>
> __str__ has absolutely nothing to do.
>
>  __import__(opt['imp_mod']).options
>>
>> eval(opt['imp_mod']+"."+opt['imp_opt'])
>>
>> how to make top work like bottom?
>>
>
> If you think you have to use eval: you don't. Never.
>
> module = __import__(opt['imp_mod'])
> module.options
>
> If the name "options" is not known until runtime, use getattr:
>
> getattr(module, name_of_attribute)
>
> The above assumes you want an attribute (like logging.ERROR). If you want a
> sub-module (a module inside a package) use __import__("dotted.name") and
> then retrieve the module by name from sys.modules; see
> http://docs.python.org/library/functions.html#__import__
>
>
> --
> Gabriel Genellina
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: __import__ with dict values

2009-03-13 Thread alex goretoy
wow, ok, thank you Gabriel, I wasn't aware of x,'y',z

This is what I decided to go with for now in one of my classes, but another
class will need a modified version of this, as mentioned x,'y',z

B=_brush()

list( ( self.__setattr__(x.replace("b_",""),getattr(B,x))  for x in
dir(B) if x.startswith("b_") ) )



-Alex Goretoy
http://www.goretoy.com



On Fri, Mar 13, 2009 at 1:46 AM, Lie Ryan  wrote:

> Gabriel Genellina wrote:
>
>> En Thu, 12 Mar 2009 09:27:35 -0200, alex goretoy <
>> aleksandr.gore...@gmail.com> escribió:
>>
>>  note i would still like to be able to do __import__("sys")."path"
>>>>
>>>
>> p = __import__("sys").path
>>
>> That's a convoluted way of doing:
>>
>> import sys
>> p = sys.path
>>
>> (except that the latter one inserts "sys" in the current namespace)
>>
>
> That's a convoluted way of doing:
>
> from path import sys
>
> (except that the latter one doesn't insert sys in the current namespace)
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: __import__ with dict values

2009-03-14 Thread alex goretoy
>
> I don't get *why* someone would like to write that. Does it look "cool"? Is
> it some kind of "Look, ma, I know those hidden names!" syndrome? Is it
> contagious?
>

I think thats what it is. It does look cool, thats for telling me about the
fact that

prevents the interpreter from doing many optimizations...
>
that makes sense to me, where would I read more about python optimizations?
I want to see code more, I like code, comments are good too :)

I have this piece of code I would like to turn into a generator, can some
one please help me do it?
I want to make it very optimized. The data comes from a options file that is
parsed and used for this header/field function mapping function . I need to
generate this, unless you advise against it then what are my options? How to
wrap my head around this?


def loop_lines(self):
self.soc.me_him(['ENTER:',__name__],self.func_me_color)
print self.lines
for k in range(len(self.lines)): #for every line in csv file
self.line=self.lines[k]
for optv in self.order:
for optvv in self._optv[optv]["headers"]:
if self._optv[optv]["headers"][optvv]!="":

_optvk=string.split(self._optv[optv]["headers"][optvv],",")
for optvk in _optvk:
for optvvv in self._optv[optv]["mappings"]:
if optvk == optvvv:
if
self._optv[optv]["mappings"][optvvv].find("self.fun.func") >= 0:
self.field=optvvv

self.value=self.parsed[k][optvv].replace('"', '\\"').replace("'", "\\'")

try:
exec
(self._optv[optv]["mappings"][optvvv]) #execute custom function
self.last_value=self.value
except NameError, e:
self.soc.w(["\n\nERROR: %s
\n\nFUNCTION or VARIABLE IS DEFINED IN JAR_CONTROLLER" % e],'white_on_red')
sys.exit(1)
#print self.opt['data']

#self.opt['data'][self.field]=self.fun.data[self.field]
#print self.opt['data']
else:
#self.soc.write(["FUNC NOT
FOUND:",pfhpv[pfhpvi],self._pfmp[pfhpv[pfhpvi]]],'red')
#if self._pfmp[pfhpv[pfhpvi]]==
pfhp:

self.opt['data']['defaults'][optv][optvvv]=self.value
self.last_item=self.value
for ff in self.final_funcs.keys():
if self.final_funcs[ff]:
exec ( ff )

self.soc.me_him(['EXIT:',__name__],self.func_me_color)

Thank you,
-Alex Goretoy
http://www.goretoy.com



On Fri, Mar 13, 2009 at 11:56 PM, Gabriel Genellina
wrote:

> prevents the interpreter from doing many optimizations...
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: __import__ with dict values

2009-03-14 Thread alex goretoy
I'm actually still getting to this section of my code, I've been working a
logging,stdout colors lately, Although I am going to need __import__ in
several places in this program

-Alex Goretoy
http://www.goretoy.com



On Sat, Mar 14, 2009 at 3:05 AM, alex goretoy
wrote:

> I don't get *why* someone would like to write that. Does it look "cool"? Is
>> it some kind of "Look, ma, I know those hidden names!" syndrome? Is it
>> contagious?
>>
>
> I think thats what it is. It does look cool, thats for telling me about the
> fact that
>
> prevents the interpreter from doing many optimizations...
>>
> that makes sense to me, where would I read more about python optimizations?
> I want to see code more, I like code, comments are good too :)
>
> I have this piece of code I would like to turn into a generator, can some
> one please help me do it?
> I want to make it very optimized. The data comes from a options file that
> is parsed and used for this header/field function mapping function . I need
> to generate this, unless you advise against it then what are my options? How
> to wrap my head around this?
>
>
> def loop_lines(self):
> self.soc.me_him(['ENTER:',__name__],self.func_me_color)
> print self.lines
> for k in range(len(self.lines)): #for every line in csv file
> self.line=self.lines[k]
> for optv in self.order:
> for optvv in self._optv[optv]["headers"]:
> if self._optv[optv]["headers"][optvv]!="":
>
> _optvk=string.split(self._optv[optv]["headers"][optvv],",")
> for optvk in _optvk:
> for optvvv in self._optv[optv]["mappings"]:
> if optvk == optvvv:
> if
> self._optv[optv]["mappings"][optvvv].find("self.fun.func") >= 0:
> self.field=optvvv
>
> self.value=self.parsed[k][optvv].replace('"', '\\"').replace("'", "\\'")
>
> try:
> exec
> (self._optv[optv]["mappings"][optvvv]) #execute custom function
> self.last_value=self.value
> except NameError, e:
> self.soc.w(["\n\nERROR: %s
> \n\nFUNCTION or VARIABLE IS DEFINED IN JAR_CONTROLLER" % e],'white_on_red')
> sys.exit(1)
> #print self.opt['data']
>
> #self.opt['data'][self.field]=self.fun.data[self.field]
> #print self.opt['data']
> else:
> #self.soc.write(["FUNC NOT
> FOUND:",pfhpv[pfhpvi],self._pfmp[pfhpv[pfhpvi]]],'red')
> #if self._pfmp[pfhpv[pfhpvi]]==
> pfhp:
>
> self.opt['data']['defaults'][optv][optvvv]=self.value
> self.last_item=self.value
> for ff in self.final_funcs.keys():
> if self.final_funcs[ff]:
> exec ( ff )
>
> self.soc.me_him(['EXIT:',__name__],self.func_me_color)
>
> Thank you,
> -Alex Goretoy
> http://www.goretoy.com
>
>
>
> On Fri, Mar 13, 2009 at 11:56 PM, Gabriel Genellina <
> gagsl-...@yahoo.com.ar> wrote:
>
>> prevents the interpreter from doing many optimizations...
>>
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: __import__ with dict values

2009-03-14 Thread alex goretoy
I can show you people more code if you want :) I like to learn
-Alex Goretoy
http://www.goretoy.com



On Sat, Mar 14, 2009 at 3:09 AM, alex goretoy
wrote:

> I'm actually still getting to this section of my code, I've been working a
> logging,stdout colors lately, Although I am going to need __import__ in
> several places in this program
>
> -Alex Goretoy
> http://www.goretoy.com
>
>
>
> On Sat, Mar 14, 2009 at 3:05 AM, alex goretoy  > wrote:
>
>> I don't get *why* someone would like to write that. Does it look "cool"?
>>> Is it some kind of "Look, ma, I know those hidden names!" syndrome? Is it
>>> contagious?
>>>
>>
>> I think thats what it is. It does look cool, thats for telling me about
>> the fact that
>>
>> prevents the interpreter from doing many optimizations...
>>>
>> that makes sense to me, where would I read more about python
>> optimizations?
>> I want to see code more, I like code, comments are good too :)
>>
>> I have this piece of code I would like to turn into a generator, can some
>> one please help me do it?
>> I want to make it very optimized. The data comes from a options file that
>> is parsed and used for this header/field function mapping function . I need
>> to generate this, unless you advise against it then what are my options? How
>> to wrap my head around this?
>>
>>
>> def loop_lines(self):
>> self.soc.me_him(['ENTER:',__name__],self.func_me_color)
>> print self.lines
>> for k in range(len(self.lines)): #for every line in csv file
>> self.line=self.lines[k]
>> for optv in self.order:
>> for optvv in self._optv[optv]["headers"]:
>> if self._optv[optv]["headers"][optvv]!="":
>>
>> _optvk=string.split(self._optv[optv]["headers"][optvv],",")
>> for optvk in _optvk:
>> for optvvv in self._optv[optv]["mappings"]:
>> if optvk == optvvv:
>> if
>> self._optv[optv]["mappings"][optvvv].find("self.fun.func") >= 0:
>> self.field=optvvv
>>
>> self.value=self.parsed[k][optvv].replace('"', '\\"').replace("'", "\\'")
>>
>> try:
>> exec
>> (self._optv[optv]["mappings"][optvvv]) #execute custom function
>> self.last_value=self.value
>> except NameError, e:
>> self.soc.w(["\n\nERROR: %s
>> \n\nFUNCTION or VARIABLE IS DEFINED IN JAR_CONTROLLER" % e],'white_on_red')
>> sys.exit(1)
>> #print self.opt['data']
>>
>> #self.opt['data'][self.field]=self.fun.data[self.field]
>> #print self.opt['data']
>> else:
>> #self.soc.write(["FUNC NOT
>> FOUND:",pfhpv[pfhpvi],self._pfmp[pfhpv[pfhpvi]]],'red')
>> #if self._pfmp[pfhpv[pfhpvi]]==
>> pfhp:
>>
>> self.opt['data']['defaults'][optv][optvvv]=self.value
>> self.last_item=self.value
>> for ff in self.final_funcs.keys():
>> if self.final_funcs[ff]:
>> exec ( ff )
>>
>> self.soc.me_him(['EXIT:',__name__],self.func_me_color)
>>
>> Thank you,
>> -Alex Goretoy
>> http://www.goretoy.com
>>
>>
>>
>> On Fri, Mar 13, 2009 at 11:56 PM, Gabriel Genellina <
>> gagsl-...@yahoo.com.ar> wrote:
>>
>>> prevents the interpreter from doing many optimizations...
>>>
>>
>>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: __import__ with dict values

2009-03-14 Thread alex goretoy
This is a chunk of what its starting to look like now, thanks

from colors import _available_colors as _ck
from has_colors import _has_colors as _ha
from log import _brush as _er

class stdout_colors(object):
def
__init__(self,colors_active=1,output_caller=1,caller_color="red",default=1,
show_lineno_write=1,show_lineno_caller=1,break_all=1,
logging=1,log_type="INFO",depth=10):
self.caller_color = caller_color #stdout_colors function caller
called output color
self.output_caller = output_caller # output caller and called
function
self.colors_active = colors_active #active colors for output

self.colors = _ck().colors


crack=_er(colors_active,default,show_lineno_write,show_lineno_caller,
break_all,logging,log_type,depth)

#Thanks Gabriel Genellina, no crack was smoked during the making
#list( ( self.__setattr__(x.replace("b_",""),getattr(B,x))  for x in
dir(B) if x.startswith("b_") ) )
for smoke in dir(crack):
if smoke.startswith("b_"):
    setattr(self, smoke[2:], getattr(crack, smoke))
-Alex Goretoy
http://www.goretoy.com



On Sat, Mar 14, 2009 at 3:13 AM, alex goretoy
wrote:

> I can show you people more code if you want :) I like to learn
> -Alex Goretoy
> http://www.goretoy.com
>
>
>
> On Sat, Mar 14, 2009 at 3:09 AM, alex goretoy  > wrote:
>
>> I'm actually still getting to this section of my code, I've been working a
>> logging,stdout colors lately, Although I am going to need __import__ in
>> several places in this program
>>
>> -Alex Goretoy
>> http://www.goretoy.com
>>
>>
>>
>> On Sat, Mar 14, 2009 at 3:05 AM, alex goretoy <
>> aleksandr.gore...@gmail.com> wrote:
>>
>>> I don't get *why* someone would like to write that. Does it look "cool"?
>>>> Is it some kind of "Look, ma, I know those hidden names!" syndrome? Is it
>>>> contagious?
>>>>
>>>
>>> I think thats what it is. It does look cool, thats for telling me about
>>> the fact that
>>>
>>> prevents the interpreter from doing many optimizations...
>>>>
>>> that makes sense to me, where would I read more about python
>>> optimizations?
>>> I want to see code more, I like code, comments are good too :)
>>>
>>> I have this piece of code I would like to turn into a generator, can some
>>> one please help me do it?
>>> I want to make it very optimized. The data comes from a options file that
>>> is parsed and used for this header/field function mapping function . I need
>>> to generate this, unless you advise against it then what are my options? How
>>> to wrap my head around this?
>>>
>>>
>>> def loop_lines(self):
>>> self.soc.me_him(['ENTER:',__name__],self.func_me_color)
>>> print self.lines
>>> for k in range(len(self.lines)): #for every line in csv file
>>> self.line=self.lines[k]
>>> for optv in self.order:
>>> for optvv in self._optv[optv]["headers"]:
>>> if self._optv[optv]["headers"][optvv]!="":
>>>
>>> _optvk=string.split(self._optv[optv]["headers"][optvv],",")
>>> for optvk in _optvk:
>>> for optvvv in self._optv[optv]["mappings"]:
>>> if optvk == optvvv:
>>> if
>>> self._optv[optv]["mappings"][optvvv].find("self.fun.func") >= 0:
>>> self.field=optvvv
>>>
>>> self.value=self.parsed[k][optvv].replace('"', '\\"').replace("'", "\\'")
>>>
>>> try:
>>> exec
>>> (self._optv[optv]["mappings"][optvvv]) #execute custom function
>>> self.last_value=self.value
>>> except NameError, e:
>>> self.soc.w(["\n\nERROR: %s
>>> \n\nFUNCTION or VARIABLE IS DEFINED IN JAR_CONTROLLER" % e],'white_on_red')
>>>     sys.exit(1)
>>> #print self.opt['data

Re: converting a string to a function parameter

2009-03-14 Thread alex goretoy
My new class I've been working on might help you. It does what you are
asking without eval (I'm still working on it) Anyone have any ideas aswell
along with the OP, thank you

#!/usr/bin env python
#
# -*- coding: UTF-8 -*-
#
# PyNutButter BETA Version 0.1.0.1
#
# Copyright 2009 - Infinity by Alex Goretoy, All Rights Reserved.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and that
# both that copyright notice and this permission notice appear in
# supporting documentation, and that the name of Vinay Sajip
# not be used in advertising or publicity pertaining to distribution
# of the software without specific, written prior permission.
# VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING
# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
# VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES
OR
# ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER
# IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# SEE ALSO LICENSE FILE IN PROJECT ROOT DIRECTORY
#
__author__  = "Aleksandr Ilyich Goretoy "
__status__  = "beta"
__version__ = "0.1.0.1"
__date__= "14 March 2009"

import sys, os


from colors import colors as _ck
from has_colors import _has_colors as _ha
from logg import _brush as _ers

class colors(object):
def
__init__(self,colors_active=1,output_caller=1,caller_color="red",default=1,
show_lineno_write=1,show_lineno_caller=1,break_all=1,
logging=1,log_type="INFO",depth=10):
"""
stdout colorization class - prints messages in color to stdout

colors_active - output to stdout in color? 1 or 0
output_caller - print output when control enters this
class/functions ,output caller and called function
caller_color - color to use to output caller only if output_caller
is 1
"""

self.caller_color = caller_color #stdout_colors function caller
called output color
self.output_caller = output_caller # output caller and called
function
self.colors_active = colors_active #active colors for output

self.has_colors = _ha(sys.stdout)
self.colors = _ck
crack=_ers(logger="simpleExample",level="INFO",

log_file=log_file=os.environ["PWD"]+"/logs/eggo",spc=1,brk=1,slk=1,fn=1)

#Thanks Gabriel Genellina, no crack was smoked while making crack
like this
#list( ( self.__setattr__(x.replace("b_",""),getattr(B,x))  for x in
dir(B) if x.startswith("b_") ) )
for smoke in dir(crack):
if smoke.startswith("b_"):
setattr(self, smoke[2:], getattr(crack, smoke))

"""
these colors may not be correct: depending on how you have your
terminal configured
"""

#if self.output_caller:
#self.me_him(['ENTER COLORS',__name__],self.caller_color)


"""
color and value
"""
self.color="default"#display color
self.value=""#used to store displayed message


def w(self,value,color="red",level="INFO"):
self.write(value,color,level)
def write(self,value,color="red",level="INFO"):
"""
write - output message,take value string or list,color=""
"""
self._hero(value,color,level)


def h(self,color="red",level="DEBUG"):
self.him(color,level)
def him(self,color="red",level="DEBUG"):
"""
him - determines caller function name, takes color=""
"""

if self.output_caller:

value=sys._getframe(2).f_code.co_name#+inspect.currentframe().f_back.f_lineno
self._hero(value,color,level)

def m_h(self,value,color="purple",level="DEBUG"):
self.me_him(value,color,level)
def me_him(self,value,color="purple",log_type="DEBUG"):
"""
me_him - determines current function prepends class name and
displays caller function
"""
if self.output_caller:



value="".join(value)+"."+sys._getframe(1).f_code.co_name+self.colors['default']+sys._getframe(2).f_code.co_name+"\x1b[00m"

self._hero(value,color,level)

def m(self,value,color="blue",level="DEBUG"):
se

Re: converting a string to a function parameter

2009-03-14 Thread alex goretoy
This is a file that is going into the new version of python-stdout-colors

> project location:
> http://code.google.com/p/python-stdout-colors/


-Alex Goretoy
http://www.goretoy.com



On Sat, Mar 14, 2009 at 10:45 AM, alex goretoy
wrote:

> My new class I've been working on might help you. It does what you are
> asking without eval (I'm still working on it) Anyone have any ideas aswell
> along with the OP, thank you
>
> #!/usr/bin env python
> #
> # -*- coding: UTF-8 -*-
> #
> # PyNutButter BETA Version 0.1.0.1
> #
> # Copyright 2009 - Infinity by Alex Goretoy, All Rights Reserved.
> #
> # Permission to use, copy, modify, and distribute this software and its
> # documentation for any purpose and without fee is hereby granted,
> # provided that the above copyright notice appear in all copies and that
> # both that copyright notice and this permission notice appear in
> # supporting documentation, and that the name of Vinay Sajip
> # not be used in advertising or publicity pertaining to distribution
> # of the software without specific, written prior permission.
> # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
> INCLUDING
> # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
> # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES
> OR
> # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
> WHETHER
> # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
> OUT
> # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
> #
> # SEE ALSO LICENSE FILE IN PROJECT ROOT DIRECTORY
> #
> __author__  = "Aleksandr Ilyich Goretoy "
> __status__  = "beta"
> __version__ = "0.1.0.1"
> __date__= "14 March 2009"
>
> import sys, os
>
>
> from colors import colors as _ck
> from has_colors import _has_colors as _ha
> from logg import _brush as _ers
>
> class colors(object):
> def
> __init__(self,colors_active=1,output_caller=1,caller_color="red",default=1,
> show_lineno_write=1,show_lineno_caller=1,break_all=1,
> logging=1,log_type="INFO",depth=10):
> """
> stdout colorization class - prints messages in color to stdout
>
> colors_active - output to stdout in color? 1 or 0
> output_caller - print output when control enters this
> class/functions ,output caller and called function
> caller_color - color to use to output caller only if output_caller
> is 1
> """
>
> self.caller_color = caller_color #stdout_colors function caller
> called output color
> self.output_caller = output_caller # output caller and called
> function
> self.colors_active = colors_active #active colors for output
>
> self.has_colors = _ha(sys.stdout)
> self.colors = _ck
> crack=_ers(logger="simpleExample",level="INFO",
>
> log_file=log_file=os.environ["PWD"]+"/logs/eggo",spc=1,brk=1,slk=1,fn=1)
>
> #Thanks Gabriel Genellina, no crack was smoked while making crack
> like this
> #list( ( self.__setattr__(x.replace("b_",""),getattr(B,x))  for x
> in dir(B) if x.startswith("b_") ) )
> for smoke in dir(crack):
> if smoke.startswith("b_"):
> setattr(self, smoke[2:], getattr(crack, smoke))
>
> """
> these colors may not be correct: depending on how you have your
> terminal configured
> """
>
> #if self.output_caller:
> #self.me_him(['ENTER COLORS',__name__],self.caller_color)
>
>
> """
> color and value
> """
> self.color="default"#display color
> self.value=""#used to store displayed message
>
>
> def w(self,value,color="red",level="INFO"):
> self.write(value,color,level)
> def write(self,value,color="red",level="INFO"):
> """
> write - output message,take value string or list,color=""
> """
> self._hero(value,color,level)
>
>
> def h(self,color="red",level="DEBUG"):
> self.him(color,level)
> def him(self,color="red",level="DEBUG"):
> """
> him - determines caller function name, takes color=""
> """
>
> if self.output

how to repeat function definitions less

2009-03-14 Thread alex goretoy
I'm doing this in my code, how to make it define all this functions for me
with lambda, I've been up for a while and cant seem to figure it out, whats
the most efficient way to do it? with lambda? how? thx

def red(self,value,color='red',level='INFO'):
self.write(value,color,level)
def gold(self,value,color='gold',level='INFO'):
self.write(value,color,level)
def green(self,value,color='green',level='INFO'):
self.write(value,color,level)
def blue(self,value,color='blue',level='INFO'):
self.write(value,color,level)
def yellow(self,value,color='yellow',level='INFO'):
self.write(value,color,level)
def purple(self,value,color='purple',level='INFO'):
self.write(value,color,level)
def w_red(self,value,color='white_on_red',level='INFO'):
self.write(value,color,level)
def w_gold(self,value,color='white_on_gold',level='INFO'):
self.write(value,color,level)
def w(self,value,color="red",level="INFO"):
self.write(value,color,level)
def write(self,value,color="red",level="INFO"):
"""
write - output message,take value string or list,color=""
"""
self._hero(value,color,level)


-Alex Goretoy
http://www.goretoy.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to repeat function definitions less

2009-03-14 Thread alex goretoy
12
elif __options[0] in ("opt","option","options"):
print (__options[0], __options[1])
if __options[1]  is not  "":
self.opt['properties']['imp_opt'] =
"".join(__options[1])
self.soc.debug( "%s"%("args imp_opt:
",self.opt['properties']['imp_opt']) )

#XXX#13
elif __options[0] in ("set","setting","settings"):
print (__options[0], __options[1])
if __options[1]  is not  "":
self.opt['properties']['imp_set'] =
"".join(__options[1])
self.soc.debug( "%s"%("args imp_set:
",self.opt['properties']['imp_set']) )

#XXX#14
elif __options[0] in ("file","files"):
print (__options[0], __options[1])
if __options[1]  is not  "":
self.opt['properties']['imp_files'] =
"".join(__options[1])
self.soc.debug( "%s"%("args imp_files:
",self.opt['properties']['imp_files']) )

#XXX#15
elif __options[0] in ("flav","flavor","flavors"):
print (__options[0], __options[1])
if __options[1]  is not  "":
self.opt['properties']['imp_flavors'] =
"".join(__options[1])
self.soc.debug( "%s"%("args imp_flavors:
",self.opt['properties']['imp_flavors']) )

elif __options[0] in
("down","download","downloads","file_download"):
print (__options[0], __options[1])
if __options[1]  is not  "":
self.opt['properties']['imp_downloads'] =
"".join(__options[1])
self.soc.debug( "%s"%("args imp_downloads:
",self.opt['properties']['imp_downloads']) )

-Alex Goretoy
http://www.goretoy.com



On Sat, Mar 14, 2009 at 6:54 PM, MRAB  wrote:

>
>def write(self, value, color="red", level="INFO"):
>print "value=%s, color=%s, level=%s" % (repr(value), repr(color),
> repr(level))
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to repeat function definitions less

2009-03-14 Thread alex goretoy
I would imagine that I could do this with a generator and setattr, but I am
still learning how to do that kinda of codingmaybe if I had a dictionary
like this and then loaded it

d={
"site_name":["s","site",'sites','site_name','site_names'],
"jar_name":["j","jar",'jars','jar_name','jar_names'],
...
}

Once again, I haven't been sleeping regularly latelyworking on
pynutbutter 24/7...Thanks for all your help

-Alex Goretoy
http://www.goretoy.com



On Sat, Mar 14, 2009 at 10:02 PM, alex goretoy
wrote:

> Nice, this is good code. Thank you. Seeing as we are still on the same
> subject, how would I do it on sysarg values from getopt?
>
> I have a main method defined like so
>
> def main(self):
> #XXX
> """
> 1
> #get site_name: prepend to curl get/post requests
> #this overrides what it is in the jar
>
> 2
> #get jar_name: jar_name used in directory for
> sys.path.append
> #import jar_name and loading jar_name.options and
> jar_name.settings
> #cmdline var o|options overrides default jar options and
> settings
>
> 3
> #get file_name: parse this file for upload
> #this is optional, you can specify it in the jar options
> #overrides jar specified files to load. makes this the main
> file
> #only works with one file this way
>
> 4
> #get verbose = 0:default 1:function/caller output 2:curl
> get/post requests/responses
> #this is optional, default is 0
> #still not working how it should, it's on the todo list
>
> 5
> #flavors/butterknives to load with the jar, eg. mysql,
> curl, csvparser support
> #with plans for urllib, httplib,https, oracle, postgres,
> mssql
> #it is not hard to also add support for user defined custom
> protocols this way
> #then just define your mapped functions inside jar
> configuration directories
> #specifying this here option in the terminal overrides what
> is configured in the jar conf
>
> 6
> #final functions to execute upon completion of all function
> mappings and exec for each line
>
> 7
> #file to download and parse, this overrides disregards
> file_name if passed in simutaniously
> #to be used with remote files, located on http/s/ftp etc...
> it fetches the file and stores it
> #under the key() as the name, which is to be concurrent
> with keys in files, so that we know which is main
> #works with multiple files
>
> 8
> #colors - allows you to specify what colors to use for
> output of caller/called functions, etc...
>
> 9
> #specify source for options to be loaded from
> #you can specify custom option modules w/ attr & settings
> to load
> #todo: implement using options from db
> #todo: implement getting data from different sources other
> than csv files
>
> 10
> #source of our configuration, only jars files work
> for now
> #currently default is storing configuration
> settings in jars files
>
> 11
> # This is the jar conf file located in the jar
> directory
> #it is imported for getting
> options/settings/mappings/etc...
> #name of module to load which is located inside the
> jar dir
>
> 12
> # jar configuration options attribute( dict that
> holds all mappings and functions, located in jar conf )
> # name of options dictionary that hold all jar
> options/mapping etc...
>
> 13
> #jar configuration settings attribute (dict that
> holds all settings, located in jar conf file)
> #name of our settings dictionary that holds all jar
> settings
>
> 14
> #jar file settings
> #secondary file to parse and use inside you
> functions
>
> """
> for _argsi in range(len("".join(self.args).split('='))-1):
> _args=self.args[_argsi].split("=")
> print ("printing A:",_args)
> #XXX#1
> if _arg

Re: how to repeat function definitions less

2009-03-14 Thread alex goretoy
sweet, I've been wondering how those work. I've read some stuff about them
and still doesn't make sense to me. Why would I want to use itPlease
explain, thank you
-Alex Goretoy
http://www.goretoy.com



On Sun, Mar 15, 2009 at 1:05 AM, Michele Simionato <
michele.simion...@gmail.com> wrote:

> On Mar 15, 12:09 am, s...@pobox.com wrote:
> > I'm doing this in my code, how to make it define all this functions
> for me
> > with lambda, I've been up for a while and cant seem to figure it out,
> whats
> > the most efficient way to do it? with lambda? how? thx
> >
> > def red(self,value,color='red',level='INFO'):
> > self.write(value,color,level)
> > def gold(self,value,color='gold',level='INFO'):
> > self.write(value,color,level)
> > ...
>
> The first thing coming to my mind is a class decorator:
>
> def addcolors(*colors):
>def dec(cls):
>for color in colors:
>def col(self, value, color=color, level='INFO'):
> self.write(value, color, level)
> col.__name__ = color
>setattr(cls, color, col)
>return cls
>return dec
>
> @addcolors('red', 'gold')
> class C(object):
>def write(self, value, color, level):
>pass
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


suggestion for python function calling

2009-03-14 Thread alex goretoy
hi i have a suggestion, surely this wont wonk, and is merely a suggestion to
aedd this type of syntax to python

This is an insperation from peps 318

> def foo(self):
> perform method operation
> foo = classmethod(foo)
>
> where it says perform mthod operation, why not have that be an actual
syntax?
having those words initialized as functions lists dict generators, etc...

 then you could do something like:

new_variable = function variable function variable

duck = if os.path.walk talk must _duck

or something to this nature and then you could either make it call functions
later

duck().().()
or
fuck(().())
or
something like that, I'mma go to sleep nowI think this way it might the
language even stonger, but who knows, what do you all think? Not trying to
make it like ruby, just more options to the interpreter, and syntax styles
-Alex Goretoy
http://www.goretoy.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: suggestion for python function calling

2009-03-15 Thread alex goretoy
basically

import os
def quacks(self,value):
return (1,0)[value]
_aduck="~/goose"
duck = if os.path.exists quacks str(_aduck)
duck()()

or does this get in the way with some other pre-existing syntax
interpretation implementations?

-Alex Goretoy
http://www.goretoy.com



On Sun, Mar 15, 2009 at 1:54 AM, alex goretoy
wrote:

> hi i have a suggestion, surely this wont wonk, and is merely a suggestion
> to aedd this type of syntax to python
>
> This is an insperation from peps 318
>
>> def foo(self):
>> perform method operation
>> foo = classmethod(foo)
>>
>> where it says perform mthod operation, why not have that be an actual
> syntax?
> having those words initialized as functions lists dict generators, etc...
>
>  then you could do something like:
>
> new_variable = function variable function variable
>
> duck = if os.path.walk talk must _duck
>
> or something to this nature and then you could either make it call
> functions later
>
> duck().().()
> or
> fuck(().())
> or
> something like that, I'mma go to sleep nowI think this way it might the
> language even stonger, but who knows, what do you all think? Not trying to
> make it like ruby, just more options to the interpreter, and syntax styles
> -Alex Goretoy
> http://www.goretoy.com
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: suggestion for python function calling

2009-03-15 Thread alex goretoy
actually it would be more like

import os
def quacks(value):
return "%s/%s%s"% (os.environ["PWD"],os.path.dirname(__file__),value)
_aduck="goose"
duck = if is not os.path.exists quacks str(_aduck)


to perform the calls
duck()()

this would only with with functions that return something though, I
believe


-Alex Goretoy
http://www.goretoy.com



On Sun, Mar 15, 2009 at 2:08 AM, alex goretoy
wrote:

> import os
> def quacks(self,value):
> return (1,0)[value]
> _aduck="~/goose"
> duck = if os.path.exists quacks str(_aduck)
> duck()()
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: suggestion for python function calling

2009-03-15 Thread alex goretoy
or use . (dot) where variable and () (parans) where function

duck()().
or
duck.().()
or
for long sentences
duck.[].()()...

using dot seperator or double dot separator for application where its
currently not being used, but for syntax errors
-Alex Goretoy
http://www.goretoy.com



On Sun, Mar 15, 2009 at 2:15 AM, alex goretoy
wrote:

> actually it would be more like
>
> import os
> def quacks(value):
> return "%s/%s%s"% (os.environ["PWD"],os.path.dirname(__file__),value)
> _aduck="goose"
> duck = if is not os.path.exists quacks str(_aduck)
>
>
> to perform the calls
> duck()()
>
> this would only with with functions that return something though, I
> believe
>
>
> -Alex Goretoy
> http://www.goretoy.com
>
>
>
> On Sun, Mar 15, 2009 at 2:08 AM, alex goretoy  > wrote:
>
>> import os
>> def quacks(self,value):
>> return (1,0)[value]
>> _aduck="~/goose"
>> duck = if os.path.exists quacks str(_aduck)
>> duck()()
>>
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: suggestion for python function calling

2009-03-15 Thread alex goretoy
maybe this is like decorators
-Alex Goretoy
http://www.goretoy.com



On Sun, Mar 15, 2009 at 2:20 AM, alex goretoy
wrote:

> or use . (dot) where variable and () (parans) where function
>
> duck()().
> or
> duck.().()
> or
> for long sentences
> duck.[].()()...
>
> using dot seperator or double dot separator for application where its
> currently not being used, but for syntax errors
> -Alex Goretoy
> http://www.goretoy.com
>
>
>
> On Sun, Mar 15, 2009 at 2:15 AM, alex goretoy  > wrote:
>
>> actually it would be more like
>>
>> import os
>> def quacks(value):
>> return "%s/%s%s"% (os.environ["PWD"],os.path.dirname(__file__),value)
>> _aduck="goose"
>> duck = if is not os.path.exists quacks str(_aduck)
>>
>>
>> to perform the calls
>> duck()()
>>
>> this would only with with functions that return something though, I
>> believe
>>
>>
>> -Alex Goretoy
>> http://www.goretoy.com
>>
>>
>>
>> On Sun, Mar 15, 2009 at 2:08 AM, alex goretoy <
>> aleksandr.gore...@gmail.com> wrote:
>>
>>> import os
>>> def quacks(self,value):
>>> return (1,0)[value]
>>> _aduck="~/goose"
>>> duck = if os.path.exists quacks str(_aduck)
>>> duck()()
>>>
>>
>>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to repeat function definitions less

2009-03-15 Thread alex goretoy
I will also actually need to nest it like so

d={
   "site_name":["s","site",'
>
> sites','site_name','site_names'],
>"jar_name":["j","jar",'jars','jar_name','jar_names'],

    "options":{
"src_name":["ss","src","source"],
"mod_name":['m',"mod",'mods',"module","modules"],
}

-Alex Goretoy
http://www.goretoy.com



On Sun, Mar 15, 2009 at 10:51 AM, MRAB  wrote:

> d={
>>"site_name":["s","site",'sites','site_name','site_names'],
>>"jar_name":["j","jar",'jars','jar_name','jar_names'],
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to repeat function definitions less

2009-03-15 Thread alex goretoy
this means i have to check if d[i] is list or dict and iterate over
properties
-Alex Goretoy
http://www.goretoy.com



On Sun, Mar 15, 2009 at 1:03 PM, alex goretoy
wrote:

> I will also actually need to nest it like so
>
> d={
>"site_name":["s","site",'
>>
>> sites','site_name','site_names'],
>>"jar_name":["j","jar",'jars','jar_name','jar_names'],
>
> "options":{
> "src_name":["ss","src","source"],
> "mod_name":['m',"mod",'mods',"module","modules"],
> }
>
> -Alex Goretoy
> http://www.goretoy.com
>
>
>
> On Sun, Mar 15, 2009 at 10:51 AM, MRAB  wrote:
>
>> d={
>>>"site_name":["s","site",'sites','site_name','site_names'],
>>>"jar_name":["j","jar",'jars','jar_name','jar_names'],
>>
>>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to repeat function definitions less

2009-03-15 Thread alex goretoy
this is what I did to define all my color functions by color name, but I am
still going to need a good solution for args

#import functions by color name into current namespace
> for color in self.colors.keys():
> setattr(self, color,lambda x,y=color,z="INFO":
> self._hero(x,y,z) )
>

Thanks to all of you for helping me learn python

-Alex Goretoy
http://www.goretoy.com



On Sun, Mar 15, 2009 at 1:05 PM, alex goretoy
wrote:

> this means i have to check if d[i] is list or dict and iterate over
> properties
> -Alex Goretoy
> http://www.goretoy.com
>
>
>
> On Sun, Mar 15, 2009 at 1:03 PM, alex goretoy  > wrote:
>
>> I will also actually need to nest it like so
>>
>> d={
>>"site_name":["s","site",'
>>>
>>> sites','site_name','site_names'],
>>>"jar_name":["j","jar",'jars','jar_name','jar_names'],
>>
>> "options":{
>> "src_name":["ss","src","source"],
>> "mod_name":['m',"mod",'mods',"module","modules"],
>> }
>>
>> -Alex Goretoy
>> http://www.goretoy.com
>>
>>
>>
>> On Sun, Mar 15, 2009 at 10:51 AM, MRAB wrote:
>>
>>> d={
>>>>"site_name":["s","site",'sites','site_name','site_names'],
>>>>"jar_name":["j","jar",'jars','jar_name','jar_names'],
>>>
>>>
>>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to repeat function definitions less

2009-03-15 Thread alex goretoy
Michele I tried your way but I dont seem to have a good grasp on the concept
yet, will read up more

for now I think I will try to make it work same way as colors only with
decorator as def inside def instead of @, that doesn't make sense quite yet

-Alex Goretoy
http://www.goretoy.com



On Sun, Mar 15, 2009 at 3:12 PM, alex goretoy
wrote:

> this is what I did to define all my color functions by color name, but I am
> still going to need a good solution for args
>
> #import functions by color name into current namespace
>> for color in self.colors.keys():
>> setattr(self, color,lambda x,y=color,z="INFO":
>> self._hero(x,y,z) )
>>
>
> Thanks to all of you for helping me learn python
>
> -Alex Goretoy
> http://www.goretoy.com
>
>
>
> On Sun, Mar 15, 2009 at 1:05 PM, alex goretoy  > wrote:
>
>> this means i have to check if d[i] is list or dict and iterate over
>> properties
>> -Alex Goretoy
>> http://www.goretoy.com
>>
>>
>>
>> On Sun, Mar 15, 2009 at 1:03 PM, alex goretoy <
>> aleksandr.gore...@gmail.com> wrote:
>>
>>> I will also actually need to nest it like so
>>>
>>> d={
>>>"site_name":["s","site",'
>>>>
>>>> sites','site_name','site_names'],
>>>>"jar_name":["j","jar",'jars','jar_name','jar_names'],
>>>
>>> "options":{
>>> "src_name":["ss","src","source"],
>>> "mod_name":['m',"mod",'mods',"module","modules"],
>>> }
>>>
>>> -Alex Goretoy
>>> http://www.goretoy.com
>>>
>>>
>>>
>>> On Sun, Mar 15, 2009 at 10:51 AM, MRAB wrote:
>>>
>>>> d={
>>>>>"site_name":["s","site",'sites','site_name','site_names'],
>>>>>"jar_name":["j","jar",'jars','jar_name','jar_names'],
>>>>
>>>>
>>>
>>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to repeat function definitions less

2009-03-15 Thread alex goretoy
this is the final result of the args i will be parsing for now

d={
"site_name":["s","sn","site",'sites','site_name','site_names'],
"jar_name":["j","jn","jar",'jars','jar_name','jar_names'],

"file_name":["f","fn",'file','files','filename','filenames','file_name','file_names'],
"verbose":["v","vv","vvv",'verbose','verbosity'],
"flavors":["fff","flav","flavor","flavors"],

"final_funcs":["ff","finfun",'fin_fun',"final_func",'final_funct',"final_funcs",

'final_functs',"final_function","final_functions"],

"download_files":["d",'df',"down",'down_file','down_files',"download",
"downloads",'download_file','download_files'],

"colors":["c","cl","col","colo","color","colors",'reaper','reapers'],
"options":{
"imp_src":['ss',"src","source","sources"],
"imp_mod":['m',"mod",'mods',"module","modules"],

"imp_opt":['o',"oo","opt",'opts',"option","options"],

"imp_set":['s','ss',"sss","set","setting","settings"],

"imp_files":["f","fn",'file','files','filename','filenames','file_name','file_names'],
    "imp_flavors":["fff","flav","flavor","flavors"],

"imp_funcs":["ff","finfun",'fin_fun',"final_func",'final_funct',"final_funcs",

'final_functs',"final_function","final_functions"],

"imp_downloads":["d",'df',"down",'down_file','down_files',"download",

"downloads",'download_file','download_files'],

"imp_colors":["c","cl","col","colo","color","colors",'reaper','reapers'],

"imp_properties":["p","prop","property","properties"]

    },
"properties":["p","prop","property","properties"]
}

pynutbutter will be really good soon, thx for your help :) I'm glad to be
doing this in python

-Alex Goretoy
http://www.goretoy.com



On Sun, Mar 15, 2009 at 3:30 PM, alex goretoy
wrote:

> Michele I tried your way but I dont seem to have a good grasp on the
> concept yet, will read up more
>
> for now I think I will try to make it work same way as colors only with
> decorator as def inside def instead of @, that doesn't make sense quite yet
>
> -Alex Goretoy
> http://www.goretoy.com
>
>
>
> On Sun, Mar 15, 2009 at 3:12 PM, alex goretoy  > wrote:
>
>> this is what I did to define all my color functions by color name, but I
>> am still going to need a good solution for args
>>
>> #import functions by color name into current namespace
>>> for color in self.colors.keys():
>>> setattr(self, color,lambda x,y=color,z="INFO":
>>> self._hero(x,y,z) )
>>>
>>
>> Thanks to all of you for helping me learn python
>>
>> -Alex Goretoy
>> http://www.goretoy.com
>>
>>
>>
>> On Sun, Mar 15, 2009 at 1:05 PM, alex goretoy <
>> aleksandr.gore...@gmail.com> wrote:
>>
>>> this means i have to check if d[i] is list or dict and iterate over
>>> properties
>>> -Alex Goretoy
>>> http://www.goretoy.com
>>>
>>>
>>>
>>> On Sun, Mar 15, 2009 at 1:03 PM, alex goretoy <
>>> aleksandr.gore...@gmail.com> wrote:
>>>
>>>> I will also actually need to nest it like so
>>>>
>>>> d={
>>>>"site_name":["s","site",'
>>>>>
>>>>> sites','site_name','site_names'],
>>>>>"jar_name":["j","jar",'jars','jar_name','jar_names'],
>>>>
>>>> "options":{
>>>> "src_name":["ss","src","source"],
>>>> "mod_name":['m',"mod",'mods',"module","modules"],
>>>> }
>>>>
>>>> -Alex Goretoy
>>>> http://www.goretoy.com
>>>>
>>>>
>>>>
>>>> On Sun, Mar 15, 2009 at 10:51 AM, MRAB wrote:
>>>>
>>>>> d={
>>>>>>"site_name":["s","site",'sites','site_name','site_names'],
>>>>>>"jar_name":["j","jar",'jars','jar_name','jar_names'],
>>>>>
>>>>>
>>>>
>>>
>>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to repeat function definitions less

2009-03-15 Thread alex goretoy
ok now for the final result, i decided to split options out to a separate
dict of lists, does this look right to every one, I currently have error
somewhere else in my code so can't test this right now, Is this a good
method to do this? or is there another option?

self.opt={}
self.opt['arg_opts_options']={
"imp_src":['ss',"src","source","sources"],
"imp_mod":['m',"mod",'mods',"module","modules"],
"imp_opt":['o',"oo","opt",'opts',"option","options"],
"imp_set":['s','ss',"sss","set","setting","settings"],

"imp_files":["f","fn",'file','files','filename','filenames','file_name','file_names'],
"imp_flavors":["fff","flav","flavor","flavors"],

"imp_funcs":["ff","finfun",'fin_fun',"final_func",'final_funct',"final_funcs",

'final_functs',"final_function","final_functions"],

"imp_downloads":["d",'df',"down",'down_file','down_files',"download",

"downloads",'download_file','download_files'],

"imp_colors":["c","cl","col","colo","color","colors",'reaper','reapers'],
"imp_properties":["p","prop","property","properties"]
}
self.opt['arg_opts']={
"site_name":["s","sn","site",'sites','site_name','site_names'],
"jar_name":["j","jn","jar",'jars','jar_name','jar_names'],

"file_name":["f","fn",'file','files','filename','filenames','file_name','file_names'],
"verbose":["v","vv","vvv",'verbose','verbosity'],
"flavors":["fff","flav","flavor","flavors"],

"final_funcs":["ff","finfun",'fin_fun',"final_func",'final_funct',"final_funcs",

'final_functs',"final_function","final_functions"],

"download_files":["d",'df',"down",'down_file','down_files',"download",
"downloads",'download_file','download_files'],

"colors":["c","cl","col","colo","color","colors",'reaper','reapers'],
"options":['o','opt','option',"options"],
"properties":["p","prop","property","properties"]
}

def main(self):
def _set_arg(a,b):
for k,v in self.opt['arg_opts']:

if a in v:
if a in ["colors","flavors",'final_funcs']:
if b is not "":
_b=b.split(',')
for c in range(len(_b)):
_c=_b[c].split(":")
if _c[1] is not "":
setattr(self,
opt['properties']['flavors'][_c[0]], _c[1])
self.soc.debug("%s"%("args "+k+":
",self.opt['properties'][k]))
elif a is "download_files":
    if b is not "":
        if bool(b):
print ("\nDOWNLOAD FILES",b)
self.opt['properties']['settings'][a] = 1
self.soc.debug( "%s"%("args "+a+":
",self.opt['properties']['settings'][a]) )
if b.find("://") > -1:
_b=b.split(";")
if _b[1] is not "":

self.opt['properties']['file_downloads'][_b[0]]=_b[1]
   

Re: how to repeat function definitions less

2009-03-15 Thread alex goretoy
i did this because this will read colors into a nested variable

How would i make this work the way you suggest? I already have it working
now :)

Not able to set to dict value with setattr, how to do this too(sorry if off
subject)?

I can set it like this:

for i in self.opt['properties'].keys():
self.opt[i] = getattr(self.opt['properties_object'],
i)
but not like this:
for i in self.opt['properties'].keys():
setattr(self, opt[i],
getattr(self.opt['properties_object'], i))
-Alex Goretoy
http://www.goretoy.com



On Sun, Mar 15, 2009 at 6:41 PM, MRAB  wrote:

> alex goretoy wrote:
>
>> ok now for the final result, i decided to split options out to a separate
>> dict of lists, does this look right to every one, I currently have error
>> somewhere else in my code so can't test this right now, Is this a good
>> method to do this? or is there another option?
>>
>>  [snip]
> First of all, *don't use "is" and "is not" to test for equality*; use "=="
> and "!=".
>
> When you split the options out like that you get duplication.
>
> You have, for example:
>
>...
>"colors": ["c", "cl", "col", ...]
>...
>
> and:
>
>...
>"imp_colors": ["c", "cl", "col", ...]
>...
>
> Couldn't you put them into one dict, something like:
>
>   ...
>   "colors": ("imp_colors", ["c", "cl", "col", ...])
>   ...
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to repeat function definitions less

2009-03-15 Thread alex goretoy
what is I just set
"colors": self.opt['arg_opts_options']['imp_colors']

then they are both pointing to the same place, correct?

-Alex Goretoy
http://www.goretoy.com



On Sun, Mar 15, 2009 at 11:16 PM, alex goretoy
wrote:

> i did this because this will read colors into a nested variable
>
> How would i make this work the way you suggest? I already have it working
> now :)
>
> Not able to set to dict value with setattr, how to do this too(sorry if off
> subject)?
>
> I can set it like this:
>
> for i in self.opt['properties'].keys():
> self.opt[i] =
> getattr(self.opt['properties_object'], i)
> but not like this:
> for i in self.opt['properties'].keys():
> setattr(self, opt[i],
> getattr(self.opt['properties_object'], i))
> -Alex Goretoy
> http://www.goretoy.com
>
>
>
> On Sun, Mar 15, 2009 at 6:41 PM, MRAB  wrote:
>
>> alex goretoy wrote:
>>
>>> ok now for the final result, i decided to split options out to a separate
>>> dict of lists, does this look right to every one, I currently have error
>>> somewhere else in my code so can't test this right now, Is this a good
>>> method to do this? or is there another option?
>>>
>>>  [snip]
>> First of all, *don't use "is" and "is not" to test for equality*; use "=="
>> and "!=".
>>
>> When you split the options out like that you get duplication.
>>
>> You have, for example:
>>
>>...
>>"colors": ["c", "cl", "col", ...]
>>...
>>
>> and:
>>
>>...
>>"imp_colors": ["c", "cl", "col", ...]
>>...
>>
>> Couldn't you put them into one dict, something like:
>>
>>   ...
>>   "colors": ("imp_colors", ["c", "cl", "col", ...])
>>   ...
>>
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: A request (was: how to repeat function definitions less

2009-03-16 Thread alex goretoy
sorry, I'll try to keep it cool
-Alex Goretoy
http://www.goretoy.com



On Mon, Mar 16, 2009 at 2:08 AM, Dennis Lee Bieber wrote:

> On Sun, 15 Mar 2009 23:18:54 -0500, alex goretoy
>  declaimed the following in
> gmane.comp.python.general:
>
> > what is I just set
> > "colors": self.opt['arg_opts_options']['imp_colors']
> >
> > then they are both pointing to the same place, correct?
> >
> > -Alex Goretoy
> > http://www.goretoy.com
> >
> >
>Could you PLEASE learn to trim quoted material -- especially...
> >
> > On Sun, Mar 15, 2009 at 11:16 PM, alex goretoy
> > wrote:
> >
>
> ... when replying to yourself!
>
>This (the message I'm replying too) has just FIVE lines of new text,
> but has a 4KB binary signature, and logs in as 180 lines in my news
> client!
>
>Many of your posts are actually exceeding the 500-line limit I've
> set in my client for down-load -- yet have nothing worthy of 500 lines!
> --
>WulfraedDennis Lee Bieber   KD6MOG
>wlfr...@ix.netcom.com   wulfr...@bestiaria.com
>HTTP://wlfraed.home.netcom.com/
>(Bestiaria Support Staff:   web-a...@bestiaria.com)
>HTTP://www.bestiaria.com/
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: print - bug or feature - concatenated format strings in a print statement

2009-03-16 Thread alex goretoy
>
>   print(10 + 20 % 7)
> a bug or a feature?

It is a feature
print ((10+20) % 7)

-Alex Goretoy
http://www.goretoy.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie question: How do I add elements to **kwargs in a function?

2009-03-16 Thread alex goretoy
I think you may need to do something like this in your code, this is what I
will be doing here shortly too

class peanutsdict(dict):
__slots__ = ['defaultZZz']
def __init__(self,default=None):
dict.__init(self)
self.default = default

def __getitem__(self,key):
if key in self:
return dict.__getitem__(self,key)
else:

return self.default

def get(self, key, *args):
if not args:
args = (self.default,)
return dict.get(self, key, *args)

def merge(self, other):
for key in other:
if key not in self:
self[key] = other[key]

-Alex Goretoy
http://www.goretoy.com
--
http://mail.python.org/mailman/listinfo/python-list


cool things you can do with dict

2009-03-16 Thread alex goretoy
I though this was cool so I'd post about it, its one of the recipes

class peanutsdict(dict):
def __init__(self,default=None):
dict.__init__(self)
self.default = default

def __getitem__(self,key):
if key in self:
return dict.__getitem__(self,key)
else:

return self.default

def get(self, key, *args):
if not args:
args = (self.default,)
return dict.get(self, key, *args)

def merge(self, other):
for key in other:
if key not in self:
self[key] = other[key]

a=peanutsdict()
a.b=peanutsdict()
a.b.c=peanutsdict()
a.x=1
a.b.y=2
a.b.c.z=3

>>> print a
{}
>>> print a.__dict__
{'default': None, 'x': 1, 'b': {}}
>>> print a.b.__dict__
{'default': None, 'y': 2, 'c': {}}
>>> print a.b.c.__dict__
{'default': None, 'z': 3}
>>> print a.b.c.z
3
>>> print a.b.c
{}
>>> a.b.b=peanutsdict()
>>> class pdict(dict): pass
...
>>> a.b.b.a=pdict()
>>> a.b.b
{}
>>> a.b.b.__dict__
{'default': None, 'a': {}}
>>> a.b.b.__dict__['a']
{}
>>> a.b.b.__dict__['a'].x=4
>>> a.b.b.__dict__['a'].x
4
>>> a.b.b.a.x
4

Anyone else know anymore cool pieces of code?


-Alex Goretoy
http://www.goretoy.com

Jean Anouilh  - "What you get free costs too much."
--
http://mail.python.org/mailman/listinfo/python-list


Re: having a function called after the constructor/__init__ is done

2009-03-16 Thread alex goretoy
__del__

I use it to close a mysql connection

-Alex Goretoy
http://www.goretoy.com

E. B. White  - "Be obscure clearly."

On Mon, Mar 16, 2009 at 10:11 PM, thomas.han...@gmail.com <
thomas.han...@gmail.com> wrote:

> Hi all,
>
> We've been breaking our heads over a good way of accomplishing an
> "on_load" event in our multitouch GUI frameowork PyMT.  We think we'd
> like to trigger an "on_load" event after a class is fully instantiated
> (or just a function call for simplicity, so you dont need to worry
> about our specific system).  This is so that if I make a subclass of
> some widget, I dont have to overwrite the __init__ method (use super,
> know the args, and pass them) everytime.  Maybe I just want to do some
> really basic stuff that doesn't really have anything to do with the
> parent class.
>
> Anyway.  My first attempt was to simply put a call to self.on_load at
> the end of the widget base class.  This doesn't work though, because,
> if I subclass it and do things after the call to super.__init__,
> on_load will be called before the constructor finishes (when the top
> most parent class __init__ finishes)
>
> We've sort of managed to achieve this by using a decorator that
> changes the __init__ function.  but even this doesnt seem like the
> best way to do this.  a) I now have to decorate every constructor i
> ever write. b) it seems impossible to make it so that it only happens
> once after the object is actually instantiated (since i have a
> decorator on all my constructors..each constructor in the inheritance
> line will call on_load once)
>
> Can I do something fancy with metaclasses here?  I think I could kind
> of do this by making all my classes use __new__, and then essentially
> use __init__ as what i want on_load to be...but that just seems really
> nasty and unpythonic.  not to speak about the confusion it would cause
> with people trying to figure out the library.
>
> So any ideas on how to get a function called on an object just after
> __init__ is done executing?
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda forms and scoping

2009-03-20 Thread alex goretoy
i looks at lambdas as unbound functions(or super function), in the case
above we create the functions in a list places it in memory unboud, once
binding a call to the memory address space it returns the value

it is basically same as doing this:
def f():
print "f"

a=f #unbound function, same as rename function
a() #bind call to address space

hope this helps

-Alex Goretoy
http://www.goretoy.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: newbie: precision question

2009-03-20 Thread alex goretoy
I think you are looking for this:

>>> (math.pi - (math.sqrt(math.pi)))**2
1.8745410610157363
>>>

simple, multiplication and division have a higher precedence over addition
and subtraction

-Alex Goretoy
http://www.goretoy.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is python worth learning as a second language?

2009-03-20 Thread alex goretoy
I've only read he subject and a few lines from other responses.

yes, it is worth learning. I came from PHP to Python. It's very powerful and
makes application development easier for me than in PHP and/or C#, but bash,
well that depends on the type of bash. It has a lot of diffent ways you can
use it too, so that adds to how powerful it is.

-Alex Goretoy
http://www.goretoy.com

Samuel Beckett  - "Birth was the death of him."

2009/3/20 Tomasz Rola 

> On Thu, 19 Mar 2009, Aahz wrote:
>
> > --===0027953262==
> >
> > In article <49b58b35$0$3548$426a7...@news.free.fr>,
> > Bruno Desthuilliers   wrote:
> > >Tomasz Rola a écrit :
> > >>
> > >> I may not be objective (tried Java, hated it after 6 years).
> > >
> > >Arf - only took me 6 months !-)
> >
> > That long?  It only took me six minutes.
>
> Guess what, there was a time when Java was looking quite promising.
> Especially in the field of distributed computing (which then meant not
> only high performance clusters). And computers were of more than one type,
> used other cpus than Intel, too.
>
> Maybe it's easier to ridicule Java now, when it has not met the
> expectations. But still, some people (better than I) have spent few
> years writing software and doing their research in Java. Sure, that was
> before Java had been nominated the common denominator of programming
> languages.
>
> Regards,
> Tomasz Rola
>
> --
> ** A C programmer asked whether computer had Buddha's nature.  **
> ** As the answer, master did "rm -rif" on the programmer's home**
> ** directory. And then the C programmer became enlightened...  **
> ** **
> ** Tomasz Rola  mailto:tomasz_r...@bigfoot.com **
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >